<?php
/**
 * 2018 Paysera
 *
 * 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.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2018 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of Paysera
 */
namespace Paysera\Form;

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

use Paysera\Entity\FormResult;
use Paysera\Helper\FormHelperInterface;

class ExtraSettingsForm implements AdminFormInterface
{
    /**
     * @var FormHelperInterface
     */
    private $formHelper;
    /**
     * @var \Module
     */
    private $module;
    /**
     * @var string
     */
    private $formId;

    /**
     * @param FormHelperInterface $formHelper
     * @param \Module $module
     */
    public function __construct(FormHelperInterface $formHelper, \Module $module)
    {
        $this->formHelper = $formHelper;
        $this->module = $module;
        $this->formId = 'ExtraSettingsForm';
    }

    /**
     * @return FormResult
     */
    public function validate()
    {
        return new FormResult(true, '');
    }

    /**
     * @return FormResult
     */
    public function update()
    {
        \Configuration::updateValue(
            'PAYSERA_EXTRA_TITLE',
            \Tools::getValue('PAYSERA_EXTRA_TITLE')
        );
        \Configuration::updateValue(
            'PAYSERA_EXTRA_DESCRIPTION',
            \Tools::getValue('PAYSERA_EXTRA_DESCRIPTION')
        );
        \Configuration::updateValue(
            'PAYSERA_EXTRA_LIST_OF_PAYMENTS',
            \Tools::getValue('PAYSERA_EXTRA_LIST_OF_PAYMENTS')
        );
        \Configuration::updateValue(
            'PAYSERA_EXTRA_SPECIFIC_COUNTRIES_GROUP',
            json_encode(\Tools::getValue('PAYSERA_EXTRA_SPECIFIC_COUNTRIES'))
        );
        \Configuration::updateValue(
            'PAYSERA_EXTRA_GRIDVIEW',
            \Tools::getValue('PAYSERA_EXTRA_GRIDVIEW')
        );
        \Configuration::updateValue(
            'PAYSERA_EXTRA_FORCE_LOGIN',
            \Tools::getValue('PAYSERA_EXTRA_FORCE_LOGIN')
        );
        \Configuration::updateValue(
            'PAYSERA_EXTRA_BUYER_CONSENT',
            \Tools::getValue('PAYSERA_EXTRA_BUYER_CONSENT')
        );

        if ('PAYSERA_SUCCESS_EXTRA_SETTING' === $this->module->l('PAYSERA_SUCCESS_EXTRA_SETTING')) {
            $successMessage = 'Your Paysera settings were successfully updated.';
        } else {
            $successMessage = $this->module->l('PAYSERA_SUCCESS_EXTRA_SETTING');
        }

        return new FormResult(true, $successMessage);
    }

    public function getFormFields()
    {
        $translations = $this->getTranslations();

        return [[
            'form' => [
                'input' => [
                    $this->formHelper->getTextForm(
                        'PAYSERA_EXTRA_TITLE',
                        $translations['title']
                    ),
                    $this->formHelper->getTextareaForm(
                        'PAYSERA_EXTRA_DESCRIPTION',
                        $translations['desc']
                    ),
                    $this->formHelper->getBoolForm(
                        'PAYSERA_EXTRA_LIST_OF_PAYMENTS',
                        $translations['list']
                    ),
                    $this->formHelper->getSelectForm(
                        'PAYSERA_EXTRA_SPECIFIC_COUNTRIES',
                        $translations['countries'],
                        $this->getCountries(),
                        false,
                        true
                    ),
                    $this->formHelper->getBoolForm(
                        'PAYSERA_EXTRA_GRIDVIEW',
                        $translations['grid']
                    ),
                    $this->formHelper->getBoolForm(
                        'PAYSERA_EXTRA_FORCE_LOGIN',
                        $translations['force_login']
                    ),
                    $this->formHelper->getBoolForm(
                        'PAYSERA_EXTRA_BUYER_CONSENT',
                        $translations['buyer_consent']
                    ),
                ],
                'submit' => [
                    'title' => $translations['save'],
                ],
            ],
        ]];
    }

