<?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
 */
declare(strict_types=1);

namespace PrestaShop\Module\AgileMultisellerPro\Form\SellerLocation;

use Doctrine\ORM\EntityManagerInterface;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\DataConfiguration;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;
use PrestaShop\PrestaShop\Core\ConstraintValidator\Constraints\AddressStateRequired;
use PrestaShop\PrestaShop\Core\Form\ConfigurableFormChoiceProviderInterface;
use PrestaShopBundle\Form\Admin\Type\CountryChoiceType;
use PrestaShopBundle\Form\Admin\Type\SwitchType;
use PrestaShopBundle\Form\Admin\Type\TranslatorAwareType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraints\Type;

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

class Form extends TranslatorAwareType
{
    /**
     * @var ConfigurationInterface
     */
    private $configuration;

    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var int
     */
    private $languageId;

    /**
     * @var ConfigurableFormChoiceProviderInterface
     */
    private $stateChoiceProvider;

    /**
     * @var int
     */
    private $contextCountryId;

    /**
     * @var RouterInterface
     */
    private $router;

    public function __construct(TranslatorInterface $translator, array $locales, ConfigurationInterface $configuration, EntityManagerInterface $entityManager, $languageId, ConfigurableFormChoiceProviderInterface $stateChoiceProvider, $contextCountryId, RouterInterface $router)
    {
        $this->configuration = $configuration;
        $this->entityManager = $entityManager;
        $this->languageId = $languageId;
        $this->stateChoiceProvider = $stateChoiceProvider;
        $this->contextCountryId = $contextCountryId;
        $this->router = $router;

        parent::__construct($translator, $locales);
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $data = $builder->getData();
        $countryId = !empty($data['id_country']) ? $data['id_country'] : $this->contextCountryId;
        $stateChoices = $this->stateChoiceProvider->getChoices(['id_country' => $countryId]);
        $showStates = !empty($stateChoices);

        $builder
            ->add('active',
                SwitchType::class,
                [
                    'label' => 'Status',
                ],
            )
            ->add('idSellerinfo',
                ChoiceType::class,
                [
                    'label' => 'Seller:',
                    'translation_domain' => 'Modules.Agilemultisellerpro.Admin',
                    'choices' => $this->getAllSellerInfo(),
                ],
            )
            ->add('idCarrierReference',
                ChoiceType::class,
                [
                    'label' => 'Carrier:',
                    'translation_domain' => 'Modules.Agilemultisellerpro.Admin',
                    'choices' => $this->getAllCarriers(),
                ],
            )
            ->add('location',
                TextType::class,
                [
                    'label' => 'Location',
                    'translation_domain' => 'Modules.Agilemultisellerpro.Admin',
                    'attr' => ['class' => 'agile-location'],
                ],
            )
            ->add('email',
                EmailType::class,
                [
                    'label' => 'Email',
                    'translation_domain' => 'Admin.Global',
                ],
            )
            ->add('address1',
                TextType::class,
                [
                    'label' => 'Address',
                    'translation_domain' => 'Admin.Global',
                    'attr' => ['class' => 'agile-address1'],
                ],
            )
            ->add('address2',
                TextType::class,
                [
                    'label' => 'Address (2)',
                    'translation_domain' => 'Admin.Global',
                    'required' => false,
                ],
            )
            ->add('city',
                TextType::class,
                [
                    'label' => 'City',
                    'translation_domain' => 'Admin.Global',
                    'attr' => ['class' => 'agile-city'],
                ],
            )
            ->add('postcode',
                TextType::class,
                [
                    'label' => 'Zip/Postal code',
                    'translation_domain' => 'Admin.Global',
                    'attr' => ['class' => 'agile-postcode'],
                ],
            )
            ->add('id_country',
                CountryChoiceType::class,
                [
                    'label' => 'Country',
                    'translation_domain' => 'Admin.Global',
                    'with_postcode_attr' => true,
                    'attr' => [
                        'class' => 'agile-country',
                        'data-states-url' => $this->router->generate('admin_country_states'),
                        'data-toggle' => 'select2',
                        'data-minimumResultsForSearch' => '7',
                    ],
                ],
            )
            // ->add('id_state',
            //     ChoiceType::class,
            //     [
            //         'label' => $this->trans('State', 'Admin.Global'),
            //         'required' => true,
            //         'choices' => $stateChoices,
            //         'constraints' => [
            //             new AddressStateRequired([
            //                 'id_country' => $countryId,
            //             ]),
            //         ],
            //         'row_attr' => [
            //             'class' => 'js-address-state-select',
            //         ],
            //         'attr' => [
            //             'visible' => $showStates,
            //             'data-toggle' => 'select2',
            //             'data-minimumResultsForSearch' => '7',
            //             'class' => 'agile-state'
            //         ],
            //     ]
            // )
            ->add('phone',
                TelType::class,
                [
                    'label' => 'Phone',
                    'translation_domain' => 'Admin.Global',
                    'required' => false,
                ],
            )
            ->add('description',
                TextareaType::class,
                [
                    'label' => 'Description:',
                    'translation_domain' => 'Modules.Agilemultisellerpro.Admin',
                    'required' => false,
                ]
            )
        ;

        if (
            $this->configuration->get(DataConfiguration::AGILE_MS_GMAP)
            && $this->configuration->get(DataConfiguration::AGILE_MS_GMAP_KEY)
        ) {
            $builder
                ->add('latitude',
                    TextType::class,
                    [
                        'label' => 'Latitude',
                        'translation_domain' => 'Modules.Agilemultisellerpro.Admin',
                        'required' => false,
                        'attr' => ['class' => 'agile-latitude'],
                        'constraints' => new Type(['type' => 'numeric']),
                    ],
                )
                ->add('longitude',
                    TextType::class,
                    [
                        'label' => 'Longitude',
                        'translation_domain' => 'Modules.Agilemultisellerpro.Admin',
                        'required' => false,
                        'attr' => ['class' => 'agile-longitude'],
                        'constraints' => new Type(['type' => 'numeric']),
                    ],
                )
                ->add('gmapKey',
                    TextType::class,
                    [
                        'required' => false,
                        'data' => $this->configuration->get(DataConfiguration::AGILE_MS_GMAP_KEY),
                        'attr' => ['class' => 'agile-gmap-key'],
                    ],
                )
            ;

            \Media::addJsDef([
                'agileLanguages' => $this->getAllCountries(),
                'idSelectedState' => !empty($data['id_state']) ? $data['id_state'] : 0,
            ]);
        }
    }

    private function getAllSellerInfo()
    {
        $result = [];
        $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);

        foreach ($sellerInfoRepository->findAll() as $sellerInfo) {
            $sellerInfoCompany = $sellerInfo->getLangByLangId($this->languageId)->getCompany()
                . ' [' . $sellerInfo->getIdSellerinfo() . ']';
            $result[$sellerInfoCompany] = $sellerInfo->getIdSellerinfo();
        }

        return $result;
    }

    private function getAllCarriers()
    {
        $result['---'] = 0;

        foreach (\Carrier::getCarriers($this->languageId) as $carrier) {
            $result[$carrier['name']] = (int) $carrier['id_reference'];
        }

        return $result;
    }

    private function getAllCountries()
    {
        if (\Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
            $countries = \Carrier::getDeliveredCountries($this->languageId, true, true);
        } else {
            $countries = \Country::getCountries($this->languageId, true);
        }

        return $countries;
    }
}
