1<?php
2/**
3 * Copyright (C) 2017-2019 thirty bees
4 * Copyright (C) 2007-2016 PrestaShop SA
5 *
6 * thirty bees is an extension to the PrestaShop software by PrestaShop SA.
7 *
8 * NOTICE OF LICENSE
9 *
10 * This source file is subject to the Academic Free License (AFL 3.0)
11 * that is bundled with this package in the file LICENSE.md.
12 * It is also available through the world-wide-web at this URL:
13 * https://opensource.org/licenses/afl-3.0.php
14 * If you did not receive a copy of the license and are unable to
15 * obtain it through the world-wide-web, please send an email
16 * to license@thirtybees.com so we can send you a copy immediately.
17 *
18 * @author    thirty bees <modules@thirtybees.com>
19 * @author    PrestaShop SA <contact@prestashop.com>
20 * @copyright 2017-2019 thirty bees
21 * @copyright 2007-2016 PrestaShop SA
22 * @license   Academic Free License (AFL 3.0)
23 * PrestaShop is an internationally registered trademark of PrestaShop SA.
24 */
25
26if (!defined('_TB_VERSION_')) {
27    exit;
28}
29
30/**
31 * Class BankWire
32 */
33class BankWire extends PaymentModule
34{
35    // @codingStandardsIgnoreStart
36    /** @var string $details */
37    public $details;
38    /** @var string $owner */
39    public $owner;
40    /** @var string $address */
41    public $address;
42    /** @var array $extra_mail_vars */
43    public $extra_mail_vars;
44    /** @var string $moduleHtml */
45    protected $moduleHtml = '';
46    /** @var array $postErrors */
47    protected $postErrors = [];
48    // @codingStandarsdIgnoreEnd
49
50    /**
51     * BankWire constructor.
52     *
53     * @throws PrestaShopException
54     */
55    public function __construct()
56    {
57        $this->name = 'bankwire';
58        $this->tab = 'payments_gateways';
59        $this->version = '2.0.8';
60        $this->author = 'thirty bees';
61        $this->need_instance = 1;
62        $this->controllers = ['payment', 'validation'];
63        $this->is_eu_compatible = 1;
64
65        $this->currencies = true;
66        $this->currencies_mode = 'checkbox';
67
68        $config = Configuration::getMultiple(['BANK_WIRE_DETAILS', 'BANK_WIRE_OWNER', 'BANK_WIRE_ADDRESS']);
69        if (!empty($config['BANK_WIRE_OWNER'])) {
70            $this->owner = $config['BANK_WIRE_OWNER'];
71        }
72        if (!empty($config['BANK_WIRE_DETAILS'])) {
73            $this->details = $config['BANK_WIRE_DETAILS'];
74        }
75        if (!empty($config['BANK_WIRE_ADDRESS'])) {
76            $this->address = $config['BANK_WIRE_ADDRESS'];
77        }
78
79        $this->bootstrap = true;
80        parent::__construct();
81
82        $this->displayName = $this->l('Bankwire Module');
83        $this->description = $this->l('Accept payments for your products via bank wire transfer.');
84        $this->tb_versions_compliancy = '> 1.0.0';
85        $this->tb_min_version = '1.0.0';
86        $this->confirmUninstall = $this->l('Are you sure about removing these details?');
87
88        if (!isset($this->owner) || !isset($this->details) || !isset($this->address)) {
89            $this->warning = $this->l('Account owner and account details must be configured before using this module.');
90        }
91        $paymentCurrencies = Currency::checkPaymentCurrencies($this->id);
92        if (!is_array($paymentCurrencies) || !count($paymentCurrencies)) {
93            $this->warning = $this->l('No currency has been set for this module.');
94        }
95
96        $this->extra_mail_vars = [
97            '{bankwire_owner}'   => Configuration::get('BANK_WIRE_OWNER'),
98            '{bankwire_details}' => nl2br(Configuration::get('BANK_WIRE_DETAILS')),
99            '{bankwire_address}' => nl2br(Configuration::get('BANK_WIRE_ADDRESS')),
100        ];
101    }
102
103    /**
104     * @return bool
105     * @throws PrestaShopException
106     */
107    public function install()
108    {
109        if (!parent::install()) {
110            return false;
111        }
112
113        $this->registerHook('displayPayment');
114        $this->registerHook('displayPaymentEU');
115        $this->registerHook('paymentReturn');
116
117        return true;
118    }
119
120    /**
121     * @return bool
122     * @throws PrestaShopDatabaseException
123     * @throws PrestaShopException
124     */
125    public function uninstall()
126    {
127        if (!Configuration::deleteByName('BANK_WIRE_DETAILS')
128            || !Configuration::deleteByName('BANK_WIRE_OWNER')
129            || !Configuration::deleteByName('BANK_WIRE_ADDRESS')
130            || !parent::uninstall()
131        ) {
132            return false;
133        }
134
135        return true;
136    }
137
138    /**
139     * @return string
140     * @throws Exception
141     * @throws PrestaShopDatabaseException
142     * @throws PrestaShopException
143     * @throws SmartyException
144     */
145    public function getContent()
146    {
147        if (Tools::isSubmit('btnSubmit')) {
148            $this->postValidation();
149            if (!is_array($this->postErrors) || !count($this->postErrors)) {
150                $this->postProcess();
151            } else {
152                foreach ($this->postErrors as $err) {
153                    $this->moduleHtml .= $this->displayError($err);
154                }
155            }
156        } else {
157            $this->moduleHtml .= '<br />';
158        }
159
160        $this->moduleHtml .= $this->displayBankwire();
161        $this->moduleHtml .= $this->renderForm();
162
163        return $this->moduleHtml;
164    }
165
166    /**
167     * @return string
168     * @throws Exception
169     * @throws PrestaShopException
170     * @throws SmartyException
171     */
172    public function displayBankwire()
173    {
174        return $this->display(__FILE__, 'infos.tpl');
175    }
176
177    /**
178     * @return string
179     * @throws Exception
180     * @throws PrestaShopDatabaseException
181     * @throws PrestaShopException
182     * @throws SmartyException
183     */
184    public function renderForm()
185    {
186        $formFields = [
187            'form' => [
188                'legend' => [
189                    'title' => $this->l('Contact details'),
190                    'icon'  => 'icon-envelope',
191                ],
192                'input'  => [
193                    [
194                        'type'     => 'text',
195                        'label'    => $this->l('Account owner'),
196                        'name'     => 'BANK_WIRE_OWNER',
197                        'required' => true,
198                    ],
199                    [
200                        'type'     => 'textarea',
201                        'label'    => $this->l('Details'),
202                        'name'     => 'BANK_WIRE_DETAILS',
203                        'desc'     => $this->l('Such as bank branch, IBAN number, BIC, etc.'),
204                        'required' => true,
205                    ],
206                    [
207                        'type'     => 'textarea',
208                        'label'    => $this->l('Bank address'),
209                        'name'     => 'BANK_WIRE_ADDRESS',
210                        'required' => true,
211                    ],
212                ],
213                'submit' => [
214                    'title' => $this->l('Save'),
215                ],
216            ],
217        ];
218
219        $helper = new HelperForm();
220        $helper->show_toolbar = false;
221        $helper->table = $this->table;
222        $lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
223        $helper->default_form_language = $lang->id;
224        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
225        $helper->identifier = $this->identifier;
226        $helper->submit_action = 'btnSubmit';
227        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
228        $helper->token = Tools::getAdminTokenLite('AdminModules');
229        $helper->tpl_vars = [
230            'fields_value' => $this->getConfigFieldsValues(),
231            'languages'    => $this->context->controller->getLanguages(),
232            'id_language'  => $this->context->language->id,
233        ];
234
235        return $helper->generateForm([$formFields]);
236    }
237
238    /**
239     * Get the configuration field values
240     *
241     * @return array
242     * @throws PrestaShopException
243     */
244    public function getConfigFieldsValues()
245    {
246        return [
247            'BANK_WIRE_DETAILS' => Tools::getValue('BANK_WIRE_DETAILS', Configuration::get('BANK_WIRE_DETAILS')),
248            'BANK_WIRE_OWNER'   => Tools::getValue('BANK_WIRE_OWNER', Configuration::get('BANK_WIRE_OWNER')),
249            'BANK_WIRE_ADDRESS' => Tools::getValue('BANK_WIRE_ADDRESS', Configuration::get('BANK_WIRE_ADDRESS')),
250        ];
251    }
252
253    /**
254     * @return string
255     * @throws Exception
256     * @throws PrestaShopException
257     * @throws SmartyException
258     */
259    public function hookPayment()
260    {
261        if (!$this->active) {
262            return '';
263        }
264
265        $this->smarty->assign(
266            [
267                'this_path'     => $this->_path,
268                'this_path_bw'  => $this->_path,
269                'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/',
270            ]
271        );
272
273        return $this->display(__FILE__, 'payment.tpl');
274    }
275
276    /**
277     * @return array|string
278     * @throws PrestaShopException
279     */
280    public function hookDisplayPaymentEU()
281    {
282        if (!$this->active) {
283            return '';
284        }
285
286        return [
287            'cta_text' => $this->l('Pay by Bank Wire'),
288            'logo'     => Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/bankwire.jpg'),
289            'action'   => $this->context->link->getModuleLink($this->name, 'validation', [], true),
290        ];
291    }
292
293    /**
294     * @param array $params
295     *
296     * @return string
297     * @throws Exception
298     * @throws PrestaShopException
299     * @throws SmartyException
300     */
301    public function hookPaymentReturn($params)
302    {
303        if (!isset($params) || !isset($params['objOrder']) || !$params['objOrder'] instanceof Order || !$this->active) {
304            return '';
305        }
306
307        try {
308            $state = $params['objOrder']->getCurrentState();
309            if (in_array($state, [Configuration::get('PS_OS_BANKWIRE'), Configuration::get('PS_OS_OUTOFSTOCK'), Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')])) {
310                $this->smarty->assign(
311                    [
312                        'total_to_pay'    => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false),
313                        'bankwireDetails' => nl2br($this->details),
314                        'bankwireAddress' => nl2br($this->address),
315                        'bankwireOwner'   => $this->owner,
316                        'status'          => 'ok',
317                        'id_order'        => $params['objOrder']->id,
318                    ]
319                );
320                if (isset($params['objOrder']->reference) && !empty($params['objOrder']->reference)) {
321                    $this->smarty->assign('reference', $params['objOrder']->reference);
322                }
323            } else {
324                $this->smarty->assign('status', 'failed');
325            }
326        } catch (PrestaShopException $e) {
327            Logger::addLog("Bankwire module error: {$e->getMessage()}");
328
329            return '';
330        }
331
332        return $this->display(__FILE__, 'payment_return.tpl');
333    }
334
335    /**
336     * Post process
337     *
338     * @throws PrestaShopException
339     */
340    protected function postProcess()
341    {
342        if (Tools::isSubmit('btnSubmit')) {
343            Configuration::updateValue('BANK_WIRE_DETAILS', Tools::getValue('BANK_WIRE_DETAILS'));
344            Configuration::updateValue('BANK_WIRE_OWNER', Tools::getValue('BANK_WIRE_OWNER'));
345            Configuration::updateValue('BANK_WIRE_ADDRESS', Tools::getValue('BANK_WIRE_ADDRESS'));
346        }
347        $this->moduleHtml .= $this->displayConfirmation($this->l('Settings updated'));
348    }
349
350    /**
351     * Post validation
352     */
353    protected function postValidation()
354    {
355        if (Tools::isSubmit('btnSubmit')) {
356            if (!Tools::getValue('BANK_WIRE_DETAILS')) {
357                $this->postErrors[] = $this->l('Account details are required.');
358            } elseif (!Tools::getValue('BANK_WIRE_OWNER')) {
359                $this->postErrors[] = $this->l('Account owner is required.');
360            }
361        }
362    }
363}
364