<?php
/**
* 2007-2020 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2020 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

use PrestaShop\PrestaShop\Core\Payment\PaymentOption;

if (!defined('_PS_VERSION_')) {
    exit;
}

class Trustpay extends PaymentModule
{
    protected $config_form = false;

    protected $currency_code;
    protected $shop_url;
    protected $url_success;
    protected $url_error;
    protected $url_cancel;
    protected $url_notification;



    public function __construct()
    {
        $this->name = 'trustpay';
        $this->tab = 'payments_gateways';
        $this->version = '1.2.1';
        $this->author = 'finby';
        $this->need_instance = 0;

        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('finby');
        $this->description = $this->l('Maximize business, reduce hassle with finby’s advanced card acquiring and business account services');

        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);

        $this->currency_code = $this->getCartCurrencyCode();
        
        $this->shop_url = Tools::getShopDomainSsl(true, true).__PS_BASE_URI__;
        $this->url_success = $this->context->link->getModuleLink('trustpay', 'success', [], true);
        $this->url_error = $this->context->link->getModuleLink('trustpay', 'error', [], true);
        $this->url_cancel = $this->context->link->getModuleLink('trustpay', 'cancel', [], true);
        $this->url_notification = $this->context->link->getModuleLink('trustpay', 'notification', [], true);
        
        /**CURRENCY RESTRICTIONS**/
        $this->currencies_mode = 'checkbox';
    }

    public function install()
    {
        Configuration::updateValue('TRUSTPAY_MODE_CC', 3);
        Configuration::updateValue('TRUSTPAY_MODE_BANK', 3);
        

        /* Copy e-mail templates */
        $this->moveOverriteFiles();

        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_AWAITING');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_AWAITING')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Čakanie na platbu finby';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Čekání na platbu finby';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Oczekiwanie na finby płatności';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Várakozás fizetési finby';
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Awaiting finby payment';
                } else {
                    $orderState->name[$language['id_lang']] = 'Awaiting finby payment';
                }
            }
            $orderState->send_email = false;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_awaiting';
            }

            $orderState->color = '#4169E1';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-awaiting.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_AWAITING', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}
        
        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_CARDWAITING');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_CARDWAITING')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Čakanie na platbu kartou';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Čekání na platbu kartou';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Oczekiwanie na wypłatę kartou';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Vár card fizetés';    
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Awaiting card payment';
                } else {
                    $orderState->name[$language['id_lang']] = 'Awaiting card payment';
                }
            }
            $orderState->send_email = false;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_cardwaiting';
            }

            $orderState->color = '#4169E1';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-cardwaiting.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_CARDWAITING', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}

        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_PENDING');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_PENDING')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Čakanie na offline platbu finby';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Čekání na offline platbu finby';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Oczekiwanie na wypłatę nieaktywny finby';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Vár finby offline fizetési';
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Awaiting finby offline payment';
                } else {
                    $orderState->name[$language['id_lang']] = 'Awaiting finby offline payment';
                }
            }
            $orderState->send_email = false;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_pending';
            }

            $orderState->color = '#4169E1';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-pending.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_PENDING', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}

        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_ANNOUNCED');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_ANNOUNCED')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Finby platba oznámená';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Finby platba oznámena';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Płatność finby ogłosił';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Finby fizetési bejelentette';
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Finby payment announced';
                } else {
                    $orderState->name[$language['id_lang']] = 'Finby payment announced';
                }
            }
            $orderState->send_email = true;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_announced';
            }

            $orderState->color = '#BD6211';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-announced.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_ANNOUNCED', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}

        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_AUTHORIZED');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_AUTHORIZED')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Finby platba autorizovaná';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Finby platba autorizována';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Płatność finby upoważniony';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Finby engedélyezett fizetési';
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Finby payment authorized';
                } else {
                    $orderState->name[$language['id_lang']] = 'Finby payment authorized';
                }
            }
            $orderState->send_email = true;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_authorized';
            }

            $orderState->color = '#1B8E6C';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-authorized.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_AUTHORIZED', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}

        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_PROCESSING');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_PROCESSING')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Finby platba sa spracováva';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Finby platba se zpracováva';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Płatność finby przetwarza';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Finby fizetés feldolgozás';
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Finby payment is processing';
                } else {
                    $orderState->name[$language['id_lang']] = 'Finby payment is processing';
                }
            }
            $orderState->send_email = true;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_processing';
            }

            $orderState->color = '#1B8E6C';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-processing.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_PROCESSING', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}

        /* Create a new OrderState */
        $id_order_state = Configuration::get('TRUSTPAY_OS_AUTHORIZEDONLY');
        if (!$id_order_state) {
            $orderState = new OrderState();
        } else {
            $orderState = new OrderState((int)$id_order_state);
        }
        
        //if (!Configuration::get('TRUSTPAY_OS_AUTHORIZEDONLY')) {
            //$orderState = new OrderState();
            $orderState->name = array();
            foreach (Language::getLanguages() as $language) {
                if (strtolower($language['iso_code']) == 'sk') {
                    $orderState->name[$language['id_lang']] = 'Platba kartou autorizovaná';
                } elseif (strtolower($language['iso_code']) == 'cs') {
                    $orderState->name[$language['id_lang']] = 'Platba kartou autorizována';
                } elseif (strtolower($language['iso_code']) == 'pl') {
                    $orderState->name[$language['id_lang']] = 'Płatność kartą upoważniony';
                } elseif (strtolower($language['iso_code']) == 'hu') {
                    $orderState->name[$language['id_lang']] = 'Bankkártyás fizetés engedélyezett';
                } elseif (strtolower($language['iso_code']) == 'en') {
                    $orderState->name[$language['id_lang']] = 'Card payment authorized';
                } else {
                    $orderState->name[$language['id_lang']] = 'Card payment authorized';
                }
            }
            $orderState->send_email = true;

            $orderState->template = array();
            foreach (Language::getLanguages() as $language) {
                $orderState->template[$language['id_lang']] = 'trustpay_authorizedonly';
            }

            $orderState->color = '#BD6211';
            $orderState->hidden = false;
            $orderState->delivery = false;
            $orderState->logable = false;
            $orderState->module_name = $this->name;
            $orderState->invoice = false;
            
            if (!$id_order_state) {
                if ($orderState->add()) {
                    copy(dirname(__FILE__).'/views/img/os/'.$this->name.'-authorizedonly.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
                }
                Configuration::updateValue('TRUSTPAY_OS_AUTHORIZEDONLY', (int)$orderState->id);
            } else {
                $orderState->update();
            }
        //}


        /* Module statuses only - Start */
        Configuration::updateValue('TRUSTPAY_STATUS_AWAITING', Configuration::get('TRUSTPAY_OS_AWAITING'));
        Configuration::updateValue('TRUSTPAY_STATUS_CARDWAITING', Configuration::get('TRUSTPAY_OS_CARDWAITING'));
        Configuration::updateValue('TRUSTPAY_STATUS_PENDING', Configuration::get('TRUSTPAY_OS_PENDING'));
        Configuration::updateValue('TRUSTPAY_STATUS_ANNOUNCED', Configuration::get('TRUSTPAY_OS_ANNOUNCED'));
        Configuration::updateValue('TRUSTPAY_STATUS_AUTHORIZED', Configuration::get('TRUSTPAY_OS_AUTHORIZED'));
        Configuration::updateValue('TRUSTPAY_STATUS_PROCESSING', Configuration::get('TRUSTPAY_OS_PROCESSING'));
        Configuration::updateValue('TRUSTPAY_STATUS_AUTHORIZEDONLY', Configuration::get('TRUSTPAY_OS_AUTHORIZEDONLY'));
        Configuration::updateValue('TRUSTPAY_STATUS_OK', Configuration::get('PS_OS_PAYMENT'));
        Configuration::updateValue('TRUSTPAY_STATUS_FAIL', Configuration::get('PS_OS_ERROR'));
        /* Module statuses only - End */

        return parent::install() &&
            //$this->registerHook('header') &&
            $this->registerHook('displayBackOfficeHeader') &&
            //$this->registerHook('payment') && // comment finby
            $this->registerHook('paymentReturn') &&
            $this->registerHook('displayHeader') &&
            //$this->registerHook('displayPayment') && // comment finby
            $this->registerHook('paymentOptions') &&
            $this->registerHook('displayPaymentReturn');
    }

    public function uninstall()
    {
        Configuration::deleteByName('TRUSTPAY_MODE');

        return parent::uninstall();
    }

    /******** COPY E-MAIL TEMPLATES INTO /mails/ FOLDER ********/
    private function moveOverriteFiles()
    {
         foreach (Language::getLanguages() as $language) {
             if (strtolower($language['iso_code']) == 'sk') {

                if (!copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_announced.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_announced.html') 
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_announced.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_announced.txt') 
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_authorized.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_authorized.html')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_authorized.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_authorized.txt')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_pending.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_pending.html')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_pending.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_pending.txt')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_processing.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_processing.html')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_processing.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_processing.txt')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_authorizedonly.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_authorizedonly.html')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_authorizedonly.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_authorizedonly.txt')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_cardwaiting.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_cardwaiting.html')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_cardwaiting.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_cardwaiting.txt')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_awaiting.html',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_awaiting.html')
                        || !copy(dirname(__FILE__).'/mails/sk/'.$this->name.'_awaiting.txt',_PS_ROOT_DIR_ .'/mails/sk/'.$this->name.'_awaiting.txt')) {
                    return false;
                }

             } elseif (strtolower($language['iso_code']) == 'cs') {

                if (!copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_announced.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_announced.html') 
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_announced.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_announced.txt') 
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_authorized.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_authorized.html')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_authorized.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_authorized.txt')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_pending.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_pending.html')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_pending.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_pending.txt')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_processing.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_processing.html')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_processing.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_processing.txt')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_authorizedonly.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_authorizedonly.html')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_authorizedonly.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_authorizedonly.txt')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_cardwaiting.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_cardwaiting.html')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_cardwaiting.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_cardwaiting.txt')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_awaiting.html',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_awaiting.html')
                        || !copy(dirname(__FILE__).'/mails/cs/'.$this->name.'_awaiting.txt',_PS_ROOT_DIR_ .'/mails/cs/'.$this->name.'_awaiting.txt')) {
                    return false;
                }

             } elseif (strtolower($language['iso_code']) == 'en') {

                if (!copy(dirname(__FILE__).'/mails/en/'.$this->name.'_announced.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_announced.html') 
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_announced.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_announced.txt') 
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorized.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorized.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorized.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorized.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_pending.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_pending.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_pending.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_pending.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_processing.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_processing.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_processing.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_processing.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorizedonly.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorizedonly.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorizedonly.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorizedonly.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_cardwaiting.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_cardwaiting.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_cardwaiting.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_cardwaiting.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_awaiting.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_awaiting.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_awaiting.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_awaiting.txt')) {
                    return false;
                }

             } else {

                if (!copy(dirname(__FILE__).'/mails/en/'.$this->name.'_announced.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_announced.html') 
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_announced.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_announced.txt') 
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorized.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorized.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorized.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorized.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_pending.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_pending.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_pending.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_pending.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_processing.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_processing.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_processing.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_processing.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorizedonly.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorizedonly.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_authorizedonly.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_authorizedonly.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_cardwaiting.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_cardwaiting.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_cardwaiting.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_cardwaiting.txt')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_awaiting.html',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_awaiting.html')
                        || !copy(dirname(__FILE__).'/mails/en/'.$this->name.'_awaiting.txt',_PS_ROOT_DIR_ .'/mails/en/'.$this->name.'_awaiting.txt')) {
                    return false;
                }

             }
         }

        return true;
    }

    public function getContent()
    {
        if (((bool)Tools::isSubmit('submitTrustpayModule')) == true) {
            $this->postProcess();
        }

        $this->context->smarty->assign('module_dir', $this->_path);

        return $this->renderForm();
    }

    protected function renderForm()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitTrustpayModule';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
            .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigForm()));
    }

    public function hookPaymentOptions($params)
    {
        if (!$this->active) {
            return;
        }

        $allowed_card_currency = false;
        
        $allowed = array('AUD',
                'CAD',
                'CZK',
                'DKK',
                'EUR',
                'GBP',
                'HRK',
                'HUF',
                'JPY',
                'NOK',
                'PLN',
                'RON',
                'SEK',
                'USD',
            );

        if (!in_array($this->currency_code, $allowed)) {
            return;
        }
        else {
            $allowed_card_currency = true;
        }

        $allowed_currency = false;
        $currency = new Currency($this->context->cookie->id_currency);
        $iso_code = Configuration::get('TRUSTPAY_CURRENCY');

        if ($iso_code == $currency->iso_code) {
            $allowed_currency = true;
        }

        $this->context->smarty->assign(array(
            'module_dir' => $this->_path,
            'tpibt_url' => $this->getTpibtUrl(),
            'tpcp_url' => $this->getTpcpUrl(),
            'shop_url' => $this->shop_url,
            'disable_popup' => (int) Configuration::get('TRUSTPAY_DISABLE_POPUP'),
            'view_type' => Configuration::get('TRUSTPAY_VIEW_TYPE'),
            'TRUSTPAY_MODE_BANK' => Configuration::get('TRUSTPAY_MODE_BANK'),
            'TRUSTPAY_MODE_CC' => Configuration::get('TRUSTPAY_MODE_CC'),
            'TRUSTPAY_LOGOS_BANK' => Configuration::get('TRUSTPAY_LOGOS_BANK'),
            'TRUSTPAY_LOGOS_CC' => Configuration::get('TRUSTPAY_LOGOS_CC'),
            'allowed_currency' => $allowed_currency,
            'allowed_card_currency' => $allowed_card_currency,
        ));
        
        $bank = Configuration::get('TRUSTPAY_MODE_BANK');
        $cc = Configuration::get('TRUSTPAY_MODE_CC');

        $payment_options = array();

        if (($bank == 3) && $allowed_currency) {
            $payment_options[] = $this->getTrustpayBwPaymentOption();            
        }

        if (($cc == 3) && $allowed_card_currency) {
            $payment_options[] = $this->getTrustpayCcPaymentOption();
        }

        return $payment_options;
    }

    public function getTrustpayBwPaymentOption()
    {
        $disable_popup = (int) Configuration::get('TRUSTPAY_DISABLE_POPUP');

        if ($disable_popup == 0) {
            $PaymentOption = new PaymentOption();
            $PaymentOption->setCallToActionText($this->l('finby').' '.$this->l('(Online bank and internal transfers)'))
                ->setModuleName('truspay_bw')
                ->setAction('javascript:void(0);')
                ->setAdditionalInformation($this->context->smarty->fetch('module:'.$this->name.'/views/templates/hook/checkout_bw.tpl'));
            return $PaymentOption;
        } else {
            $PaymentOption = new PaymentOption();
            $PaymentOption->setCallToActionText($this->l('finby').' '.$this->l('(Online bank and internal transfers)'))
                ->setModuleName('truspay_bw')
                ->setAction($this->context->link->getModuleLink($this->name, 'payment', array('type' => 'wire'), true))
                ->setAdditionalInformation($this->context->smarty->fetch('module:'.$this->name.'/views/templates/hook/checkout_bw.tpl'));
            return $PaymentOption;
        }
    }

    public function getTrustpayCcPaymentOption()
    {
        $disable_popup = (int) Configuration::get('TRUSTPAY_DISABLE_POPUP');

        if ($disable_popup == 0) {
            $PaymentOption = new PaymentOption();
            $PaymentOption->setCallToActionText($this->l('finby').' '.$this->l('(Card payment)'))
                ->setAction('javascript:void(0);')
                ->setModuleName('trustpay_cc')
                ->setAdditionalInformation($this->context->smarty->fetch('module:'.$this->name.'/views/templates/hook/checkout_cc.tpl'));

            return $PaymentOption;
        } else {
            $PaymentOption = new PaymentOption();
            $PaymentOption->setCallToActionText($this->l('finby').' '.$this->l('(Card payment)'))
                ->setAction($this->context->link->getModuleLink($this->name, 'payment', array('type' => 'card'), true))
                ->setModuleName('trustpay_cc')
                ->setAdditionalInformation($this->context->smarty->fetch('module:'.$this->name.'/views/templates/hook/checkout_cc.tpl'));

            return $PaymentOption;
        }

    }

    protected function getConfigForm()
    {
        $statuses = OrderState::getOrderStates($this->context->language->id);

        /* AWAITING status */
        $statuses_awaiting_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_awaiting) {
            $statuses_awaiting_list[] = array(
                'id' => $status_awaiting['id_order_state'],
                'name' => $status_awaiting['id_order_state'] == Configuration::get('TRUSTPAY_OS_AWAITING') ? $status_awaiting['name'].' &nbsp; [*]' : $status_awaiting['name'],
            );
        }

        /* CARDWAITING status */
        $statuses_cardwaiting_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_cardwaiting) {
            $statuses_cardwaiting_list[] = array(
                'id' => $status_cardwaiting['id_order_state'],
                'name' => $status_cardwaiting['id_order_state'] == Configuration::get('TRUSTPAY_OS_CARDWAITING') ? $status_cardwaiting['name'].' &nbsp; [*]' : $status_cardwaiting['name'],
            );
        }

        /* PENDING status */
        $statuses_pending_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_pending) {
            $statuses_pending_list[] = array(
                'id' => $status_pending['id_order_state'],
                'name' => $status_pending['id_order_state'] == Configuration::get('TRUSTPAY_OS_PENDING') ? $status_pending['name'].' &nbsp; [*]' : $status_pending['name'],
            );
        }

        /* ANNOUNCED status */
        $statuses_announced_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_announced) {
            $statuses_announced_list[] = array(
                'id' => $status_announced['id_order_state'],
                'name' => $status_announced['id_order_state'] == Configuration::get('TRUSTPAY_OS_ANNOUNCED') ? $status_announced['name'].' &nbsp; [*]' : $status_announced['name'],
            );
        }

        /* AUTHORIZED status */
        $statuses_authorized_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_authorized) {
            $statuses_authorized_list[] = array(
                'id' => $status_authorized['id_order_state'],
                'name' => $status_authorized['id_order_state'] == Configuration::get('TRUSTPAY_OS_AUTHORIZED') ? $status_authorized['name'].' &nbsp; [*]' : $status_authorized['name'],
            );
        }

        /* PROCESSING status */
        $statuses_processing_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_processing) {
            $statuses_processing_list[] = array(
                'id' => $status_processing['id_order_state'],
                'name' => $status_processing['id_order_state'] == Configuration::get('TRUSTPAY_OS_PROCESSING') ? $status_processing['name'].' &nbsp; [*]' : $status_processing['name'],
            );
        }

        /* AUTHORIZEDONLY status */
        $statuses_authorizedonly_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_authorizedonly) {
            $statuses_authorizedonly_list[] = array(
                'id' => $status_authorizedonly['id_order_state'],
                'name' => $status_authorizedonly['id_order_state'] == Configuration::get('TRUSTPAY_OS_AUTHORIZEDONLY') ? $status_authorizedonly['name'].' &nbsp; [*]' : $status_authorizedonly['name'],
            );
        }

        /* PAYMENT RECEIVED status */
        $statuses_ok_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status) {
            $statuses_ok_list[] = array(
                'id' => $status['id_order_state'],
                'name' => $status['id_order_state'] == 2 ? $status['name'].' &nbsp; [*]' : $status['name'],
            );
        }

        /* PAYMENT ERROR status */
        $statuses_fail_list = array(
            0 => array(
                'id' => 0,
                'name' => $this->l('-- select an order status --'),
            )
        );

        foreach ($statuses as $status_fail) {
            $statuses_fail_list[] = array(
                'id' => $status_fail['id_order_state'],
                'name' => $status_fail['id_order_state'] == 8 ? $status_fail['name'].' &nbsp; [*]' : $status_fail['name'],
            );
        }


        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Settings'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'radio',
                        'label' => $this->l('Online bank & internal transfers'),
                        'name' => 'TRUSTPAY_MODE_BANK',
                        'values' => array(
                            array(
                                'value' => 3,
                                'id' => 'banking_enabled_live',
                                'label' => $this->l('Enable - Live (Finby Merchant Portal)')
                            ),
                            array(
                                'value' => 4,
                                'id' => 'banking_disabled',
                                'label' => $this->l('Disable')
                            ),
                        ),
                        'desc' => $this->l('Enable this option only if you have an agreement with finby for domestic bank wire payments. Otherwise an error message will be shown to all customers. Please ask finby company to enable bankwire/transfer payments for you.')
                    ),
                    array(
                        'type' => 'radio',
                        'label' => $this->l('Card payments'),
                        'name' => 'TRUSTPAY_MODE_CC',
                        'values' => array(
                            array(
                                'value' => 3,
                                'id' => 'cc_enabled_live',
                                'label' => $this->l('Enable - Live (Finby Merchant Portal)')
                            ),
                            array(
                                'value' => 4,
                                'id' => 'cc_disabled',
                                'label' => $this->l('Disable')
                            ),
                        ),
                        'desc' => $this->l('Enable this option only if you have an agreement with finby for card payments. Otherwise an error message will be shown to all customers. Please ask finby company to enable card payments for you.')
                    ),
                    array(
                        'col' => 3,
                        'type' => 'text',
                        'name' => 'TRUSTPAY_AID',
                        'label' => $this->l('AID (Account ID)'),
                    ),
                    array(
                        'type' => 'text',
                        'name' => 'TRUSTPAY_SECRET_KEY',
                        'label' => $this->l('Secret key'),
                        'desc' => $this->l('For testing purposes please use your testing credentials.')
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Safe mode'),
                        'name' => 'TRUSTPAY_DISABLE_POPUP',
                        'values' => array(
                            array(
                                'id' => 'TRUSTPAY_DISABLE_POPUP_on',
                                'value' => 1
                            ),
                            array(
                                'id' => 'TRUSTPAY_DISABLE_POPUP_off',
                                'value' => 0
                            )
                        ),
                        'desc' => $this->l('In case you are using any custom OPC module')

                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('View Type'),
                        'name' => 'TRUSTPAY_VIEW_TYPE',
                        'required' => true,
                        'options' => array(
                            'query' => array(
                                array('id' => 'popup', 'name' => $this->l('Popup')),
                                array('id' => 'redirect', 'name' => $this->l('Redirect')),
                            ),
                            'id' => 'id',
                            'name' => 'name',
                        ),
                        'desc' => $this->l('View Type Popup or Redirect')
                        
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Account currency type'),
                        'name' => 'TRUSTPAY_CURRENCY',
                        'required' => true,
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => array(
                                array('id' => '', 'name' => $this->l('-- choose (required) --')),
                                array('id' => 'EUR', 'name' => $this->l('Euro')),
                                array('id' => 'CZK', 'name' => $this->l('Czech koruna')),
                            ),
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Awaiting payment order status'),
                        'hint' => $this->l('Default payment status is "Awaiting finby payment".'),
                        'name' => 'TRUSTPAY_STATUS_AWAITING',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_AWAITING'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_awaiting_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Awaiting card payment order status'),
                        'hint' => $this->l('Default payment status is "Awaiting Card payment".'),
                        'name' => 'TRUSTPAY_STATUS_CARDWAITING',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_CARDWAITING'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_cardwaiting_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Awaiting offline payment order status'),
                        'hint' => $this->l('Default payment status is "Awaiting finby offline payment".'),
                        'name' => 'TRUSTPAY_STATUS_PENDING',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_PENDING'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_pending_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Announced payment order status'),
                        'hint' => $this->l('Default payment status is "finby payment announced".'),
                        'name' => 'TRUSTPAY_STATUS_ANNOUNCED',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_ANNOUNCED'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_announced_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Authorized payment order status'),
                        'hint' => $this->l('Default payment status is "finby payment authorized".'),
                        'name' => 'TRUSTPAY_STATUS_AUTHORIZED',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_AUTHORIZED'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_authorized_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Processing payment order status'),
                        'hint' => $this->l('Default payment status is "finby payment is processing".'),
                        'name' => 'TRUSTPAY_STATUS_PROCESSING',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_PROCESSING'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_processing_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Card authorized payment order status'),
                        'hint' => $this->l('Default payment status is "Card payment authorized".'),
                        'name' => 'TRUSTPAY_STATUS_AUTHORIZEDONLY',
                        'required' => true,
                        'default_value' => Configuration::get('TRUSTPAY_OS_AUTHORIZEDONLY'),
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_authorizedonly_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    /* Build-in payment states */
                    array(
                        'type' => 'select',
                        'label' => $this->l('Success payment order status'),
                        'hint' => $this->l('Default payment status is "Payment accepted".'),
                        'name' => 'TRUSTPAY_STATUS_OK',
                        'required' => true,
                        'default_value' => '2',
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_ok_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Error payment order status'),
                        'hint' => $this->l('Default payment status is "Payment error".'),
                        'name' => 'TRUSTPAY_STATUS_FAIL',
                        'required' => true,
                        'default_value' => '8',
                        'class' => 'fixed-width-xxl',
                        'options' => array(
                            'query' => $statuses_fail_list,
                            'id' => 'id',
                            'name' => 'name',
                        ),
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Show Online bank & internal transfers logos'),
                        'name' => 'TRUSTPAY_LOGOS_BANK',
                        'values' => array(
                            array(
                                'id' => 'TRUSTPAY_LOGOS_BANK_on',
                                'value' => 1,
                            ),
                            array(
                                'id' => 'TRUSTPAY_LOGOS_BANK_off',
                                'value' => 0,
                            ),
                        ),
                        'desc' => '
                        <div class="trustpay_logos_banks">
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/tb.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/slsp.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/vub.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/pb.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/csob.svg" /></p>
                            
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/N26.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/Revolut.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/fio.svg" /></p>
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/raiff.svg" /></p>
                            
                            <p class="trustpay-logo-wapper"><img src="'.$this->shop_url.'modules/trustpay/views/img/logo/ib.svg" /></p>
                        </div>',
                    ),
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Card payments logos'),
                        'name' => 'TRUSTPAY_LOGOS_CC',
                        'values' => array(
                            array(
                                'id' => 'TRUSTPAY_LOGOS_CC_on',
                                'value' => 1,
                            ),
                            array(
                                'id' => 'TRUSTPAY_LOGOS_CC_off',
                                'value' => 0,
                            ),
                        ),
                        'desc' => '
                        <div class="trustpay_logos">
                            <img src="'.$this->shop_url.'modules/trustpay/views/img/logo/visa.svg" />
                            <img src="'.$this->shop_url.'modules/trustpay/views/img/logo/visa-electron.svg" />
                            <img src="'.$this->shop_url.'modules/trustpay/views/img/logo/mastercard.svg" />
                            <img src="'.$this->shop_url.'modules/trustpay/views/img/logo/maestro.svg" />
                        </div>',
                    ),

                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }

    public function getCartCurrencyCode()
    {
        if (isset($this->context->cart)) {
            $cart = $this->context->cart;
            $currency = new Currency($cart->id_currency);

            return $currency->iso_code;            
        }
    }

    protected function getConfigFormValues()
    {
        return array(
            'TRUSTPAY_MODE_BANK' => Configuration::get('TRUSTPAY_MODE_BANK'),
            'TRUSTPAY_MODE_CC' => Configuration::get('TRUSTPAY_MODE_CC'),
            'TRUSTPAY_LOGOS_BANK' => Configuration::get('TRUSTPAY_LOGOS_BANK'),
            'TRUSTPAY_LOGOS_CC' => Configuration::get('TRUSTPAY_LOGOS_CC'),
            'TRUSTPAY_AID' => Configuration::get('TRUSTPAY_AID'),
            'TRUSTPAY_SECRET_KEY' => Configuration::get('TRUSTPAY_SECRET_KEY'),
            'TRUSTPAY_CURRENCY' => Configuration::get('TRUSTPAY_CURRENCY'),
            'TRUSTPAY_DISABLE_POPUP' => (int)Configuration::get('TRUSTPAY_DISABLE_POPUP'),
            'TRUSTPAY_VIEW_TYPE' => Configuration::get('TRUSTPAY_VIEW_TYPE'),
            'TRUSTPAY_STATUS_AWAITING' => Configuration::get('TRUSTPAY_STATUS_AWAITING'),
            'TRUSTPAY_STATUS_CARDWAITING' => Configuration::get('TRUSTPAY_STATUS_CARDWAITING'),
            'TRUSTPAY_STATUS_PENDING' => Configuration::get('TRUSTPAY_STATUS_PENDING'),
            'TRUSTPAY_STATUS_ANNOUNCED' => Configuration::get('TRUSTPAY_STATUS_ANNOUNCED'),
            'TRUSTPAY_STATUS_AUTHORIZED' => Configuration::get('TRUSTPAY_STATUS_AUTHORIZED'),
            'TRUSTPAY_STATUS_PROCESSING' => Configuration::get('TRUSTPAY_STATUS_PROCESSING'),
            'TRUSTPAY_STATUS_AUTHORIZEDONLY' => Configuration::get('TRUSTPAY_STATUS_AUTHORIZEDONLY'),
            'TRUSTPAY_STATUS_OK' => Configuration::get('TRUSTPAY_STATUS_OK'),
            'TRUSTPAY_STATUS_FAIL' => Configuration::get('TRUSTPAY_STATUS_FAIL'),
        );
    }

    protected function postProcess()
    {
        $form_values = $this->getConfigFormValues();

        foreach (array_keys($form_values) as $key) {
            Configuration::updateValue($key, Tools::getValue($key));
        }
    }

    public function hookDisplayBackOfficeHeader()
    {
            $this->context->controller->addJS($this->_path.'views/js/back.js');
            $this->context->controller->addCSS($this->_path.'views/css/back.css');
    }
    /*
    public function hookHeader()
    {
        $this->context->controller->addJS($this->_path.'/views/js/front.js');
        $this->context->controller->addCSS($this->_path.'/views/css/front.css');
    }
    */
    public function hookDisplayPaymentEU($params)
    {

    }
    
    public function hookPayment($params)
    {

    }

    public function hookPaymentReturn($params)
    {
        if ($this->active == false)
            return;

        $order = $params['objOrder'];

        if ($order->getCurrentOrderState()->id != Configuration::get('PS_OS_ERROR'))
            $this->smarty->assign('status', 'ok');

        $this->smarty->assign(array(
            'id_order' => $order->id,
            'order_reference' => $order->reference,
            'params' => $params,
            'contact_url' => $this->context->link->getPageLink('contact', true),
            'shop_url' => $this->shop_url,
            //'total' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false),
            'total' => self::displayPriceSmarty($params['total_to_pay'], $params['currencyObj']),
        ));

        return $this->display(__FILE__, 'views/templates/hook/payment_return.tpl');
    }
    
    // nahradenie Tools::displayPriceSmarty - malo druhy parameter nejaku referenciu a nevyuzitu - asi bug v prestashope
    
    public static function displayPriceSmarty($totalToPay, $currencyObj)
    {
        $context = Context::getContext();
        $locale = Tools::getContextLocale($context);
        if ($currencyObj instanceof Currency) {
            //$currency = Currency::getCurrencyInstance((int) $params['currency']);
            if (Validate::isLoadedObject($currencyObj)) {
                return $locale->formatPrice($totalToPay, $currencyObj->iso_code);
            }
        }

        return $locale->formatPrice($totalToPay, $context->currency->iso_code);
    }

    public function hookDisplayHeader()
    {
        $this->context->controller->addJS($this->_path.'views/js/front.js');
        $this->context->controller->addCSS($this->_path.'views/css/front.css');
        $this->context->controller->addCSS($this->_path.'views/css/loader.css');
    }

    public function hookDisplayPayment()
    {
        $allowed_card_currency = false;
        
        $allowed = array('AUD',
                'CAD',
                'CZK',
                'DKK',
                'EUR',
                'GBP',
                'HRK',
                'HUF',
                'JPY',
                'NOK',
                'PLN',
                'RON',
                'SEK',
                'USD',
            );

        if (!in_array($this->currency_code, $allowed)) {
            return;
        }
        else {
            $allowed_card_currency = true;
        }
        
        $allowed_currency = false;
        $currency = new Currency($this->context->cookie->id_currency);
        $iso_code = Configuration::get('TRUSTPAY_CURRENCY');

        if($iso_code == $currency->iso_code) {
            $allowed_currency = true;
        }

        $this->smarty->assign(array(
            'module_dir' => $this->_path,
            'tpibt_url' => $this->getTpibtUrl(),
            'tpcp_url' => $this->getTpcpUrl(),
            'allowed_currency' => $allowed_currency,
            'allowed_card_currency' => $allowed_card_currency,
            'shop_url' => $this->shop_url
        ));

        return $this->display(__FILE__, 'views/templates/hook/payment.tpl');
    }

    public function hookDisplayPaymentReturn($params)
    {
        if ($this->active == false)
            return;

        if (version_compare(_PS_VERSION_, '1.7', '>=') === true) {
            $order = $params['order'];
            /*
            $total = Tools::displayPrice(
                    $params['order']->getOrdersTotalPaid(),
                    new Currency($params['order']->id_currency),
                    false
                );*/
            $total = self::displayPriceSmarty(
                    $params['order']->getOrdersTotalPaid(),
                    new Currency($params['order']->id_currency)
                );
        } else {
            $order = $params['objOrder'];
            //$total = Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false);
            $total = self::displayPriceSmarty($params['total_to_pay'], $params['currencyObj']);
        }


        if ($order->getCurrentOrderState()->id != Configuration::get('PS_OS_ERROR'))
            $this->smarty->assign('status', 'ok');

        $this->smarty->assign(array(
            'id_order' => $order->id,
            'order_reference' => $order->reference,
            'params' => $params,
            'contact_url' => $this->context->link->getPageLink('contact', true),
            'shop_url' => $this->shop_url,
            'total' => $total,
        ));

        return $this->display(__FILE__, 'views/templates/hook/payment_return.tpl');
    }

    public function getTpcpUrl()
    {
        $cart = new Cart($this->context->cart->id);
        $customer = new Customer($cart->id_customer);
        $address = new Address($cart->id_address_invoice);
        $country = new Country($address->id_country);
        $language = new Language($this->context->cookie->id_lang);
        $base_url = $this->getTpcpModeUrl();
        $id_account = Configuration::get('TRUSTPAY_AID');
        $amount = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
        $billing_city = $address->city;
        $billing_country = $country->iso_code;
        $billing_postcode = $address->postcode;
        $billing_postcode = str_replace(' ', '', $billing_postcode);
        $billing_street = $address->address1;
        $card_holder = $address->firstname.' '.$address->lastname;
        $currency = new Currency($cart->id_currency);

        $currency = $currency->iso_code;
        $email = $customer->email;
        $reference = $this->context->cart->id;
        $payment_type = 0;
        $localization = $language->iso_code;

        $secret_key = Configuration::get('TRUSTPAY_SECRET_KEY');
        $sig_data = sprintf("%d/%s/%s/%s/%d/%s/%s/%s/%s/%s/%s", $id_account, number_format($amount, 2, '.', ''), $currency, $reference, $payment_type, $billing_city, $billing_country, $billing_postcode, $billing_street, $card_holder, $email);

        $signature = $this->getSignature($secret_key, $sig_data);

        $url = $base_url;
        $url .= '?AccountId='.$id_account;
        $url .= '&Amount='.number_format($amount, 2, '.', '');
        $url .= '&Currency='.$currency;
        $url .= '&Reference='.urlencode($reference);
        $url .= '&PaymentType='.$payment_type;
        $url .= '&Signature='.$signature;
        $url .= '&BillingCity='.$billing_city;
        $url .= '&BillingCountry='.$billing_country;
        $url .= '&BillingPostcode='.$billing_postcode;
        $url .= '&BillingStreet='.$billing_street;
        $url .= '&CardHolder='.$card_holder;
        $url .= '&Email='.$email;
        $url .= '&ReturnUrl='.urlencode($this->url_success);
        $url .= '&CancelUrl='.urlencode($this->url_cancel);
        $url .= '&ErrorUrl='.urlencode($this->url_error);
        $url .= '&NotificationUrl='.urlencode($this->url_notification);
        $url .= '&Localization='.$localization;
        $url .= '&PluginVersion=prestashop9-'.$this->version;

        return $url;
    }

    public function getTpcpModeUrl()
    {
        $url = '';

        $TRUSTPAY_MODE_CC = Configuration::get('TRUSTPAY_MODE_CC');

        if ($TRUSTPAY_MODE_CC == 3) {
            $url ="https://amapi.finby.eu/mapi5/Card/PayPopup";
        }

        return $url;
    }

    public function getIdOrder($reference)
    {
        $sql = 'SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE `id_cart` = '.$reference;
        $id_order = (int)Db::getInstance()->getValue($sql);

        return $id_order;   
    }
    
    public function getOrderTotalPaid($orderId)
    {
        $sql = 'SELECT `total_paid` FROM `'._DB_PREFIX_.'orders` WHERE `id_order` = '.$orderId;
        $total_paid = Db::getInstance()->getValue($sql);

        return $total_paid;   
    }

    public function getOrderState($result_code)
    {
        switch ($result_code) {
            case '0':
                $id_state = Configuration::get('TRUSTPAY_STATUS_OK');
                $msg = $this->l('Finby payment transaction has been done.');
                break;
            case '1':
                $id_state = Configuration::get('TRUSTPAY_STATUS_PENDING');
                $msg = $this->l('Finby payment is pending (Offline payment).');
                break;
            case '2':
                $id_state = Configuration::get('TRUSTPAY_STATUS_ANNOUNCED');
                $msg = $this->l('Finby payment was successfully announced. Waiting for payment approval.');
                break;
            case '3':
                $id_state = Configuration::get('TRUSTPAY_STATUS_AUTHORIZED');
                $msg = $this->l('Finby payment was successfully authorized. Waiting for payment approval.');
                break;
            case '4':
                $id_state = Configuration::get('TRUSTPAY_STATUS_PROCESSING');
                $msg = $this->l('Finby payment was successfully received, but it must be internally processed.');
                break;
            case '5':
                $id_state = Configuration::get('TRUSTPAY_STATUS_AUTHORIZEDONLY');
                $msg = $this->l('Card payment was successfully authorized, but not captured.');
                break;
            case '6':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = '';
                break;
            case '1001':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1001] Invalid request - Data sent is not properly formatted.');
                break;
            case '1002':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1002] Unknown account - Account with specified ID was not found.');
                break;
            case '1003':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1003] Merchant account disabled - Merchant account has been disabled.');
                break;
            case '1004':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1004] Invalid sign - Sign of message is invalid.');
                break;
            case '1005':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1005] User cancel - User has cancelled payment.');
                break;
            case '1006':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1006] Invalid authentication - The request was not properly authenticated.');
                break;
            case '1007':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1007] Disposable balance - Requested transaction amount is greater than disposable balance.');
                break;
            case '1008':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1008] Service not allowed - Service cannot be used or permission to use given service has not been granted.');
                break;
            case '1009':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1009] PaySafeCard timeout - Cards allocation will be cancelled.');
                break;
            case '1010':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1010] Transaction not found - Transaction with specified ID was not found.');
                break;
            case '1011':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1011] Unsupported transaction - The requested action is not supported for the transaction.');
                break;
            case '1014':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1014] Transaction was rejected by issuer.');
                break;
            case '1100':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1100] General Error - Internal error has occurred.');
                break;
            case '1101':
                $id_state = Configuration::get('TRUSTPAY_STATUS_FAIL');
                $msg = $this->l('[Code #1101] Unsupported currency conversion - Currency conversion for requested currencies is not supported.');
                break;
        }

        $data = array();
        $data['id_state'] = $id_state;
        $data['msg'] = $msg;

        return $data;
    }

    public function getTpibtUrl()
    {
        $cart = new Cart($this->context->cart->id);

        $base_url = $this->getTpibtModeUrl();
        $id_account = Configuration::get('TRUSTPAY_AID');
        $amount = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
        $currency = new Currency($cart->id_currency);

        $currency = $currency->iso_code;
        $reference = $this->context->cart->id;
        $payment_type = 0;
        $language = new Language($this->context->cookie->id_lang);
        $localization = $language->iso_code;

        $secret_key = Configuration::get('TRUSTPAY_SECRET_KEY');
        $sig_data = sprintf("%d/%s/%s/%s/%d", $id_account, number_format($amount, 2, '.', ''), $currency, $reference, $payment_type);

        $signature = $this->getSignature($secret_key, $sig_data);


        $url = $base_url;
        $url .= '?AccountId='.$id_account;
        $url .= '&Amount='.number_format($amount, 2, '.', '');
        $url .= '&Currency='.$currency;
        $url .= '&Reference='.urlencode($reference);
        $url .= '&PaymentType='.$payment_type;
        $url .= '&Signature='.$signature;
        $url .= '&ReturnUrl='.urlencode($this->url_success);
        $url .= '&CancelUrl='.urlencode($this->url_cancel);
        $url .= '&ErrorUrl='.urlencode($this->url_error);
        $url .= '&NotificationUrl='.urlencode($this->url_notification);
        $url .= '&Localization='.$localization;
        $url .= '&PluginVersion=prestashop9-'.$this->version;

        return $url;
    }

    public function getTpibtModeUrl()
    {
        $url = '';

        $TRUSTPAY_MODE_BANK = Configuration::get('TRUSTPAY_MODE_BANK');

        if ($TRUSTPAY_MODE_BANK == 3) {
            $url ="https://amapi.finby.eu/mapi5/wire/paypopup";
        }

        return $url;
    }

    public function getSignature($key, $message)
    {
        $signature = '';

        if (function_exists('hash_hmac')) {
            $signature = strtoupper(hash_hmac('sha256', pack('A*', $message), pack('A*', $key)));
        } else {
            $this->_postErrors[] = $this->l($this->displayName.': Function hash_hmac doesn\'t exist on your server. Contact your webhosting provider.');
        }
          
        return $signature;
    }
}
