<?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\SellerinfoMembershipCustomer;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipHistory;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipType;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoProduct;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperMembership;
use PrestaShop\Module\AgileMultisellerPro\Repository\SellerInfoMembershipTypeRepository;

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

class AgileMultiSellerProMyMembershipModuleFrontController extends AgileModuleFrontController
{
    private $confirmation = false;
    private $sellerInfoMembershipCustomerRepository;

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

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

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

        $this->setMemberShipVars();

        $this->context->smarty->assign([
            'content_only' => (int) Tools::getValue('content_only'),
            'confirmation' => $this->confirmation,
        ]);

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

    protected function setMemberShipVars()
    {
        $idLang = (int) $this->context->language->id;
        $idCustomer = $this->sellerinfo->getIdCustomer();
        $membership_valid = false;
        $expiry_date = '---';
        $idCurrentMembershipTypeProduct = 0;

        $sellerInfoMembershipCustomer = $this->sellerInfoMembershipCustomerRepository
            ->findOneBy(['idCustomer' => $idCustomer]);

        if ($sellerInfoMembershipCustomer) {
            $expiry_date = $this->sellerInfoMembershipCustomerRepository
                ->getExpiryDate($sellerInfoMembershipCustomer->getIdCustomer(), $idLang);
            $today = new DateTime(date('Y-m-d H:i:s'));
            $membership_valid = ($expiry_date >= $today);

            $idCurrentMembershipTypeProduct = $sellerInfoMembershipCustomer
                ->getSellerinfoMembershipType()->getIdProduct();
        }

        $idCategory = (int) Configuration::get('AGILE_MEMBERSHIP_CID');

        $sellerinfoProductRepository = $this->entityManager->getRepository(SellerinfoProduct::class);
        $nbSllerProducts = $sellerinfoProductRepository->getCountProducts($this->sellerinfo);

        // display tariffs which available for seller
        $membershipTypeRepository = $this->entityManager->getRepository(SellerinfoMembershipType::class);
        $mproducts = $membershipTypeRepository->getMembershipProducts($this->context->language->id);
        foreach ($mproducts as $k => $product) {
            $membershipType = $membershipTypeRepository->findOneBy(['idProduct' => (int) $product['id_product']]);
            if (!$membershipType) {
                unset($mproducts[$k]);
                continue;
            }

            if (
                $membershipType->getListingMax() > 0
                && $membershipType->getListingMax() <= $nbSllerProducts
            ) {
                unset($mproducts[$k]);
                continue;
            }

            $mproducts[$k]['max_products'] = $membershipType->getListingMax();
            $mproducts[$k]['max_product_images'] = $membershipType->getProductImages();
            $mproducts[$k]['units'] = $membershipType->getUnits();
            $mproducts[$k]['interval'] = $membershipType->getIntervalMembership();
        }

        $this->context->smarty->assign([
            'nbSllerProducts' => $nbSllerProducts,
            'idCurrentMembershipTypeProduct' => $idCurrentMembershipTypeProduct,
            'membership_valid' => $membership_valid,
            'membership' => $sellerInfoMembershipCustomer,
            'expiry_date' => $expiry_date,
            'membershiptypes' => SellerInfoMembershipTypeRepository::getMembershipTypes($idCategory, $idLang, false),
            'membership_history' => $this->sellerInfoMembershipCustomerRepository->getMembershipsForCsutomer($idCustomer, $idLang),
            'mproducts' => array_values($mproducts),
            'membership_cancelmethod' => (int) Configuration::get('AGILE_MEMBERSHIP_CANCEL_METHOD'),
        ]);
    }

    public function postProcess()
    {
        $process = Tools::getValue('process');

        if ($process == 'cancel') {
            $id_membership_history = (int) Tools::getValue('id_membership_history');
            $this->sellerInfoMembershipCustomerRepository->cancelMembership($id_membership_history);
            $this->redirectBack();

            return;
        } elseif ($process == 'renew') {
            $this->prepareCart();
        } elseif ($process == 'switch') {
            $id_membership_history = $this->entityManager
                ->getRepository(SellerinfoMembershipHistory::class)
                ->getCurrentmembershipHistoryId($this->context->customer->id);

            $this->sellerInfoMembershipCustomerRepository->cancelMembership($id_membership_history);

            $this->prepareCart();
        } elseif ($process == 'purchase') {
            $this->prepareCart();
        }

        parent::postProcess();
    }

    private function prepareCart()
    {
        $id_product = (int) Tools::getValue('id_product');
        $price = Product::getPriceStatic($id_product, true, null, $decimals = 6, null, false, true, $quantity = 1);

        if ($price == 0) {
            $id_order = AgileHelperMembership::assignMembership(
                $this->context->customer,
                $id_product,
                (int) Configuration::get('AGILE_MEMBERSHIP_FREE_TRIAL_STATE')
            );

            $this->redirectBack();
        } else {
            $this->context->cart->delete();
            Tools::redirect($this->context->link->getPageLink('cart') . "?add=1&id_product=$id_product&ipa=0&token=" . Tools::getToken(false));
        }
    }

    private function redirectBack()
    {
        Tools::redirect($this->context->link->getModuleLink('agilemultisellerpro', 'mymembership', [], true));
    }
}
