<?php
/**
 * PayZen V2-Payment Module version 1.7.0 for Prestashop 1.5-1.6. Support contact : support@payzen.eu.
 *
 * NOTICE OF LICENSE
 *
 * This source file is licensed under the Open Software License version 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/osl-3.0.php
 *
 * @category  payment
 * @package   payzen
 * @author    Lyra Network (http://www.lyra-network.com/)
 * @copyright 2014-2015 Lyra Network and contributors
 * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @version   1.7.0 (revision 67311)
 */

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

/**
 * Class that renders PayZen payment module administration interface.
 */
class PayzenAdminDisplay
{
    private $module = null;
    private $post_size = 0;
    private $post_vars = 0;

    public function __construct($payzen)
    {
        $this->module = $payzen;
    }

    /**
     * Builds the html code for the admin form
     */
    public function commonHtml()
    {
        // Form beginning
        $html = '<fieldset><legend><img style="width: 16px;" src="../modules/'.$this->module->name.'/logo.png" alt="PayZen"/>'.$this->module->displayName
                .'</legend>'
                .$this->l('Developed by')
                .' : <b><a href="http://www.lyra-network.com/" target="_blank">Lyra Network</a></b><br/>'
                .$this->l('Contact us')
                .' : <b><a href="mailto:support@payzen.eu">support@payzen.eu</a></b><br/>'
                .$this->l('Module version')
                .' : <b>'.(defined('_PS_HOST_MODE_') ? 'Cloud' : '').'1.7.0</b><br/>'
                .$this->l('Platform version')
                .' : <b>V2</b><br/>
                <a style="color: red;" href="../modules/payzen/installation_doc/Integration_PayZen_Prestashop_1.5-1.6_v1.7.0.pdf" target="_blank"><b>'
                .$this->l('CLICK HERE TO VIEW THE MODULE CONFIGURATION DOCUMENTATION').'</b></a>
            </fieldset>';

        return $html;
    }

