<?php
/**
 * 2007-2022 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-2022 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

require_once dirname(__FILE__) . '/AdminEtsHDBaseController.php';

class AdminEtsHDFormController extends AdminEtsHDBaseController
{
    /**
     * @var Ets_helpdesk
     */
    public $module;

    public function renderOptions($ret = false)
    {
        if (!$this->fields_options) {
            return $this->content;
        }
        $fields_form = array(
            'form' => array(
                'legend' => array(
                    'title' => isset($this->fields_options['title']) ? $this->fields_options['title'] : '',
                    'icon' => 'icon-AdminAdmin'
                ),
                'input' => array(),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
        if (isset($this->fields_options['buttons']) && $this->fields_options['buttons']) {
            $fields_form['form']['buttons'] = $this->fields_options['buttons'];
        }
        if (isset($this->fields_options['fields']) && count($this->fields_options['fields']) > 0) {
            foreach ($this->fields_options['fields'] as $key => $config) {
                $fields = $config;
                $fields['name'] = $key;
                $fields['values'] = isset($config['values']) ? $config['values'] : ($config['type'] == 'switch' ? array(
                    array(
                        'id' => 'active_on',
                        'value' => 1,
                        'label' => $this->l('Yes')
                    ),
                    array(
                        'id' => 'active_off',
                        'value' => 0,
                        'label' => $this->l('No')
                    )
                ) : false);
                if ($config['type'] == 'select' && !empty($fields['multiple']) && stripos($fields['name'], '[]') === false)
                    $fields['name'] .= '[]';
                $fields_form['form']['input'][] = $fields;
            }
        }

        $language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));

        // Helper Form.
        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->default_form_language = $language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $helper->module = $this->module;
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitOptions' . $this->table;
        $helper->currentIndex = self::$currentIndex;
        $helper->token = Tools::getAdminTokenLite($this->controller_name);
        $helper->override_folder = '/';

        $helper->tpl_vars = array(
            'base_url' => $this->context->shop->getBaseURL(),
            'language' => array(
                'id_lang' => $language->id,
                'iso_code' => $language->iso_code
            ),
            'fields_value' => $this->getConfigFieldsValue($helper->submit_action),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );
        $helper->tpl_vars = array_merge($helper->tpl_vars, $this->tpl_option_vars);
        $form = $helper->generateForm(array($fields_form));
        if ($ret) {
            return $form;
        }
        $this->content .= $form;
    }

    protected function getConfigFieldsValue($submit_action)
    {
        $fields = array();

        if (isset($this->fields_options['fields'])
            && ($configs = $this->fields_options['fields'])
            && is_array($configs)
            && count($configs) > 0
        ) {

            $languages = Language::getLanguages(false);
            if (trim($submit_action) !== '' && Tools::isSubmit($submit_action)) {
                foreach ($configs as $key => $config) {
                    if (isset($config['lang']) && $config['lang']) {
                        foreach ($languages as $l) {
                            $fields[$key][$l['id_lang']] = Tools::getValue($key . '_' . $l['id_lang'], isset($config['default']) ? $config['default'] : '');
                        }
                    } elseif ($config['type'] == 'select' && isset($config['multiple']) && $config['multiple']) {
                        $fields[$key . ($config['type'] == 'select' ? '[]' : '')] = Tools::getValue($key, array());
                    } elseif ($config['type'] == 'checkbox') {
                        $fields[$key] = Tools::getValue($key, array());
                    } elseif ($config['type'] == 'file')
                        $fields[$key] = $this->getFields($key, !empty($config['global']) ? 1 : 0);
                    else
                        $fields[$key] = Tools::getValue($key, isset($config['default']) ? $config['default'] : '');
                }
            } else {
                foreach ($configs as $key => $config) {
                    $global = !empty($config['global']) ? 1 : 0;
                    if (isset($config['lang']) && $config['lang']) {
                        foreach ($languages as $l) {
                            $fields[$key][$l['id_lang']] = $this->getFields($key, $global, $l['id_lang']);
                        }
                    } elseif ($config['type'] == 'select' && isset($config['multiple']) && $config['multiple']) {
                        $fields[$key . ($config['type'] == 'select' ? '[]' : '')] = ($result = $this->getFields($key, $global)) != '' ? explode(',', $result) : array();
                    } elseif ($config['type'] == 'checkbox') {
                        $fields[$key] = ($result = $this->getFields($key, $global)) != '' ? explode(',', $result) : array();
                    } else
                        $fields[$key] = $this->getFields($key, $global);
                }
            }
        }

        return $fields;
    }

    protected function getFields($key, $global = false, $idLang = null)
    {
        return $global ? Configuration::getGlobalValue($key, $idLang) : Configuration::get($key, $idLang);
    }

    protected function setFields($key, $global, $values, $html = false)
    {
        return $global ? Configuration::updateGlobalValue($key, $values, $html) : Configuration::updateValue($key, $values, $html);
    }

    public function validateRules($class_name = null)
    {
        parent::validateRules($class_name);

        if (!count($this->errors)
            && $this->fields_form
            && isset($this->fields_form['input'])
            && is_array($this->fields_form['input'])
            && count($this->fields_form['input']) > 0
        ) {
            $this->validateFields($this->fields_form['input']);
        }
    }

    public function validateFields($configs = array(), $id_lang_default = 0)
    {
        $this->module->validateFields($configs, 0, $id_lang_default);
    }

    protected function processUpdateOptions()
    {
        if (!$this->fields_options ||
            !isset($this->fields_options['fields']) ||
            !$this->fields_options['fields']
        ) {
            return false;
        }

        $configs = $this->fields_options['fields'];
        $languages = Language::getLanguages(false);
        $id_lang_default = (int)Configuration::get('PS_LANG_DEFAULT');

        $this->validateFields($configs, $id_lang_default);
        if (!$this->errors) {
            foreach ($configs as $key => $config) {
                $global = isset($config['global']) && $config['global'] ? 1 : 0;
                if (isset($config['lang']) && $config['lang']) {
                    $values = array();
                    foreach ($languages as $lang) {
                        if ($config['type'] == 'switch')
                            $values[$lang['id_lang']] = (int)trim(Tools::getValue($key . '_' . $lang['id_lang'])) ? 1 : 0;
                        else
                            $values[$lang['id_lang']] = trim(Tools::getValue($key . '_' . $lang['id_lang'])) ? trim(Tools::getValue($key . '_' . $lang['id_lang'])) : trim(Tools::getValue($key . '_' . $id_lang_default));
                    }
                    $this->setFields($key, $global, $values, true);
                } else {
                    if ($config['type'] == 'switch') {
                        $this->setFields($key, $global, (int)trim(Tools::getValue($key)) ? 1 : 0);
                    } elseif ($config['type'] == 'checkbox' || $config['type'] == 'select' && isset($config['multiple']) && $config['multiple']) {
                        $this->setFields($key, $global, implode(',', Tools::getValue($key, array())), true);
                    } elseif ($config['type'] == 'file') {
                        if (isset($_FILES[$key]) && !empty($_FILES[$key]['name'])) {

                            $folder = isset($config['folder']) ? $config['folder'] : HDDefines::$default_upload;
                            $type = Tools::strtolower(Tools::substr(strrchr($_FILES[$key]['name'], '.'), 1));
                            $file_name = HDTools::getNewFilename($folder) . '.' . $type;

                            if (!($temp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !@move_uploaded_file($_FILES[$key]['tmp_name'], $temp_name)) {
                                $this->errors[] = $this->l('An error occurred while uploading the image.');
                            } elseif (!ImageManager::resize($temp_name, $folder . $file_name, null, null, $type)) {
                                $this->errors[] = sprintf($this->l('An error occurred while copying this image: %s'), Tools::stripslashes($_FILES[$key]['name']));
                            } else {
                                $old_image_value = $this->getFields($key, $global); 
                                $this->setFields($key, $global, $file_name, true);
                                if($old_image_value)
                                {
                                    $folder = isset($config['folder']) ? $config['folder'] : HDDefines::$default_upload;
                                    @unlink($folder.$old_image_value);
                                }
                            }
                            if (isset($temp_name))
                                @unlink($temp_name);
                        } elseif (
                            trim($image_deleted = Tools::getValue($key . '_DELETED')) !== ''
                            && Validate::isUnsignedInt($image_deleted)
                            && $image_deleted > 0
                        ) {
                            $folder = isset($config['folder']) ? $config['folder'] : HDDefines::$default_upload;
                            $old_image = $folder . $this->getFields($key, $global);
                            if (!file_exists($old_image) || @unlink($old_image)) {
                                $this->setFields($key, $global, '');
                            }
                        }
                    } else {
                        $this->setFields($key, $global, trim(Tools::getValue($key)), true);
                    }
                }
            }
        }
        if (empty($this->errors)) {
            $this->confirmations[] = $this->_conf[6];
        }
    }

    public function copyFromPost(&$object, $table)
    {
        parent::copyFromPost($object, $table);

        /* Multilingual fields */
        $class_vars = get_class_vars(get_class($object));
        $fields = array();
        if (isset($class_vars['definition']['fields'])) {
            $fields = $class_vars['definition']['fields'];
        }
        if (is_array($fields) &&
            count($fields) > 0
        ) {

            $id_lang_default = (int)Configuration::get('PS_LANG_DEFAULT');
            $languageIds = Language::getIDs(false);

            foreach ($fields as $field => $params) {
                if (array_key_exists('lang', $params) &&
                    $params['lang'] &&
                    is_array($languageIds) &&
                    count($languageIds) > 0
                ) {
                    foreach ($languageIds as $id_lang) {
                        if ($id_lang > 0 &&
                            Tools::isSubmit($field . '_' . $id_lang) &&
                            trim(Tools::getValue($field . '_' . $id_lang)) == ''
                        ) {
                            $object->{$field}[$id_lang] = trim(Tools::getValue($field . '_' . $id_lang_default));
                        }
                    }
                }
            }
        }
    }
}