<?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
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

use PrestaShop\Module\AgileMultisellerPro\Controller\Front\AgileModuleFrontController;
use PrestaShop\Module\AgileMultisellerPro\Controller\Front\Traits\SellerTrait;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileConst;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperSellerInfo;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileImageUploader;
use PrestaShop\Module\AgileMultisellerPro\Helper\Form\SellerInfoForm;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class AgileMultiSellerProSellerBusinessModuleFrontController extends AgileModuleFrontController
{
    use SellerTrait;

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

        $deflang = new Language($this->context->language->id);
        $isoTinyMCE = (file_exists(_PS_ROOT_DIR_ . '/js/tiny_mce/langs/' . $deflang->iso_code . '.js') ?
            $deflang->iso_code : 'en');

        Media::addJsDef([
            'is_multilang_address' => true,
            'has_address' => true,
            'pathCSS' => _THEME_CSS_DIR_,
            'idSelectedCountry' => $this->getSelectedCountry(),
            'idSelectedState' => $this->getSelectedState(),
            'iso' => $isoTinyMCE,
            'ad' => str_replace('\\', '\\\\', dirname($_SERVER['PHP_SELF'])),
            'id_language_current' => (int) $this->context->language->id,
            'agileCountries' => $this->getCountries(),
        ]);

        Media::addJsDefL('sellerbusiness_fileDefaultHtml', $this->trans('No file selected', [], 'Modules.Agilemultisellerpro.Business'));
        Media::addJsDefL('sellerbusiness_fileButtonHtml', $this->trans('Choose File', [], 'Modules.Agilemultisellerpro.Business'));

        $this->registerJavascript(
            'agile_statememneger',
            '/modules/agilemultisellerpro/views/js/AgileStatesManagement.js',
            ['position' => 'bottom', 'priority' => 100]
        );

        $this->registerJavascript(
            'agile_multilanguage',
            '/modules/agilemultisellerpro/views/js/multi-language.js',
            ['position' => 'bottom', 'priority' => 100]
        );

        $this->registerJavascript(
            'agile_sellerpage',
            '/modules/agilemultisellerpro/views/js/sellerpage.js',
            ['position' => 'bottom', 'priority' => 100]
        );
        // $this->registerJavascript(
        //     'agile_sellerbusiness',
        //     '/modules/agilemultisellerpro/views/js/sellerbusiness.js',
        //     ['position' => 'bottom', 'priority' => 100]
        // );
    }

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

        $this->assignCountries();
        $this->assignVatNumber();
        $this->assignAddressFormat();
        $this->addSmartyVariables();

        $this->setTemplate('module:agilemultisellerpro/views/templates/front/sellerbusiness.tpl');
    }

    private function addSmartyVariables()
    {
        $sellerLogo = null;
        $sellerBanner = null;

        $idSellerinfo = $this->sellerinfo->getIdSellerinfo();

        if (AgileHelper::checkImage($idSellerinfo, 'logo')) {
            $sellerLogo = AgileHelper::getImagePath($idSellerinfo, 'logo');
        }

        if (AgileHelper::checkImage($idSellerinfo, 'banner')) {
            $sellerBanner = AgileHelper::getImagePath($idSellerinfo, 'banner');
        }

        $conf = Configuration::getMultiple(AgileHelper::getCustomFields());
        $custom_labels = AgileHelper::getCustomLabels(':');
        $custom_hints = AgileHelper::getCustomHints();

        $this->context->smarty->assign([
            'seller_tab_id' => 2,
            'languages' => Language::getLanguages(true),
            'id_language_current' => (int) $this->context->language->id,
            'sellerLogo' => $sellerLogo,
            'sellerBanner' => $sellerBanner,
            'conf' => $conf,
            'custom_labels' => $custom_labels,
            'custom_hints' => $custom_hints,

            'formFields' => (new SellerInfoForm($this->sellerinfo, $this->entityManager))->makeForm(false),
        ]);
    }

    public function postProcess()
    {
        if (Tools::isSubmit('submitSellerinfo')) {
            $this->processSubmitSellerinfo();
        }
    }

    protected function processSubmitSellerinfo()
    {
        AgileMultiSellerPro::ensureDateCustomField();

        $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);
        $this->errors = array_merge($this->errors, $sellerInfoRepository->validateBySellerInfo($this->sellerinfo, Tools::getAllValues()));

        if (!empty($this->errors)) {
            return;
        }

        $shop_name = trim(Tools::getValue('shop_name', ''));

        if (Tools::getIsset('virtual_uri')) {
            $virtual_uri = Tools::link_rewrite(trim(Tools::getValue('virtual_uri'), ' /')) . '/';
        }

        $this->sellerinfo->setIdCustomer($this->context->customer->id);

        if (empty($shop_name)) {
            $this->errors[] = $this->trans('The shop name can not be empty.', [], 'Modules.Agilemultisellerpro.Business');
        }

        if (empty(Tools::getValue('virtual_uri'))) {
            $this->errors[] = $this->trans('The shop Virtual Uri can not be empty.', [], 'Modules.Agilemultisellerpro.Business');
        }

        if ($this->sellerinfo->getIdShop() <= 1) {
            $this->sellerinfo->setIdshop(0);
        }

        $seller_shop = new Shop($this->sellerinfo->getIdShop());

        if ($sellerInfoRepository->shopNameDuplicated($shop_name, $seller_shop->id)) {
            $this->errors[] = $this
                ->trans('The shop name you select has been used by other seller. Please choose a new one.', [], 'Modules.Agilemultisellerpro.Business');
        }
        if ($this->errors) {
            return;
        }
        if (!Validate::isLoadedObject($seller_shop)) {
            $vshop = AgileHelper::createNewShop($this->sellerinfo->getIdSellerinfo(), $shop_name);
            $this->sellerinfo->setIdshop($vshop->id);
            $this->sellerinfo->setThemeName($vshop->theme_name);

            $this->entityManager->persist($this->sellerinfo);
            $this->entityManager->flush();

            $seller_shop = new Shop($this->sellerinfo->getIdShop());
        }

        $seller_shopurl = new ShopUrl($sellerInfoRepository->getMainUrlId($seller_shop->id));

        $id_found = $seller_shopurl->canAddThisUrl(
            $seller_shopurl->domain,
            $seller_shopurl->domain_ssl,
            $seller_shopurl->physical_uri,
            $virtual_uri
        );

        if ((int) $id_found > 0) {
            $this->errors[] = $this->trans('The URL you select has been used by other seller. Please choose a new one.', [], 'Modules.Agilemultisellerpro.Business');
        }

        $this->sellerinfo->setPaymentCollection(false);
        $this->sellerinfo->setPostcode(Tools::getValue('postcode'));
        $this->sellerinfo->setIdCountry((int) Tools::getValue('id_country'));
        $this->sellerinfo->setPhone(Tools::getValue('phone'));

        if (Country::containsStates($this->sellerinfo->getIdCountry())) {
            $this->sellerinfo->setIdState((int) Tools::getValue('id_state'));
        }

        // Multilanguage fields
        foreach ($this->sellerinfo->getLangs() as $sellerInfoLang) {
            $sellerInfoLang->setCompany(Tools::getValue('company'));
            $sellerInfoLang->setAddress1(Tools::getValue('address1'));
            $sellerInfoLang->setAddress2(Tools::getValue('address2'));
            $sellerInfoLang->setCity(Tools::getValue('city'));
            $sellerInfoLang->setDescription(Tools::getValue('description'));
        }

        if (!empty($_FILES['logo']['name'])) {
            if (filesize($_FILES['logo']['tmp_name']) > AgileConst::MAX_LOGO_FILE_SIZE_IN_BYTES) {
                $this->errors[] = $this->trans(
                    'Logo file size is too bigger, maximum logo gile size (bytes) is: ',
                    [],
                    'Modules.Agilemultisellerpro.Business'
                ) . AgileConst::MAX_LOGO_FILE_SIZE_IN_BYTES;
            }

            if (empty($this->errors)) {
                $file = new UploadedFile($_FILES['logo']['tmp_name'], $_FILES['logo']['name'], 'image/jpeg');

                if (!AgileImageUploader::upload($this->sellerinfo->getIdSellerinfo(), 'logo', $file)) {
                    $this->errors[] = $this->trans(
                        'The logo upload failed, please make sure you are uploading an image file.',
                        [],
                        'Modules.Agilemultisellerpro.Business'
                    );
                }
            }
        }

        if (isset($_FILES['banner']) && !empty($_FILES['banner']['name'])) {
            if (filesize($_FILES['banner']['tmp_name']) > AgileConst::MAX_BANNER_FILE_SIZE_IN_BYTES) {
                $this->errors[] = $this->trans(
                    'Banner file size is too bigger, maximum banner gile size (bytes) is: ',
                    [],
                    'Modules.Agilemultisellerpro.Business'
                ) . AgileConst::MAX_BANNER_FILE_SIZE_IN_BYTES;
            }
            if (empty($this->errors)) {
                $file = new UploadedFile($_FILES['banner']['tmp_name'], $_FILES['banner']['name'], 'image/jpeg');
                if (!AgileImageUploader::upload($this->sellerinfo->getIdSellerinfo(), 'banner', $file)) {
                    $this->errors[] = $this->trans(
                        'The banner upload failed, please make sure you are uploading an image file.',
                        [],
                        'Modules.Agilemultisellerpro.Business'
                    );
                }
            }
        }

        $this->errors = array_merge($this->errors, $sellerInfoRepository->validateBySellerInfo($this->sellerinfo));

        if (!empty($this->errors)) {
            return;
        }

        AgileHelperSellerInfo::syncSellerManufacturerSupplier($this->sellerinfo);

        $this->entityManager->persist($this->sellerinfo);
        $this->entityManager->flush();

        $seller_shop->name = $shop_name;
        $seller_shop->theme_name = $this->sellerinfo->getThemeName();
        $seller_shop->save();
        $seller_shopurl->virtual_uri = $virtual_uri;

        /**
         * Due to an error triggered by the $seller_shopurl->save() method in the ps_mbo module,
         * we are employing a workaround by executing a direct database query.
         */
        $sql = 'UPDATE `' . _DB_PREFIX_ . 'shop_url`
                SET `virtual_uri` = \'' . pSQL($seller_shopurl->virtual_uri) . '\'
                WHERE `id_shop_url` = ' . (int) $seller_shopurl->id;
        Db::getInstance()->Execute($sql);

        Shop::cacheShops(true);

        if (empty($this->errors)) {
            $this->context->smarty->assign([
                'cfmmsg_flag' => 1,
            ]);
        }
    }
}
