<?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
 */

use PrestaShop\Module\AgileMultisellerPro\Controller\Front\AgileModuleFrontController;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipCustomer;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;

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

class AgileMultiSellerProAgileSellersModuleFrontController extends AgileModuleFrontController
{
    public $auth = false;
    public $name = 'agilesellers';

    public function initContent()
    {
        parent::initContent();
        $this->processData();

        $this->setTemplate('module:' . $this->module->name . '/views/templates/front/multipleshop/agilesellers.tpl');
    }

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

        $this->context->controller->addJS($this->module->getPathUri() . 'views/js/front/multipleshop.agilesellers.js');
        $this->context->controller->addCss($this->module->getPathUri() . 'views/css/multipleshop.agilesellers.css');
    }

    public function processData()
    {
        $filter = strcasecmp(Tools::getValue('filter'), 'All') ? Tools::getValue('filter') : '';

        $seller_list = $this->getSellers(
            Tools::getValue('nameq'),
            Tools::getValue('seller_location'),
            Tools::getValue('seller_type'),
            $filter,
        );
        $sellers_nb = count($seller_list);

        $filters = range('a', 'z');
        array_unshift($filters, 'All');

        $this->context->smarty->assign([
            'seller_list' => $seller_list,
            'selers_nb' => $sellers_nb,
            'filters' => $filters,
            'filter' => Tools::getValue('filter'),
            'nameq' => Tools::getValue('nameq'),
            'seller_type' => (int) Tools::getValue('seller_type'),
            'seller_location' => Tools::getValue('seller_location'),
            'formAction' => $this->context->link->getModuleLink($this->module->name, $this->name),
            'countriesList' => $this->getSellersLocationsList(),
            'sellerTypesList' => $this->getSellersTypesList(),
        ]);
    }

    public function getSellers(string $nameq = '', $sellerLocation, int $sellerType, string $filter, bool $ative = true)
    {
        $idLang = $this->context->language->id;
        $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);

        $sellers = $sellerInfoRepository->getSellerInfos(
            $this->context->language->id,
            $ative,
            $nameq,
            $sellerLocation,
            $sellerType,
            $filter,
        );

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

        $sellersData = [];
        foreach ($sellers as $key => $val) {
            $expiry_date = $sellerInfoMembershipCustomerRepository
                ->getExpiryDate($val->getIdCustomer(), $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) {
                continue;
            }

            $idSeller = $val->getIdSellerinfo();
            $sellerLang = $val->getLangByLangId($idLang);

            $shop = Shop::getShop($val->getIdShop());

            $sellersData[$key] = [
                'idSeller' => $idSeller,
                'description' => $sellerLang->getDescription(),
                'company' => $sellerLang->getCompany(),
                'countryName' => Country::getNameById($idLang, $val->getIdCountry()),
                'logoImageUrl' => AgileHelper::getImagePath($idSeller, 'logo'),
                'sellerLink' => AgileHelper::getSellerUrlByShopId($val->getidShop()),
                'shopName' => (isset($shop['name']) && !empty($shop['name'])) ? $shop['name'] : $sellerLang->getCompany(),
            ];
        }

        return $sellersData;
    }

    public function getSellersLocationsList()
    {
        $locationLevel = Configuration::get('AGILE_MS_LOCATION_BLOCK_LEVEL');

        $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);
        return $sellerInfoRepository->getSellersLocationsByLang($this->context->language->id, $locationLevel);
    }

    public function getSellersTypesList()
    {
        $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);
        return $sellerInfoRepository->getSellersTypesByLang($this->context->language->id);
    }
}
