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

namespace PrestaShop\Module\AgileMultisellerPro\Controller\Front;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipCustomer;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;

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

class AgileModuleFrontController extends \ModuleFrontController
{
    public $auth = true;
    public $ssl = true;
    protected $sellerinfo;
    protected $isSeller;
    protected $seller = false;
    /** @var EntityManagerInterface */
    protected $entityManager;

    protected $public_pages = [
        'sellersummary',
        'module-agilemultisellerpro-sellersignup',
        'module-agilemultisellerpro-sellersummary',
        'module-agilemultisellerpro-agilesellers',
        'module-agilemultisellerpro-sellerbusiness',
        'module-agilemultisellerpro-sellerproducts',
        'module-agilemultisellerpro-sellerorders',
        'module-agilemultisellerpro-sellershipping',
        'module-agilemultisellerpro-productimport',
        'module-agilemultisellerpro-sellerpdfinvoice',
        'module-agilemultisellerpro-feedbackwaitlist',
        'sellerlocation',
        'showcaseform',
        'showcaselist',
        'showcaseview',
    ];

    protected $membership_access_pages = [
        'module-agilemultisellerpro-sellerbusiness',
        'module-agilemultisellerpro-sellerproducts',
        'module-agilemultisellerpro-sellerorders',
        'module-agilemultisellerpro-sellershipping',
        'module-agilemultisellerpro-productimport',
        'module-agilemultisellerpro-myreviews',
        'module-agilemultisellerpro-sellerproductdetail',
    ];

    public $display_column_left = false;
    public $display_column_right = false;

    public function init()
    {
        parent::init();

        $this->entityManager = $this->container->get('doctrine.orm.entity_manager');

        /** @var EntityRepository $sellerInfoRepository */
        $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);

        $this->sellerinfo = $sellerInfoRepository->findOneBy(['idCustomer' => $this->context->cookie->id_customer]);

        if (!$this->sellerinfo) {
            $this->sellerinfo = new Sellerinfo();
        }

        $this->isSeller = ($this->sellerinfo && $this->sellerinfo->isActive());
        if ($this->isSeller) {
            $this->seller = new \Customer($this->context->cookie->id_customer);
        }

        $pagename = $this->getPageName();

        if (!$this->isSeller && !in_array($pagename, $this->public_pages)) {
            $this->errors[] = $this->context->getTranslator()->trans(
                'You do not have permission to access this page. Please conatct store administrator.',
                [],
                'Modules.Agilemultisellerpro.Front'
            );
        }

        $sellerInfoMembershipCustomerRepository = $this->entityManager
            ->getRepository(SellerinfoMembershipCustomer::class);

        $expiry_date = $sellerInfoMembershipCustomerRepository
            ->getExpiryDate($this->context->customer->id, $this->context->language->id);
        $today = new \DateTime(date('Y-m-d H:i:s'));

        $membership_valid = ($expiry_date >= $today);

        if (\Configuration::get('AGILE_MEMBERSHIP_STATUS')
            && !$membership_valid
            && in_array($pagename, $this->membership_access_pages)
        ) {
            \Tools::redirect($this->context->link->getModuleLink($this->module->name, 'mymembership'));
        }

        // if (Module::isEnabled('agilesellerlistoptions')) {
        //     include_once(_PS_ROOT_DIR_ . '/modules/agilesellerlistoptions/agilesellerlistoptions.php');
        //     $aslmodule = new AgileSellerListOptions();
        //     $this->context->smarty->assign(array(
        //         'pay_options_link' => $aslmodule->getPayOptionLink($this->sellerinfo->id_seller)
        //     ));
        // }

