<?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\Sellerinfo;

use Doctrine\ORM\EntityManagerInterface;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoLang;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\DataConfiguration;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\Membership\DataConfiguration as MembershipDataConfiguration;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperMembership;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperSellerInfo;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileImageUploader;
use PrestaShop\Module\AgileMultisellerPro\Repository\SellerInfoRepository;
use PrestaShop\PrestaShop\Core\Form\IdentifiableObject\DataHandler\FormDataHandlerInterface;
use PrestaShopBundle\Entity\Lang;

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

class DataHandler implements FormDataHandlerInterface
{
    /**
     * @var SellerInfoRepository
     */
    private $repository;

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

    /**
     * @param SellerInfoRepository $sellerInfoRepository
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(SellerInfoRepository $sellerInfoRepository, EntityManagerInterface $entityManager)
    {
        $this->repository = $sellerInfoRepository;
        $this->entityManager = $entityManager;
    }

    public function create(array $data)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function update($sellerinfoId, array $data)
    {
        $sellerInfo = $this->repository->findOneBy(['idSellerinfo' => $sellerinfoId]);

        $oldStatus = $sellerInfo->isActive();

        if (isset($data['active'])) {
            $sellerInfo->setActive((bool) $data['active']);
        }

        if (isset($data['payment_collection'])) {
            $sellerInfo->setPaymentCollection((bool) $data['payment_collection']);
        }

        if (isset($data['id_sellertype1'])) {
            $sellerInfo->setIdSellertype1($data['id_sellertype1']);
        }

        if (isset($data['id_sellertype2'])) {
            $sellerInfo->setIdSellertype2($data['id_sellertype2']);
        }

        if (isset($data['postcode'])) {
            $sellerInfo->setPostcode($data['postcode']);
        }

        if (isset($data['id_country'])) {
            $sellerInfo->setIdCountry((int) $data['id_country']);
        }

        if (isset($data['phone'])) {
            $sellerInfo->setPhone($data['phone']);
        }

        if (isset($data['fax'])) {
            $sellerInfo->setFax($data['fax']);
        }

        if (isset($data['latitude'])) {
            $sellerInfo->setLatitude($data['latitude']);
        }

        if (isset($data['longitude'])) {
            $sellerInfo->setLongitude($data['longitude']);
        }

        for ($i = 1; $i <= DataConfiguration::AGILE_MS_SELLER_NUMBER_QUANTITY; ++$i) {
            $valueName = 'ams_custom_number' . $i;
            if (isset($data[$valueName])) {
                $methodName = 'setAmsCustomNumber' . $i;
                $sellerInfo->$methodName($data[$valueName]);
            }
        }

        for ($i = 1; $i <= DataConfiguration::AGILE_MS_SELLER_DATE_QUANTITY; ++$i) {
            $valueName = 'ams_custom_date' . $i;
            if (isset($data[$valueName])) {
                $methodName = 'setAmsCustomDate' . $i;
                $sellerInfo->$methodName($data[$valueName]);
            }
        }

        for ($i = 1; $i <= DataConfiguration::AGILE_MS_SELLER_STRING_QUANTITY; ++$i) {
            $valueName = 'ams_custom_string' . $i;
            if (isset($data[$valueName])) {
                $methodName = 'setAmsCustomString' . $i;
                $sellerInfo->$methodName($data[$valueName]);
            }
        }

        $defaultIdLang = (int) \Configuration::get('PS_LANG_DEFAULT');
        $sellerInfoDefaultLang = $sellerInfo->getLangByLangId($defaultIdLang);

        // Multilanguage fields
        $langRepository = $this->entityManager->getRepository(Lang::class);

        foreach ($langRepository->findAll() as $lang) {
            $idLang = (int) $lang->getId();
            $sellerInfoLang = $sellerInfo->getLangByLangId($idLang);
            $isSetLang = false;

            if (!$sellerInfoLang) {
                $sellerInfoLang = new SellerinfoLang();
                $sellerInfoLang->setIdLang($lang);
                $isSetLang = true;
            }

            if (isset($data['company'])) {
                $sellerInfoLang->setCompany($data['company'][$idLang]);
            }

            if (isset($data['description'])) {
                $sellerInfoLang->setDescription($data['description'][$idLang]);
            }

            if (isset($data['address1'])) {
                $sellerInfoLang->setAddress1($data['address1'][$idLang]);
            }

            if (isset($data['address2'])) {
                $sellerInfoLang->setAddress2($data['address2'][$idLang]);
            }

            if (isset($data['city'])) {
                $sellerInfoLang->setCity($data['city'][$idLang]);
            }

            for ($i = 1; $i <= DataConfiguration::AGILE_MS_SELLER_TEXT_QUANTITY; ++$i) {
                $valueName = 'ams_custom_text' . $i;
                if (isset($data[$valueName][$idLang])) {
                    $methodName = 'setAmsCustomText' . $i;
                    $sellerInfoLang->$methodName($data[$valueName][$idLang]);
                }
            }

            for ($i = 1; $i <= DataConfiguration::AGILE_MS_SELLER_HTML_QUANTITY; ++$i) {
                $valueName = 'ams_custom_html' . $i;
                if (isset($data[$valueName][$idLang])) {
                    $methodName = 'setAmsCustomHtml' . $i;
                    $sellerInfoLang->$methodName($data[$valueName][$idLang]);
                }
            }

            if ($idLang != $defaultIdLang) {
                if (!$sellerInfoLang->getCompany() && $sellerInfoDefaultLang->getCompany()) {
                    $sellerInfoLang->setCompany($sellerInfoDefaultLang->getCompany());
                }

                if (!$sellerInfoLang->getAddress1() && $sellerInfoDefaultLang->getAddress1()) {
                    $sellerInfoLang->setAddress1($sellerInfoDefaultLang->getAddress1());
                }

                if (!$sellerInfoLang->getCity() && $sellerInfoDefaultLang->getCity()) {
                    $sellerInfoLang->setCity($sellerInfoDefaultLang->getCity());
                }
            }

            if (true === $isSetLang) {
                $sellerInfo->addSellerLang($sellerInfoLang);
            }
        }

        if (!empty($data['logo'])) {
            AgileImageUploader::upload($sellerInfo->getIdSellerinfo(), 'logo', $data['logo']);
        }

        $this->validateData($sellerInfo);

        AgileHelperSellerInfo::syncSellerManufacturerSupplier($sellerInfo);

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

        if (
            false === $oldStatus
            && true === $sellerInfo->isActive()
            && (int) \Configuration::get(MembershipDataConfiguration::AGILE_MEMBERSHIP_FREE_TRIAL_TIMING)
            == MembershipDataConfiguration::TIMING_SELLER_APPROVAL
        ) {
            $customer = new \Customer($sellerInfo->getIdCustomer());

            if (\Validate::isLoadedObject($customer)) {
                AgileHelperMembership::createFreeMembership($customer);
            }
        }

        return $sellerInfo->getIdSellerinfo();
    }

    public function validateData($sellerInfo)
    {
        if ($formErrors = $this->repository->validateBySellerInfo($sellerInfo)) {
            $number = 1;
            foreach ($formErrors as &$errorMessage) {
                $errorMessage = $number . '. ' . $errorMessage;
                ++$number;
            }
            $errorsMessage = implode('</br>', $formErrors);
            throw new \Exception($errorsMessage);
        }

        return true;
    }
}