    /**
     * @return array
     */
    public function getFieldsValue()
    {
        $configTitle = \Configuration::get('PAYSERA_EXTRA_TITLE');

        $configDesc = \Configuration::get('PAYSERA_EXTRA_DESCRIPTION');
        $configPaymentsList = \Configuration::get('PAYSERA_EXTRA_LIST_OF_PAYMENTS');
        $configGrid = \Configuration::get('PAYSERA_EXTRA_GRIDVIEW');
        $configForceLogin = \Configuration::get('PAYSERA_EXTRA_FORCE_LOGIN');
        $configBuyerConsent = \Configuration::get('PAYSERA_EXTRA_BUYER_CONSENT');

        $multiSelectValues = $this->getMultipleFieldValues('PAYSERA_EXTRA_SPECIFIC_COUNTRIES');

        $extraSetting = [];
        $extraSetting['PAYSERA_EXTRA_TITLE'] =
            \Tools::getValue('PAYSERA_EXTRA_TITLE', $configTitle)
        ;
        $extraSetting['PAYSERA_EXTRA_DESCRIPTION'] =
            \Tools::getValue('PAYSERA_EXTRA_DESCRIPTION', $configDesc)
        ;
        $extraSetting['PAYSERA_EXTRA_LIST_OF_PAYMENTS'] =
            \Tools::getValue('PAYSERA_EXTRA_LIST_OF_PAYMENTS', $configPaymentsList)
        ;
        $extraSetting['PAYSERA_EXTRA_GRIDVIEW'] =
            \Tools::getValue('PAYSERA_EXTRA_GRIDVIEW', $configGrid)
        ;
        $extraSetting['PAYSERA_EXTRA_FORCE_LOGIN'] =
            \Tools::getValue('PAYSERA_EXTRA_FORCE_LOGIN', $configForceLogin)
        ;
        $extraSetting['PAYSERA_EXTRA_BUYER_CONSENT'] =
            \Tools::getValue('PAYSERA_EXTRA_BUYER_CONSENT', $configBuyerConsent)
        ;
        $extraSetting[$multiSelectValues['name']] = $multiSelectValues['values'];

        return $extraSetting;
    }

    public function additionalHTML()
    {
        return '';
    }