        $this->context->smarty->assign([
            'isSeller' => $this->isSeller,
            'agilemultiseller_views' => _PS_ROOT_DIR_ . '/modules/agilemultisellerpro/views/',
            'sellerinfo' => $this->sellerinfo,
            'is_seller_shipping_installed' => false,
            'is_seller_commission_installed' => false,
            'is_seller_messenger_installed' => false,
            'is_seller_ratings_installed' => false,
            'is_multiple_shop_installed' => false,
            'is_seller_listoptions_installed' => false,
            'is_agileprepaidcredit_installed' => false,
            'is_seller_tools_installed' => false,
            'sellertoken' => \Tools::hash('ams_seller') . ($this->isSeller ? $this->seller->passwd : ''),
            'admin_folder_name' => \Configuration::get('AGILE_MS_ADMIN_FOLDER_NAME'),
            'selleremail' => ($this->seller ? $this->seller->email : ''),
            'ajaxurl' => _MODULE_DIR_,
            'seller_palenl_withleft' => (int) \Configuration::get('AGILE_MS_SELLER_PANEL_WITHLEFT'),
            'seller_palenl_withright' => (int) \Configuration::get('AGILE_MS_SELLER_PANEL_WITHRIGHT'),
            'is_seller_pickupcenter_installed' => false,
            'base_dir_ssl' => $this->context->shop->getBaseURL(true, true),
        ]);
    }

    public function setMedia()
    {
        if (\Tools::getValue('ajax') != 'true') {
            parent::setMedia();

            $this->addAgileJqueryPlugin();
            $this->addAgileJqueryUi();
            $this->addAgileStylesheet();
            $this->addAgileJavascript();
        }
    }

    private function addAgileJqueryPlugin()
    {
        $this->addJqueryPlugin([
            'idTabs',
            'fancybox',
            'typewatch',
        ]);
    }

    private function addAgileJqueryUi()
    {
        $component = [
            'ui.datepicker',
            'ui.widget',
            'ui.mouse',
            'ui.slider',
        ];

        foreach ($component as $ui) {
            $ui_path = \Media::getJqueryUIPath($ui, 'base', true);

            if (!empty($ui_path['css'])) {
                if (is_array($ui_path['css'])) {
                    foreach ($ui_path['css'] as $uri => $media) {
                        $this->registerStylesheet(
                            sha1($uri),
                            $uri,
                            ['media' => $media, 'priority' => 80]
                        );
                    }
                }
            }

            if (!empty($ui_path['js'])) {
                if (is_array($ui_path['js'])) {
                    foreach ($ui_path['js'] as $uri) {
                        $this->registerJavascript(
                            sha1($uri),
                            $uri,
                            ['position' => 'bottom', 'priority' => 80]
                        );
                    }
                }
            }
        }
    }

    private function addAgileStylesheet()
    {
        $this->registerStylesheet(
            'agile_global_style',
            '/modules/agilemultisellerpro/views/css/front/agile.global.css',
            ['media' => 'all', 'priority' => 100]
        );
    }

    private function addAgileJavascript()
    {
        $this->registerJavascript(
            'js_tools',
            '/js/tools.js',
            ['position' => 'bottom', 'priority' => 100]
        );

        $this->registerJavascript(
            'js_uitimepicker',
            '/js/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js',
            ['position' => 'bottom', 'priority' => 100]
        );

        \Media::addJsDef(AgileHelper::getAjaxUrls());
    }

    public function copyFromPost(&$object, $table)
    {
        foreach ($_POST as $key => $value) {
            if (
                $key != 'id_' . $table
                && (
                    (is_array($object) && key_exists($key, $object))
                    || (is_object($object) && property_exists($object, $key))
                )
            ) {
                if ($key == 'passwd' && \Tools::getValue('id_' . $table) && empty($value)) {
                    continue;
                }

                if ($key == 'passwd' && !empty($value)) {
                    $value = \Tools::encrypt($value);
                }

                try {
                    $object->{$key} = $value;
                } catch (\Exception $e) {
                }
            }
        }

        $rules = call_user_func([get_class($object), 'getValidationRules'], get_class($object));

        if (count($rules['validateLang'])) {
            $languages = \Language::getLanguages(false);
            foreach ($languages as $language) {
                foreach (array_keys($rules['validateLang']) as $field) {
                    if (\Tools::getIsset($field . '_' . (int) $language['id_lang'])) {
                        if (!isset($object->{$field}) || !is_array($object->{$field})) {
                            $object->{$field} = [];
                        }

                        $object->{$field}[(int) $language['id_lang']] = \Tools::getValue($field . '_' .
                            (int) $language['id_lang']);

                        if ($field == 'link_rewrite' && !empty($value)) {
                            $object->{$field}[(int) $language['id_lang']] = \Tools::link_rewrite($object->{$field}[(int) $language['id_lang']]);
                        }
                    }
                }
            }
        }
    }

    public function validateRules($class_name = false, $isGlobalErrors = true)
    {
        $fieldsErrors = [];

        if (!$class_name) {
            $class_name = $this->className;
        }

        $rules = call_user_func([$class_name, 'getValidationRules'], $class_name);

        if (
            count($rules['requiredLang'])
            || count($rules['sizeLang'])
            || count($rules['validateLang'])
        ) {
            $default_language = new \Language((int) \Configuration::get('PS_LANG_DEFAULT'));

            $languages = \Language::getLanguages(false);
        }

        foreach ($rules['required'] as $field) {
            if (($value = \Tools::getValue($field)) == false && (string) $value != '0') {
                if (!\Tools::getValue($this->identifier) || ($field != 'passwd' && $field != 'no-picture')) {
                    $msg = sprintf(
                        $this->trans('The field %1$s is required', [], 'Modules.Agilemultisellerpro.Front'),
                        call_user_func([$class_name, 'displayFieldName'], $field, $class_name)
                    );

                    $fieldsErrors[] = [
                        'field' => $field,
                        'msg' => $msg,
                    ];

                    if (true === $isGlobalErrors) {
                        $this->errors[] = $msg;
                    }
                }
            }
        }

        foreach ($rules['requiredLang'] as $field_lang) {
            if (
                (($empty = \Tools::getValue($field_lang . '_' . $default_language->id)) === false || $empty !== '0')
                && empty($empty)
            ) {
                $msg = sprintf(
                    $this->trans('The field %1$s is required at least in %2$s', [], 'Modules.Agilemultisellerpro.Front'),
                    call_user_func([$class_name, 'displayFieldName'], $field_lang, $class_name),
                    $default_language->name
                );

                $fieldsErrors[] = [
                    'field' => $field_lang,
                    'msg' => $msg,
                ];

                if (true === $isGlobalErrors) {
                    $this->errors[] = $msg;
                }
            }
        }

        foreach ($rules['size'] as $field => $max_length) {
            if (\Tools::getValue($field) !== false && \Tools::strlen(\Tools::getValue($field)) > $max_length) {
                $msg = sprintf(
                    $this->trans('The field %1$s is too long (%2$d chars max)', [], 'Modules.Agilemultisellerpro.Front'),
                    call_user_func([$class_name, 'displayFieldName'], $field_lang, $class_name),
                    $max_length
                );

                $fieldsErrors[] = [
                    'field' => $field,
                    'msg' => $msg,
                ];

                if (true === $isGlobalErrors) {
                    $this->errors[] = $msg;
                }
            }
        }

        foreach ($rules['sizeLang'] as $field_lang => $max_length) {
            foreach ($languages as $language) {
                $field_lang = \Tools::getValue($field_lang . '_' . $language['id_lang']);
                if ($field_lang !== false && \Tools::strlen($field_lang) > $max_length) {
                    $msg = sprintf(
                        $this->trans('The field %1$s (%2$s) is too long (%3$d chars max, html chars including)', [], 'Modules.Agilemultisellerpro.Front'),
                        call_user_func([$class_name, 'displayFieldName'], $field_lang, $class_name),
                        $language['name'],
                        $max_length
                    );

                    $fieldsErrors[] = [
                        'field' => $field_lang,
                        'msg' => $msg,
                    ];

                    if (true === $isGlobalErrors) {
                        $this->errors[] = $msg;
                    }
                }
            }
        }

        foreach ($rules['validate'] as $field => $function) {
            if (($value = \Tools::getValue($field)) !== false && ($field != 'passwd')) {
                if (!\Validate::$function($value) && !empty($value)) {
                    $msg = sprintf(
                        $this->trans('The field %1$s is invalid - ', [], 'Modules.Agilemultisellerpro.Front') . $function,
                        call_user_func([$class_name, 'displayFieldName'], $field, $class_name)
                    );

                    $fieldsErrors[] = [
                        'field' => $field,
                        'msg' => $msg,
                    ];

                    if (true === $isGlobalErrors) {
                        $this->errors[] = $msg;
                    }
                }
            }
        }

        if (($value = \Tools::getValue('passwd')) != false) {
            if ($class_name == 'Employee' && !Validate::isPasswdAdmin($value)) {
                $msg = sprintf(
                    $this->trans('The field %1$s is invalid', [], 'Modules.Agilemultisellerpro.Front'),
                    call_user_func([$class_name, 'displayFieldName'], 'passwd', $class_name)
                );

                $fieldsErrors[] = [
                    'field' => 'passwd',
                    'msg' => $msg,
                ];

                if (true === $isGlobalErrors) {
                    $this->errors[] = $msg;
                }
            } elseif ($class_name == 'Customer' && !\Validate::isPasswd($value)) {
                $msg = sprintf(
                    $this->trans('The field %1$s is invalid', [], 'Modules.Agilemultisellerpro.Front'),
                    call_user_func([$class_name, 'displayFieldName'], 'passwd', $class_name)
                );

                $fieldsErrors[] = [
                    'field' => 'passwd',
                    'msg' => $msg,
                ];

                if (true === $isGlobalErrors) {
                    $this->errors[] = $msg;
                }
            }
        }

        foreach ($rules['validateLang'] as $field_lang => $function) {
            foreach ($languages as $language) {
                if (
                    ($value = \Tools::getValue($field_lang . '_' . $language['id_lang'])) !== false
                    && !empty($value)
                ) {
                    if (!\Validate::$function($value)) {
                        $msg = sprintf(
                            $this->trans('The field %1$s (%2$) is invalid', [], 'Modules.Agilemultisellerpro.Front'),
                            call_user_func([$class_name, 'displayFieldName'], $field_lang, $class_name),
                            $language['name']
                        );

                        $fieldsErrors[] = [
                            'field' => $field_lang,
                            'msg' => $msg,
                        ];

                        if (true === $isGlobalErrors) {
                            $this->errors[] = $msg;
                        }
                    }
                }
            }
        }

        return $fieldsErrors;
    }
}