    public function generalTabHtml()
    {
        $html = '<fieldset><legend>'.$this->l('BASE SETTINGS').'</legend>';
        // enable / disbale logs
        $options = array(
                'False' => $this->l('Disabled'),
                'True' => $this->l('Enabled')
        );
        $html .= $this->adminFormSelect($options, 'PAYZEN_ENABLE_LOGS', $this->l('Logs'), $this->l('Enable / disbale module logs'));

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * payment gateway access settings
        */
        $html .= '<fieldset><legend>'.$this->l('PAYMENT GATEWAY ACCESS').'</legend>';

        $html .= $this->adminFormText('PAYZEN_SITE_ID', $this->l('Site ID'), $this->l('The identifier provided by your bank.'));
        $html .= $this->adminFormText(
            'PAYZEN_KEY_TEST',
            $this->l('Certificate in test mode'),
            $this->l('Certificate provided by your bank for test mode (available in your store Back Office).')
        );
        $html .= $this->adminFormText(
            'PAYZEN_KEY_PROD',
            $this->l('Certificate in production mode'),
            $this->l('Certificate provided by your bank (available in your store Back Office after enabling production mode).')
        );

        // context mode
        $options = array(
                'TEST' => $this->l('TEST'),
                'PRODUCTION' => $this->l('PRODUCTION')
        );
        $html .= $this->adminFormSelect($options, 'PAYZEN_MODE', $this->l('Mode'), $this->l('The context mode of this module.'));
        $html .= $this->adminFormText('PAYZEN_PLATFORM_URL', $this->l('Payment page URL'), $this->l('Link to the payment page.'), 'size="65"');

        // check URL display
        $html .= '<label>'.$this->l('Instant Payment Notification URL to copy into your store Back Office:').'</label>';
        $html .= '<div class="margin-form"><p>';

        $shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));

        // ssl enabled on default shop ?
        $ssl = Configuration::get('PS_SSL_ENABLED', null, isset($shop->id_shop_group) ? $shop->id_shop_group : $shop->id_group_shop, $shop->id);

        $html .= ($ssl ? 'https://'.$shop->domain_ssl : 'http://'.$shop->domain).
                $shop->getBaseURI().'modules/'.$this->module->name.'/validation.php';
        $html .= '<br><a style="color: red;">'. $this->l('In multistore mode, notification URL is the same for all the stores.').'</a>';

        $html .= '</p></div>';

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * payment page settings
         */
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        // supported languages
        $options = array();
        foreach (PayzenApi::getSupportedLanguages() as $key => $value) {
            $options[$key] = $this->l($value);
        }
        asort($options);

        // default language
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_DEFAULT_LANGUAGE',
            $this->l('Default language'),
            $this->l('Default language on the payment page.')
        );

        // available languages
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_AVAILABLE_LANGUAGES',
            $this->l('Available languages'),
            $this->l('Languages available on the payment page. If you do not select any, all the supported languages will be available.'),
            true,
            'size="8"'
        );

        // capture delay
        $html .= $this->adminFormText(
            'PAYZEN_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture (adjustable in your store Back Office).')
        );

        // validation mode
        $options = array(
                '' => $this->l('Back office configuration'),
                '0' => $this->l('Automatic'),
                '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_VALIDATION_MODE',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );

        // payment cards
        $html .= $this->adminFormSelect(
            array('' => $this->l('ALL')) + PayzenApi::getSupportedCardTypes(),
            'PAYZEN_PAYMENT_CARDS',
            $this->l('Card Types'),
            $this->l('The card type(s) that can be used for the payment. Select none to use platform configuration.'),
            true,
            'size="7"'
        );

        // product categories
        $category_options = array(
            'FOOD_AND_GROCERY' => $this->l('Food and grocery'),
            'AUTOMOTIVE' => $this->l('Automotive'),
            'ENTERTAINMENT' => $this->l('Entertainment'),
            'HOME_AND_GARDEN' => $this->l('Home and garden'),
            'HOME_APPLIANCE' => $this->l('Home appliance'),
            'AUCTION_AND_GROUP_BUYING' => $this->l('Auction and group buying'),
            'FLOWERS_AND_GIFTS' => $this->l('Flowers and gifts'),
            'COMPUTER_AND_SOFTWARE' => $this->l('Computer and software'),
            'HEALTH_AND_BEAUTY' => $this->l('Health and beauty'),
            'SERVICE_FOR_INDIVIDUAL' => $this->l('Service for individual'),
            'SERVICE_FOR_BUSINESS' => $this->l('Service for business'),
            'SPORTS' => $this->l('Sports'),
            'CLOTHING_AND_ACCESSORIES' => $this->l('Clothing and accessories'),
            'TRAVEL' => $this->l('Travel'),
            'HOME_AUDIO_PHOTO_VIDEO' => $this->l('Home audio, photo, video'),
            'TELEPHONY' => $this->l('Telephony')
        );

        $html .= '<label for="PAYZEN_COMMON_CATEGORY">'.$this->l('Category mapping').'</label>';
        $html .= '<div class="margin-form">';

        $common_category = key_exists(Configuration::get('PAYZEN_COMMON_CATEGORY'), $category_options) ?
            Configuration::get('PAYZEN_COMMON_CATEGORY') : 'CUSTOM_MAPPING';

        $html .= $this->createSelectField(
            'PAYZEN_COMMON_CATEGORY',
            $common_category,
            array('CUSTOM_MAPPING' => $this->l('(Use category mapping below)')) + $category_options,
            false,
            'style="width: 220px;" onchange="javascript: payzenCategoryTableVisibility();"'
        );

        $html .= '<p>'.$this->l('Use the same category for all products.').'</p>';
        $html .= '<br />';

        $html .= '<table cellpadding="10" cellspacing="0" class="table payzen_category_mapping"'
                .($common_category != 'CUSTOM_MAPPING' ? ' style="display: none;"' : '').'>
                    <thead><tr>
                        <th>'.$this->l('Product category').'</th>
                        <th>'.$this->l('Bank product category').'</th>
                    </tr></thead>';

        $html .= '<tbody>'; {
            $payzen_categories = array();
        }

        $categories_array = Category::getCategories((int)Configuration::get('PS_LANG_DEFAULT'), true, true, '', '', '');

        if (!empty($categories_array)) {
            foreach ($categories_array as $category_array) {
                foreach ($category_array as $categories) {
                    foreach ($categories as $category) {
                        if ($category['name'] != 'Root') {
                            $category_id = $category['id_category'];
                            $payzen_category = isset($payzen_categories[$category_id]) ? $payzen_categories[$category_id] : 'FOOD_AND_GROCERY';

                            $exists = isset($payzen_categories[$category_id]);

                            $html .= '<tr id="payzen_category_mapping_'.$category_id.'">
                                        <td>'.$category['name'].(!$exists ? '<span style="color: red;">*</span>' : '').'</td>
                                        <td>';
                            $html .= $this->createSelectField(
                                'PAYZEN_CATEGORY_MAPPING['.$category_id.']',
                                $payzen_category,
                                $category_options,
                                false,
                                'style="width: 220px;"'.($common_category != 'CUSTOM_MAPPING' ? ' disabled="disabled"' : '')
                            );
                            $html .= '  </td>
                                    </tr>';
                        }
                    }
                }
            }
        }
        $html .= '</tbody></table>';

        $html .= '<p class="payzen_category_mapping"'.($common_category != 'CUSTOM_MAPPING' ? ' style="display: none;"' : '').'>'
                .$this->l('Match each product category with a bank product category.').' <b>'
                .$this->l('Entries marked with * are newly added and must be configured.').'</b></p>';
        $html .= '</div>';

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * payment page customization settings
        */
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE CUSTOMIZE').'</legend>';

        // theme configuration
        $html .= $this->adminFormText(
            'PAYZEN_THEME_CONFIG',
            $this->l('Theme configuration'),
            $this->l('The theme configuration to customize the payment page (logo, css).'),
            'size="65"'
        );

        // shop name
        $html .= $this->adminFormText(
            'PAYZEN_SHOP_NAME',
            $this->l('Shop name'),
            $this->l('Shop name to display on the payment page. Leave blank to use gateway configuration.')
        );

        // shop URL
        $html .= $this->adminFormText(
            'PAYZEN_SHOP_URL',
            $this->l('Shop URL'),
            $this->l('Shop URL to display on the payment page. Leave blank to use gateway configuration.'),
            'size="65"'
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * selective 3DS settings
        */
        $html .= '<fieldset><legend>'.$this->l('SELECTIVE 3DS').'</legend>';

        // min amount to activate three ds
        $html .= $this->adminFormText(
            'PAYZEN_3DS_MIN_AMOUNT',
            $this->l('Minimum amount to activate 3-DS'),
            $this->l('Needs subscription to Selective 3-D Secure option.')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * return to shop settings
         */
        $html .= '<fieldset><legend>'.$this->l('RETURN TO SHOP').'</legend>';

        // automatic redirection
        $options = array(
                'False' => $this->l('Disabled'),
                'True' => $this->l('Enabled')
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_REDIRECT_ENABLED',
            $this->l('Automatic redirection'),
            $this->l('If enabled, the buyer is automatically redirected to your site at the end of the payment.')
        );

        // automatic redirection options
        $html .= $this->adminFormText(
            'PAYZEN_REDIRECT_SUCCESS_T',
            $this->l('Redirection timeout on success'),
            $this->l('Time in seconds (0-300) before the buyer is automatically redirected to your website after a successful payment.')
        );
        $html .= $this->adminFormText(
            'PAYZEN_REDIRECT_SUCCESS_M',
            $this->l('Redirection message on success'),
            $this->l('Message displayed on the payment page prior to redirection after a successful payment.'),
            'size="65"'
        );
        $html .= $this->adminFormText(
            'PAYZEN_REDIRECT_ERROR_T',
            $this->l('Redirection timeout on failure'),
            $this->l('Time in seconds (0-300) before the buyer is automatically redirected to your website after a declined payment.')
        );
        $html .= $this->adminFormText(
            'PAYZEN_REDIRECT_ERROR_M',
            $this->l('Redirection message on failure'),
            $this->l('Message displayed on the payment page prior to redirection after a declined payment.'),
            'size="65"'
        );

        // return mode
        $options = array(
            'GET' => 'GET',
            'POST' => 'POST'
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_RETURN_MODE',
            $this->l('Return mode'),
            $this->l('Method that will be used for transmitting the payment result from the payment page to your shop.')
        );

        // payment failed management
        $options = array(
            Payzen::ON_FAILURE_RETRY => $this->l('Go back to checkout'),
            Payzen::ON_FAILURE_SAVE => $this->l('Save order and go back to order history')
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_FAILURE_MANAGEMENT',
            $this->l('Payment failed management'),
            $this->l('How to manage the buyer return to shop when the payment is failed.')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        ###BEGIN_ONEY_CODE###
        /*
         * additional options
        */
        $html .= '<fieldset><legend>'.$this->l('ADDITIONAL OPTIONS').'</legend>';

        // FacilyPay Oney contract
        $options = array(
            '1' => $this->l('Yes'),
            '0' => $this->l('No')
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_ONEY_CONTRACT',
            $this->l('FacilyPay Oney contract'),
            $this->l('Select «Yes» if you have a FacilyPay Oney contract.'),
            false,
            'onchange="javascript: payzenOneyContractChanged();"'
        );

        // Oney shipping settings
        $oney_options = @unserialize(Configuration::get('PAYZEN_ONEY_SHIP_OPTIONS'));
        if (!is_array($oney_options)) {
            $oney_options = array();
        }

        $carriers = Carrier::getCarriers((int)Configuration::get('PS_LANG_DEFAULT'), true, false, false, null, Carrier::ALL_CARRIERS);

        $oney_contract = Configuration::get('PAYZEN_ONEY_CONTRACT');
        $html .= '<label class="payzen_oney_ship_options"'.(!$oney_contract ? ' style="display: none;"' : '').'>'
                .$this->l('Shipping options').'</label>';

        $html .= '<div class="payzen_oney_ship_options margin-form"'.(!$oney_contract ? ' style="display: none;"' : '').'>';

        $type_options = array(
            'PACKAGE_DELIVERY_COMPANY' => $this->l('Delivery company'),
            'RECLAIM_IN_SHOP' => $this->l('Reclaim in shop'),
            'RELAY_POINT' => $this->l('Relay point'),
            'RECLAIM_IN_STATION' => $this->l('Reclaim in station')
        );

        $speed_options = array(
            'STANDARD' => $this->l('Standard'),
            'EXPRESS' => $this->l('Express')
        );

        $html .= '<table cellpadding="10" cellspacing="0" class="table">
                    <thead><tr>
                        <th>'.$this->l('Name').'</th>
                        <th>'.$this->l('FacilyPay Oney label').'</th>
                        <th>'.$this->l('Type').'</th>
                        <th>'.$this->l('Speed').'</th>
                        <th style="width: 270px;">'.$this->l('Address').'</th>
                    </tr></thead>';

        $html .= '  <tbody>';

        if (!empty($carriers)) {
            foreach ($carriers as $carrier) {
                $carrier_id = $carrier['id_carrier'];

                $oney_option = isset($oney_options[$carrier_id]) ?
                        $oney_options[$carrier_id] :
                        array(
                            'label' => preg_replace("#[^A-Z0-9ÁÀÂÄÉÈÊËÍÌÎÏÓÒÔÖÚÙÛÜÇ /'-]#ui", ' ', $carrier['name']),
                            'speed' => 'STANDARD',
                            'type' => 'PACKAGE_DELIVERY_COMPANY',
                            'address' => ''
                        );

                $html_label = $this->createTextField('PAYZEN_ONEY_SHIP_OPTIONS['.$carrier_id.'][label]', $oney_option['label'], !$oney_contract ? ' disabled="disabled"' : '');

                $html_type = $this->createSelectField(
                    'PAYZEN_ONEY_SHIP_OPTIONS['.$carrier_id.'][type]',
                    $oney_option['type'],
                    $type_options,
                    false,
                    'onchange="javascript: payzenDeliveryTypeChanged('.$carrier_id.');" style="width: 150px;"'.(!$oney_contract ? ' disabled="disabled"' : '')
                );

                $html_speed = $this->createSelectField(
                    'PAYZEN_ONEY_SHIP_OPTIONS['.$carrier_id.'][speed]',
                    $oney_option['speed'],
                    $speed_options,
                    false,
                    !$oney_contract ? ' disabled="disabled"' : ''
                );

                $html_address = $this->createTextField(
                    'PAYZEN_ONEY_SHIP_OPTIONS['.$carrier_id.'][address]',
                    $oney_option['address'],
                    'style="width: 270px;'.((string)$oney_option['type'] != 'RECLAIM_IN_SHOP' ? ' display: none;' : '').'"'
                    .(!$oney_contract ? ' disabled="disabled"' : '')
                );

                $exists = isset($oney_options[$carrier_id]);
                $html .= '<tr>
                            <td>'.$carrier['name'].(!$exists ? '<span style="color: red;">*</span>' : '').'</td>
                            <td>'.$html_label.'</td>
                            <td>'.$html_type.'</td>
                            <td>'.$html_speed.'</td>
                            <td>'.$html_address.'</td>
                        </tr>';
            }
        }
        $html .= '</tbody></table>';

        $html .= '<p>'.$this->l('Define the FacilyPay Oney information about all shipping methods.').'<br />';
        $html .= '<b>'.$this->l('FacilyPay Oney label').' : </b>'.$this->l('The label of the shipping method (use 55 alphanumeric characters, accentuated characters and these special characters: space, slash, hyphen, apostrophe).').'<br />';
        $html .= '<b>'.$this->l('Type').' : </b>'.$this->l('The delivery type of shipping method.').'<br />';
        $html .= '<b>'.$this->l('Speed').' : </b>'.$this->l('Select whether the delivery is STANDARD or EXPRESS.').'<br />';
        $html .= '<b>'.$this->l('Address').' : </b>'.$this->l('Enter address if it is a reclaim in shop.').'<br />';
        $html .= '<b>'.$this->l('Entries marked with * are newly added and must be configured.').'</b></p>';
        $html .= '</div>';

        $html .= '</fieldset><div class="clear">&nbsp;</div>';
        ###END_ONEY_CODE###

        return $html;
    }

    public function singleTabHtml()
    {
        /*
         * standard payment mode specific settings
        */
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        // title
        $html .= $this->adminFormTextLang(
            'PAYZEN_STD_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // enable/disable module
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_STD_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'standard')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * disable payment mode for specific amounts
         */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_STD_AMOUNTS');

        /*
         * card data entry mode
        */
        $html .= '<fieldset><legend>'.$this->l('CARD DATA ENTRY').'</legend>';

        $options = array(
            '1' => $this->l('Card data entry on payment gateway'),
            '2' => $this->l('Card type selection on merchant site'),
            '3' => $this->l('Card data entry on merchant site')
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_STD_CARD_DATA_MODE',
            $this->l('Card data entry mode'),
            $this->l('Select how the credit card infos will be entered. Attention, to use data acquisition on the merchant site, you must ensure that you have subscribed to this option with your bank.')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_STD_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_STD_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    public function multiTabHtml()
    {
        /*
         * multiple payment mode specific settings
        */
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        // title
        $html .= $this->adminFormTextLang(
            'PAYZEN_MULTI_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // enable/disable module
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );
        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_MULTI_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'multiple')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * disable payment mode for specific amounts
         */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_MULTI_AMOUNTS');

        /*
         * multiple payment options
         */
        $multi_options = Configuration::get('PAYZEN_MULTI_OPTIONS');
        if (!empty($multi_options)) {
            $multi_options = unserialize($multi_options);
        } else {
            $multi_options = array();
        }

        $html .= '<fieldset><legend>'.$this->l('PAYMENT OPTIONS').'</legend>';

        $html .= "\n";
        $html .= '<label for="PAYZEN_MULTI_OPTIONS">'.$this->l('Payment options').'</label>';
        $html .= '<div class="margin-form">';
        $html .= '<input id="payzen_multi_options_btn"'.(!empty($multi_options) ? ' style="display: none;"' : '')
                .' type="button" value="'.$this->l('Add').'" onclick="javascript: payzenAddOption(true, \''.$this->l('Delete').'\');" />';
        $html .= '<table id="payzen_multi_options_table"'.(empty($multi_options) ? ' style="display: none;"' : '')
                .' cellpadding="10" cellspacing="0" class="table">
                   <thead>
                        <tr>
                            <th style="font-size: 10px;">'.$this->l('Label').'</th>
                            <th style="font-size: 10px;">'.$this->l('Min amount').'</th>
                            <th style="font-size: 10px;">'.$this->l('Max amount').'</th>
                            <th style="font-size: 10px;">'.$this->l('Contract').'</th>
                            <th style="font-size: 10px;">'.$this->l('Count').'</th>
                            <th style="font-size: 10px;">'.$this->l('Period').'</th>
                            <th style="font-size: 10px;">'.$this->l('1st payment').'</th>
                            <th style="font-size: 10px;"></th>
                        </tr>
                    </thead>

                    <tbody>';
        if (!empty($multi_options)) {
            foreach ($multi_options as $key => $option) {
                $html .= '<tr id="payzen_multi_option_'.$key.'">
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][label]', $option['label'], 'style="width: 140px;"').'</td>
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][amount_min]', $option['amount_min'], 'style="width: 75px;"').'</td>
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][amount_max]', $option['amount_max'], 'style="width: 75px;"').'</td>
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][contract]', $option['contract'], 'style="width: 65px;"').'</td>
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][count]', $option['count'], 'style="width: 60px;"').'</td>
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][period]', $option['period'], 'style="width: 60px;"').'</td>
                    <td>'.$this->createTextField('PAYZEN_MULTI_OPTIONS['.$key.'][first]', $option['first'], 'style="width: 70px;"').'</td>
                    <td><input style="width: 70px;" type="button" value="'.$this->l('Delete').'" onclick="javascript: payzenDeleteOption('.$key.');"/></td>
                    </tr>';
            }
        }

        $html .= '<tr id="payzen_multi_option_add">
            <td colspan="7"></td>
            <td><input type="button" value="'.$this->l('Add').'" onclick="javascript: payzenAddOption(false, \''.$this->l('Delete').'\');" /></td>
            </tr>
            </tbody>
            </table>';

        $html .= '<p>'.$this->l('Click on «Add» button to configure one or more payment options.').'<br />';
        $html .= '<b>'.$this->l('Label').' : </b>'.$this->l('The option label to display on the frontend.').'<br />';
        $html .= '<b>'.$this->l('Min amount').' : </b>'.$this->l('Minimum amount to enable the payment option.').'<br />';
        $html .= '<b>'.$this->l('Max amount').' : </b>'.$this->l('Maximum amount to enable the payment option.').'<br />';
        $html .= '<b>'.$this->l('Contract').' : </b>'.$this->l('ID of the contract to use with the option (Leave blank preferably).').'<br />';
        $html .= '<b>'.$this->l('Count').' : </b>'.$this->l('Total number of payments.').'<br />';
        $html .= '<b>'.$this->l('Period').' : </b>'.$this->l('Delay (in days) between payments.').'<br />';
        $html .= '<b>'.$this->l('1st payment').' : </b>'.
                $this->l('Amount of first payment, in percentage of total amount. If empty, all payments will have the same amount.').
                '<br />';
        $html .= '<b>'.$this->l('Do no forget to clik on «Save» button to save your modifications.').'</b></p>';
        $html .= '</div>';

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_MULTI_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_MULTI_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    public function oneyTabHtml()
    {
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        $html .= $this->adminFormTextLang(
            'PAYZEN_ONEY_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // activate Oney payment mode
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_ONEY_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'FacilyPay Oney').
            '<br /><b>'.$this->l('Requires a FacilyPay Oney contract with Banque Accord and a subscription to your bank option').'</b>'
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * deactivate for specific amounts
        */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_ONEY_AMOUNTS');

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_ONEY_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_ONEY_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    public function ancvTabHtml()
    {
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        $html .= $this->adminFormTextLang(
            'PAYZEN_ANCV_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // activate Oney payment mode
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_ANCV_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'ANCV')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * deactivate for specific amounts
        */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_ANCV_AMOUNTS');

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_ANCV_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_ANCV_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    public function sepaTabHtml()
    {
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        $html .= $this->adminFormTextLang(
            'PAYZEN_SEPA_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // activate Oney payment mode
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_SEPA_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'SEPA')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * deactivate for specific amounts
        */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_SEPA_AMOUNTS');

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_SEPA_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_SEPA_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    public function sofortTabHtml()
    {
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        $html .= $this->adminFormTextLang(
            'PAYZEN_SOFORT_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // activate Oney payment mode
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_SOFORT_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'SOFORT Banking')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * deactivate for specific amounts
            */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_SOFORT_AMOUNTS');

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_SOFORT_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_SOFORT_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    public function paypalTabHtml()
    {
        $html = '<fieldset><legend>'.$this->l('MODULE OPTIONS').'</legend>';

        $html .= $this->adminFormTextLang(
            'PAYZEN_PAYPAL_TITLE',
            $this->l('Method title'),
            $this->l('Method title to display on payment means page.'),
            'size="45"'
        );

        // activate Oney payment mode
        $options = array(
            'False' => $this->l('Disabled'),
            'True' => $this->l('Enabled')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_PAYPAL_ENABLED',
            $this->l('Activation'),
            sprintf($this->l('Enables / disables %s payment.'), 'PayPal')
        );

        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        /*
         * deactivate for specific amounts
         */
        $html .= $this->createAmountRestrictionBlock('PAYZEN_PAYPAL_AMOUNTS');

        // module capture delay
        $html .= '<fieldset><legend>'.$this->l('PAYMENT PAGE').'</legend>';

        $html .= $this->adminFormText(
            'PAYZEN_PAYPAL_DELAY',
            $this->l('Capture delay'),
            $this->l('The number of days before the bank capture. Enter value only if different from « Base settings ».')
        );

        // module validation mode
        $options = array(
            '-1' => $this->l('Base settings configuration'),
            '' => $this->l('Back office configuration'),
            '0' => $this->l('Automatic'),
            '1' => $this->l('Manual')
        );

        $html .= $this->adminFormSelect(
            $options,
            'PAYZEN_PAYPAL_VALIDATION',
            $this->l('Payment validation'),
            $this->l('If manual is selected, you will have to confirm payments manually in your bank Back Office.')
        );
        $html .= '</fieldset><div class="clear">&nbsp;</div>';

        return $html;
    }

    /**
     * Shortcut function for creating an HTML input text.
     *
     * @param string $name
     * @param string $label
     * @param string $description
     * @param string $extra_attributes
     */
    private function adminFormText($name, $label, $description = null, $extra_attributes = '')
    {
        $html = "\n";
        $html .= '<label for="'.$name.'">'.$label.'</label>';
        $html .= '<div class="margin-form">';
        $html .= $this->createTextField($name, (string)Configuration::get($name), $extra_attributes);
        $html .= '<p>'.$description.'</p>';
        $html .= '</div>';

        return $html;
    }

    /**
     * Shortcut function for creating an HTML select.
     *
     * @param array[string][string] $options
     * @param string $name
     * @param string $label
     * @param string $description
     * @param boolean $multiple true if multi selection is allowed
     * @param string $extra_attributes
     */
    private function adminFormSelect($options, $name, $label, $description, $multiple = false, $extra_attributes = '')
    {
        $selected = (string)Configuration::get($name);
        if ($multiple) { // multi selection field
            $selected = !$selected ? array('') : explode(';', $selected);
        }

        $html = "\n";
        $html .= '<label for="'.$name.'">'.$label.'</label>';
        $html .= '<div class="margin-form">';
        $html .= $this->createSelectField($name, $selected, $options, $multiple, $extra_attributes);
        $html .= '<p>'.$description.'</p></div>';
        return $html;
    }

    /**
     * Shortcut function for creating an HTML translatable input text.
     *
     * @param string $name
     * @param string $label
     * @param string $description
     * @param string $extra_attributes
     */
    private function adminFormTextLang($name, $label, $description = null, $extra_attributes = '')
    {
        $html = "\n";
        $html .= '<label>'.$label.'</label>';
        $html .= '<div class="margin-form">';

        $current = Context::getContext()->language->id;

        $languages = Language::getLanguages(false);
        foreach ($languages as $language) {
            $id_lang = (int)$language['id_lang'];
            $value = Configuration::get($name, $id_lang) ? (string)Configuration::get($name, $id_lang) : '';

            $id = str_replace(array('[', ']'), array('_', ''), $name);
            $html .= '<div class="bootstrap translatable-field lang-'.$id_lang.'" id="'.$id.'_'.$id_lang.
                     '" style="display: '.($id_lang == $current ? 'block' : 'none').';">';
            $html .= '<div style="float: left;">';
            $html .= $this->createTextField($name.'_'.$id_lang, $value, $extra_attributes);
            $html .= '</div>';

            if (version_compare(_PS_VERSION_, '1.6', '>=')) {
                $html .= $this->displayLanguagesDropdown($language, $languages);
            }
            $html .= '</div>';
        }

        if (version_compare(_PS_VERSION_, '1.6', '<')) { // using flags is deprecated since this version
            $html .= $this->module->displayFlags($languages, $current, $name, $name, true);
        }

        $html .= '<br class="clear" /><p>'.$description.'</p>';
        $html .= '</div>';

        return $html;
    }

    private function createTextField($name, $value, $extra_attributes = '')
    {
        $html = "\n";

        $id = str_replace(array('[', ']'), array('_', ''), $name);
        $html .= '<input type="text" id="'.$id.'" name="'.$name.'" value="'.$value.'" '.$extra_attributes.'/>';

        $this->post_size += Tools::strlen($name) + Tools::strlen($value);
        $this->post_vars++;
        return $html;
    }

    private function createSelectField($name, $selected, $options, $multiple = false, $extra_attributes = '')
    {
        $html = "\n";

        $id = str_replace(array('[', ']'), array('_', ''), $name);
        $html .= '<select id="'.$id.'" name="'.$name.($multiple ? '[]" multiple="multiple"' : '"').' '.$extra_attributes.'>';
        foreach ($options as $value => $text) {
            if ($multiple || ((string)$value === (string)$selected)) {
                $this->post_size += Tools::strlen($name) + Tools::strlen($value);
                $this->post_vars++;
            }

            $is_selected = is_array($selected) ? in_array($value, $selected) : ((string)$value === (string)$selected);
            $html .= '<option value="'.$value.'"';
            $html .= $is_selected ? ' selected="selected"' : '';
            $html .= '>'.$text.'</option>';
        }
        $html .= '</select>';

        return $html;
    }

    private function displayLanguagesDropdown($language, $languages)
    {
        $html = '<div class="col-lg-2">
                    <button type="button" class="btn btn-default dropdown-toggle" tabindex="-1" data-toggle="dropdown">
                        '.$language['iso_code'].'
                        <i class="icon-caret-down"></i>
                    </button>
                    <ul class="dropdown-menu">';

        foreach ($languages as $lang) {
            $html .= '<li><a href="javascript: hideOtherLanguage('.$lang['id_lang'].')" tabindex="-1">'.$lang['name'].'</a></li>';
        }

        $html .= '    </ul>
                </div>';

        return $html;
    }

    private function createAmountRestrictionBlock($name)
    {
        $html = '<fieldset><legend>'.$this->l('AMOUNT RESTRICTIONS').'</legend>';
        $html .= "\n";
        $html .= '<label for="PAYZEN_MULTI_OPTIONS">'.$this->l('Customer group amount restriction').'</label>';
        $html .= '<div class="margin-form">';

        $amounts = @unserialize(Configuration::get($name));
        if (!is_array($amounts)) {
            $amounts = array();
        }

        $html .= '<table cellpadding="10" cellspacing="0" class="table">
                    <thead><tr>
                        <th>'.$this->l('Customer group').'</th>
                        <th>'.$this->l('Minimum amount').'</th>
                        <th>'.$this->l('Maximum amount').'</th>
                    </tr></thead>';

        $html .= '  <tbody>';

        $group_amount = isset($amounts[0]) ? $amounts[0] : array('min_amount' => '', 'max_amount' => '');

        $html_min_amount = $this->createTextField(
            $name.'[0][min_amount]',
            $group_amount['min_amount'],
            'style="width: 200px;"'
        );

        $html_max_amount = $this->createTextField(
            $name.'[0][max_amount]',
            $group_amount['max_amount'],
            'style="width: 200px;"'
        );

        $html .= '<tr style="background-color: #bebebe;">
                       <td>'.$this->l('ALL GROUPS').'</td>
                       <td>'.$html_min_amount.'</td>
                       <td>'.$html_max_amount.'</td>
                   </tr>';

        if ((!method_exists('Group', 'isFeatureActive') || Group::isFeatureActive()) && ($cust_groups = $this->getAuthorizedGroups())) {
            foreach ($cust_groups as $group) {
                $group_id = $group['id_group'];
                $group_amount = isset($amounts[$group_id]) ? $amounts[$group_id] : array('min_amount' => '', 'max_amount' => '');

                $html_min_amount = $this->createTextField(
                    $name.'['.$group_id.'][min_amount]',
                    $group_amount['min_amount'],
                    'style="width: 200px;"'
                );

                $html_max_amount = $this->createTextField(
                    $name.'['.$group_id.'][max_amount]',
                    $group_amount['max_amount'],
                    'style="width: 200px;"'
                );

                $html .= '<tr>
                            <td>'.$group['name'].'</td>
                            <td>'.$html_min_amount.'</td>
                            <td>'.$html_max_amount.'</td>
                         </tr>';
            }
        }

        $html .= '</tbody></table>';
        $html .= '<p>'.$this->l('Define amount restriction for each customer group.').'<br />';
        $html .= '</div>';

        $html .= '</fieldset><div class="clear">&nbsp;</div>';
        return $html;
    }

    public function getPostSize()
    {
        return $this->post_size;
    }

    public function getPostVars()
    {
        return $this->post_vars;
    }

    /**
     * Shortcut for module translation function.
     *
     * @param string $text
     *
     * @return localized text
     */
    private function l($string)
    {
        return $this->module->l($string, 'payzenadmindisplay', null);
    }

    public function getAuthorizedGroups()
    {
        $sql = 'SELECT DISTINCT gl.`id_group`, gl.`name` FROM `'._DB_PREFIX_.'group_lang` AS gl
            INNER JOIN `'._DB_PREFIX_.'module_group` AS mg
            ON (gl.`id_group` = mg.`id_group` AND mg.`id_module` = '.(int)$this->module->id.' AND mg.`id_shop` = '.(int)Context::getContext()->shop->id.')
            WHERE gl.`id_lang` = '.(int)Context::getContext()->language->id;

        return Db::getInstance()->executeS($sql);
    }
}