    /**
     * @return array
     */
    private function getTranslations()
    {
        $translations = [];

        if ('PAYSERA_EXTRA_TITLE' === $this->module->l('PAYSERA_EXTRA_TITLE')) {
            $translations['title']['label'] = 'Title';
        } else {
            $translations['title']['label'] = $this->module->l('PAYSERA_EXTRA_TITLE');
        }
        if ('PAYSERA_EXTRA_DESCRIPTION' === $this->module->l('PAYSERA_EXTRA_DESCRIPTION')) {
            $translations['desc']['label'] = 'Description';
        } else {
            $translations['desc']['label'] = $this->module->l('PAYSERA_EXTRA_DESCRIPTION');
        }
        if ('PAYSERA_EXTRA_LIST_OF_PAYMENTS' === $this->module->l('PAYSERA_EXTRA_LIST_OF_PAYMENTS')) {
            $translations['list']['label'] = 'List of payments';
        } else {
            $translations['list']['label'] = $this->module->l('PAYSERA_EXTRA_LIST_OF_PAYMENTS');
        }
        if ('PAYSERA_EXTRA_SPECIFIC_COUNTRIES' === $this->module->l('PAYSERA_EXTRA_SPECIFIC_COUNTRIES')) {
            $translations['countries']['label'] = 'Specific countries';
        } else {
            $translations['countries']['label'] = $this->module->l('PAYSERA_EXTRA_SPECIFIC_COUNTRIES');
        }
        if ('PAYSERA_EXTRA_GRIDVIEW' === $this->module->l('PAYSERA_EXTRA_GRIDVIEW')) {
            $translations['grid']['label'] = 'Grid view';
        } else {
            $translations['grid']['label'] = $this->module->l('PAYSERA_EXTRA_GRIDVIEW');
        }
        if ('PAYSERA_EXTRA_FORCE_LOGIN' === $this->module->l('PAYSERA_EXTRA_FORCE_LOGIN')) {
            $translations['force_login']['label'] = 'Force Login';
        } else {
            $translations['force_login']['label'] = $this->module->l('PAYSERA_EXTRA_FORCE_LOGIN');
        }
        if ('PAYSERA_EXTRA_BUYER_CONSENT' === $this->module->l('PAYSERA_EXTRA_BUYER_CONSENT')) {
            $translations['buyer_consent']['label'] = 'Buyer consent';
        } else {
            $translations['buyer_consent']['label'] = $this->module->l('PAYSERA_EXTRA_BUYER_CONSENT');
        }

        if ('PAYSERA_EXTRA_TITLE_DESC' === $this->module->l('PAYSERA_EXTRA_TITLE_DESC')) {
            $translations['title']['desc'] = 'Payment method title that the customer will see on your website.';
        } else {
            $translations['title']['desc'] = $this->module->l('PAYSERA_EXTRA_TITLE_DESC');
        }
        if ('PAYSERA_EXTRA_DESCRIPTION_DESC' === $this->module->l('PAYSERA_EXTRA_DESCRIPTION_DESC')) {
            $translations['desc']['desc'] = 'This controls the description which the user sees during checkout.';
        } else {
            $translations['desc']['desc'] = $this->module->l('PAYSERA_EXTRA_DESCRIPTION_DESC');
        }
        if ('PAYSERA_EXTRA_LIST_OF_PAYMENTS_DESC' === $this->module->l('PAYSERA_EXTRA_LIST_OF_PAYMENTS_DESC')) {
            $translations['list']['desc'] = 'Enable this to display payment methods list at checkout page';
        } else {
            $translations['list']['desc'] = $this->module->l('PAYSERA_EXTRA_LIST_OF_PAYMENTS_DESC');
        }
        if ('PAYSERA_EXTRA_SPECIFIC_COUNTRIES_DESC' === $this->module->l('PAYSERA_EXTRA_SPECIFIC_COUNTRIES_DESC')) {
            $translations['countries']['desc'] = 'Select which country payment methods to display (empty means all)';
        } else {
            $translations['countries']['desc'] = $this->module->l('PAYSERA_EXTRA_SPECIFIC_COUNTRIES_DESC');
        }
        if ('PAYSERA_EXTRA_GRIDVIEW_DESC' === $this->module->l('PAYSERA_EXTRA_GRIDVIEW_DESC')) {
            $translations['grid']['desc'] = 'Enable this to use payments gridview';
        } else {
            $translations['grid']['desc'] = $this->module->l('PAYSERA_EXTRA_GRIDVIEW_DESC');
        }
        if ('PAYSERA_EXTRA_FORCE_LOGIN_DESC' === $this->module->l('PAYSERA_EXTRA_FORCE_LOGIN_DESC')) {
            $translations['force_login']['desc'] = 'Enable this to force customer to login on checkout';
        } else {
            $translations['force_login']['desc'] = $this->module->l('PAYSERA_EXTRA_FORCE_LOGIN_DESC');
        }
        if ('PAYSERA_EXTRA_BUYER_CONSENT_DESC' === $this->module->l('PAYSERA_EXTRA_BUYER_CONSENT_DESC')) {
            $translations['buyer_consent']['desc'] = 'Enable this to use buyer consent';
        } else {
            $translations['buyer_consent']['desc'] = $this->module->l('PAYSERA_EXTRA_BUYER_CONSENT_DESC');
        }

        if ('BACKEND_EXTRA_SAVE' === $this->module->l('BACKEND_EXTRA_SAVE')) {
            $translations['save'] = 'Save extra settings';
        } else {
            $translations['save'] = $this->module->l('BACKEND_EXTRA_SAVE');
        }

        return $translations;
    }

    public function getFormId()
    {
        return $this->formId;
    }

    public function getFormTitle()
    {
        return $this->module->l('Extra Settings');
    }

    public function getSubmitActionName()
    {
        return 'btnExtraSubmit';
    }

    /**
     * @return FormHelperInterface
     */
    public function getFormHelper()
    {
        return $this->formHelper;
    }

    /**
     * @return array
     */
    private function getCountries()
    {
        $context = \Context::getContext();
        $countries = [[
            'id' => '',
            'name' => $this->module->l('All countries'),
        ]];

        foreach (\Country::getCountries($context->language->id) as $country) {
            $countries[] = [
                'id' => strtolower($country['iso_code']),
                'name' => $country['name'],
            ];
        }

        return $countries;
    }

    /**
     * @param string $key
     *
     * @return array
     */
    private function getMultipleFieldValues($key)
    {
        $keyGroup = $key . '_GROUP';
        $arrayName = $key . '[]';
        $values = [];

        $defaultVal = \Configuration::get($keyGroup);
        $val = \Tools::getValue($keyGroup, $defaultVal);

        if ($val !== false) {
            foreach (json_decode($val) as $item) {
                $values[$item] = $item;
            }
        }

        return [
            'name' => $arrayName,
            'values' => $values,
        ];
    }
}
