<?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\Helper\Form;

use PrestaShop\Module\AgileMultisellerPro\Adapter\SellerInfoAdapter;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoLang;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellertype;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;

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

class SellerInfoForm extends AbstractForm
{
    private $sellerinfo;
    private $entityManager;
    private $sellerinfoMapping;
    private $sellerinfoLangMapping;
    private $sellerinfoFields;
    private $isSignup;

    public function __construct(Sellerinfo $sellerinfo, $entityManager)
    {
        parent::__construct();

        $this->sellerinfo = $sellerinfo;
        $this->entityManager = $entityManager;
        $this->sellerinfoMapping = $this->entityManager->getClassMetadata(Sellerinfo::class)->fieldNames;
        $this->sellerinfoLangMapping = $this->entityManager->getClassMetadata(SellerinfoLang::class)->fieldNames;
        $this->sellerinfoFields = SellerInfoAdapter::getSellerinfoFields();
    }

    protected function getFieldsByType($isSignup): array
    {
        $this->isSignup = $isSignup;

        if (true === $this->isSignup) {
            $fields = $this->getSignupSellerInfoFields();
        } else {
            $fields = $this->getAccountSellerInfoFields();
        }

        return $fields;
    }

    private function getAccountSellerInfoFields(): array
    {
        $fields = [
            'id_sellerinfo',
            'id_customer',
            'id_manufacturer',
            'id_supplier',
            'company',
            [
                'fieldName' => 'shop_name',
                'options' => [
                    'value' => $this->getShopInfo()['name'],
                    'label' => $this->translator->trans('Shop name', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['text'],
                    ],
                ],
            ],
            [
                'fieldName' => 'shop_url',
                'options' => [
                    'value' => AgileHelper::getSellerUrlByShopId($this->sellerinfo->getIdShop()),
                    'label' => $this->translator->trans('Shop URL', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['text'],
                        'availableValues' => [
                            'otherAttr' => 'disabled',
                        ],
                        'isAgileForm' => true,
                    ],
                ],
            ],
            [
                'fieldName' => 'virtual_uri',
                'options' => [
                    'value' => $this->getShopInfo()['virtual_uri'],
                    'label' => $this->translator->trans('Virtual URL', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['text'],
                    ],
                ],
            ],
            'logo',
            // 'banner',
            'address1',
            'address2',
            'postcode',
            'city',
            'id_country',
            'id_state',
            'phone',
            'description',
        ];

        return $fields;
    }

    private function getSignupSellerInfoFields(): array
    {
        $fields = [
            'id_sellerinfo',
            'id_customer',
            [
                'fieldName' => 'label',
                'options' => [
                    'value' => $this->translator->trans('Your account information', [], 'Modules.Agilemultisellerpro.Form'),
                    'label' => '',
                    'formOptions' => [
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['label'],
                        'isAgileForm' => true,
                    ],
                ],
            ],
            [
                'fieldName' => 'firstname',
                'options' => [
                    'value' => \Tools::getValue('firstname', ''),
                    'label' => $this->translator->trans('First Name', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['text'],
                    ],
                ],
            ],
            [
                'fieldName' => 'lastname',
                'options' => [
                    'value' => \Tools::getValue('lastname', ''),
                    'label' => $this->translator->trans('Last Name', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['text'],
                        'placeholder' => 123,
                    ],
                ],
            ],
            [
                'fieldName' => 'email',
                'options' => [
                    'value' => \Tools::getValue('email', ''),
                    'label' => $this->translator->trans('Email Address', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['email'],
                    ],
                ],
            ],
            [
                'fieldName' => 'passwd',
                'options' => [
                    'value' => '',
                    'label' => $this->translator->trans('Password', [], 'Modules.Agilemultisellerpro.Form'),
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['password'],
                    ],
                ],
            ],
            [
                'fieldName' => 'label',
                'options' => [
                    'value' => $this->translator->trans('Your business information', [], 'Modules.Agilemultisellerpro.Form'),
                    'label' => '',
                    'formOptions' => [
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['label'],
                        'isAgileForm' => true,
                    ],
                ],
            ],
            'company',
            'address1',
            'address2',
            'postcode',
            'city',
            'id_country',
            'id_state',
            'phone',
            'description',
        ];

        if ((int) \Configuration::get('AGILE_MS_SELLER_TERMS')) {
            $cms = new \CMS((int) \Configuration::get('AGILE_MS_SELLER_TERMS'), $this->context->language->id);
            $link_terms = $this->context->link->getCMSLink($cms, $cms->link_rewrite, true);

            if (!strpos($link_terms, '?')) {
                $link_terms .= '?content_only=1';
            } else {
                $link_terms .= '&content_only=1';
            }

            $label = $this->translator->trans('Yes, I have read and I agree on the Seller Terms & condition', [], 'Modules.Agilemultisellerpro.Form')
                . ' <a href="' . $link_terms . '" id="seller_terms" class="iframe">'
                . $this->translator->trans('Seller Terms & conditions', [], 'Modules.Agilemultisellerpro.Form') . '</a>';

            $fields[] = [
                'fieldName' => 'seller_account_signup',
                'options' => [
                    'value' => '',
                    'label' => $label,
                    'formOptions' => [
                        'required' => true,
                        'type' => SellerInfoAdapter::FORM_FIELD_TYPES['checkbox'],
                    ],
                ],
            ];
        }

