<?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\SellerinfoCartCarrier;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoShipping;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;

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

class AgileMultiSellerProAjaxShippingModuleFrontController extends AgileModuleFrontController
{
    public $auth = false;

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

        $action = Tools::getValue('action');

        if ($action == 'setSellerCartCarrier') {
            $this->setSellerCartCarrier();
        }

        exit;
    }

    public function setSellerCartCarrier()
    {
        $sellerinfoCartCarrierRepository = $this->entityManager->getRepository(SellerinfoCartCarrier::class);

        $idSellerInfo = isset(Tools::getValue('requestData')['idSellerInfo']) ?
            (int) Tools::getValue('requestData')['idSellerInfo'] : false;

        $idCarrierReference = isset(Tools::getValue('requestData')['idCarrierReference']) ?
            (int) Tools::getValue('requestData')['idCarrierReference'] : false;

        $idCart = isset(Tools::getValue('requestData')['idCart']) ?
            (int) Tools::getValue('requestData')['idCart'] : false;

        $idLocationCarrier = isset(Tools::getValue('requestData')['idLocationCarrier']) ?
            (int) Tools::getValue('requestData')['idLocationCarrier'] : null;

        if ($idSellerInfo === false || $idCarrierReference === false || $idCart === false) {
            $this->ajaxRender(json_encode([
                'success' => false,
                'message' => $this->trans('Error - not valid data.', [], 'Modules.Agilemultisellerpro.Shipping'),
                'requestData' => Tools::getAllValues(),
            ]));

            return false;
        }

        $sellerinfoCartCarrier = $sellerinfoCartCarrierRepository->findOneBy([
            'idSellerInfo' => $idSellerInfo,
            'idCart' => $idCart,
        ]);

        if (!$sellerinfoCartCarrier) {
            $sellerinfoCartCarrier = new SellerinfoCartCarrier();
            $sellerinfoCartCarrier->setIdSellerInfo($idSellerInfo);
            $sellerinfoCartCarrier->setIdCart($idCart);
        }

        $sellerinfoShippingRepository = $this->entityManager->getRepository(SellerinfoShipping::class);

        $cart = new Cart($idCart);

        $products = $cart->getProducts();

        $idZone = AgileHelper::getZoneID(
            $cart->id_address_delivery,
            $cart->id_customer
        );

        $shippingData = $sellerinfoShippingRepository->groupProductsBySellerAndCalculateShipping(
            $products,
            $idZone,
            $idCart
        );

        $sellerinfoCartCarrier->setIdCarrierReference($idCarrierReference);
        $sellerinfoCartCarrier->setWeight($shippingData[$idSellerInfo]['weightSum']);
        $sellerinfoCartCarrier->setShippingCost(
            $shippingData[$idSellerInfo]['carriers'][$idCarrierReference]['carrierShippingPriceWithTax']
        );
        $sellerinfoCartCarrier->setIdLocationCarrier($idLocationCarrier);

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

        $this->ajaxRender(json_encode([
            'success' => true,
            'message' => $this->trans('Ok', [], 'Modules.Agilemultisellerpro.Ajaxshipping'),
            'requestData' => Tools::getAllValues(),
        ]));
    }
}