        return $fields;
    }

    protected function getAvailableValuesByField($field): array
    {
        $availableValues = [];
        $options = $this->getOptionsByField($field);

        if (isset($options['formOptions']['availableValues'])) {
            $availableValues = $options['formOptions']['availableValues'];
            $typeAvailable = $options['formOptions']['availableValues'];

            if ($typeAvailable === SellerInfoAdapter::FORM_FIELD_AVAILABLE_TYPES['type']) {
                $availableValues = $this->entityManager->getRepository(Sellertype::class)
                    ->getTypesByLang($this->context->language->id);
            } elseif ($typeAvailable === SellerInfoAdapter::FORM_FIELD_AVAILABLE_TYPES['country']) {
                $availableValues = $this->getCountries();
            }
        }

        return $availableValues;
    }

    protected function getIsAgileFormByField($field): bool
    {
        if (in_array($this->getNameByField($field), ['logo', 'banner'])) {
            return true;
        }

        return parent::getIsAgileFormByField($field);
    }

    protected function getOptionsByField($field)
    {
        $options = [];
        $fieldType = $this->getNameByField($field);

        if (isset($this->sellerinfoFields[$fieldType])) {
            $options = $this->sellerinfoFields[$fieldType];
        } elseif (isset($field['options'])) {
            $options = $field['options'];
        } elseif ('logo' === $fieldType) {
            $options = [
                'label' => [
                    'show' => $this->translator->trans('Shop Logo', [], 'Modules.Agilemultisellerpro.Form'),
                    'add' => $this->translator->trans('Add a logo image', [], 'Modules.Agilemultisellerpro.Form'),
                ],
                'formOptions' => [
                    'type' => SellerInfoAdapter::FORM_FIELD_TYPES['image'],
                ],
            ];
        } elseif ('banner' === $fieldType) {
            $options = [
                'label' => [
                    'show' => $this->translator->trans('Seller Banner / Header image', [], 'Modules.Agilemultisellerpro.Form'),
                    'add' => $this->translator->trans('Add a banner / Header image', [], 'Modules.Agilemultisellerpro.Form'),
                ],
                'formOptions' => [
                    'type' => SellerInfoAdapter::FORM_FIELD_TYPES['image'],
                ],
            ];
        }

        if (true === $this->isSignup && 'description' === $fieldType) {
            $options['label'] = $this->translator->trans('Comments', [], 'Modules.Agilemultisellerpro.Form');
        }

        return $options;
    }

    protected function getValueFormByField($field)
    {
        $fieldValue = null;

        if ('payment_collection' === $field) {
            $methodName = 'is' . ucfirst($this->sellerinfoMapping[$field]);
        } elseif ('logo' === $field || 'banner' === $field) {
            return AgileHelper::getImagePath($this->sellerinfo->getIdSellerinfo(), $field);
        } else {
            $methodName = 'get' . ucfirst($this->sellerinfoMapping[$field]);
        }

        if (method_exists($this->sellerinfo, $methodName)) {
            $fieldValue = $this->sellerinfo->{$methodName}();
        }

        if ($fieldValue instanceof \DateTime) {
            $fieldValue = $fieldValue->format('Y-m-d');
        }

        return $fieldValue;
    }

    protected function getValueLangByField($field)
    {
        $value = null;
        $methodName = 'get' . ucfirst($this->sellerinfoLangMapping[$field]);

        $id_lang = (int) \Configuration::get('PS_LANG_DEFAULT');

        if ($sellerInfoLang = $this->sellerinfo->getLangByLangId($id_lang)) {
            if (method_exists($sellerInfoLang, $methodName)) {
                $value = $sellerInfoLang->{$methodName}();
            }
        }

        return $value;
    }

    private function getCountries()
    {
        $countries = [];

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

        return $countries;
    }

    private function getShopInfo()
    {
        $shop = \Shop::getShop($this->sellerinfo->getIdShop());
        if (!isset($shop['name'])) {
            $shop['name'] = '';
        }

        if (!isset($shop['uri'])) {
            $shop['uri'] = '';
        } else {
            $shop['uri'] = trim($shop['uri'], '/');
        }

        // get shop virtual URI
        $shopUrl = \ShopUrl::getShopUrls($this->sellerinfo->getIdShop())->getFirst();
        $shop['virtual_uri'] = $shopUrl ? trim($shopUrl->virtual_uri, '/') : '';

        return $shop;
    }

    protected function getIsLangField($field): bool
    {
        return false;
    }

    protected function getTypeByField($field): string
    {
        $type = SellerInfoAdapter::FORM_FIELD_TYPES['text'];
        $options = $this->getOptionsByField($field);

        if (!empty($options['formOptions']['type'])) {
            $type = $options['formOptions']['type'];
        }

        return $type;
    }
}
