<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Carrier;

use Adapter_ServiceLocator;
use Address;
use Cart;
use CartRule;
use Context;
use Module;
use PrestaShop\PrestaShop\Adapter\Adapter_ServiceLocator as PsAdapterServiceLocator;

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

final class CartCarrierSetter
{
    public function __construct(private readonly Context $context)
    {
    }

    public function apply(int $idCarrier): void
    {
        if ($idCarrier <= 0) {
            return;
        }

        $cart = $this->context->cart;
        if (!$cart instanceof Cart || !$cart->id) {
            return;
        }

        $idAddressDelivery = (int) $cart->id_address_delivery;
        if ($idAddressDelivery <= 0 && $cart->id_customer) {
            $idAddressDelivery = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer);
        }
        if ($idAddressDelivery <= 0) {
            return;
        }

        $deliveryOption = [$idAddressDelivery => $idCarrier . ','];

        $cart->setDeliveryOption($deliveryOption);
        $cart->id_carrier = $idCarrier;
        $cart->update();

        if (Module::isEnabled('thecheckout')) {
            $this->syncTheCheckout($deliveryOption);
        }

        CartRule::autoRemoveFromCart($this->context);
        CartRule::autoAddToCart($this->context);
    }

    /**
     * @param array<int, string> $deliveryOption
     */
    private function syncTheCheckout(array $deliveryOption): void
    {
        $cookie = $this->context->cookie;
        $opcFormRadios = [];
        if (!empty($cookie->opc_form_radios)) {
            $decoded = json_decode($cookie->opc_form_radios, true);
            if (is_array($decoded)) {
                $opcFormRadios = $decoded;
            }
        }
        $opcFormRadios['delivery_option'] = $deliveryOption;
        $cookie->opc_form_radios = json_encode($opcFormRadios);

        if (class_exists(PsAdapterServiceLocator::class)) {
            $checkoutSession = PsAdapterServiceLocator::get('prestashop.core.checkout.checkout_session');
            if (is_object($checkoutSession) && method_exists($checkoutSession, 'setDeliveryOption')) {
                $checkoutSession->setDeliveryOption($deliveryOption);
            }
        } elseif (class_exists(Adapter_ServiceLocator::class)) {
            $checkoutSession = Adapter_ServiceLocator::get('prestashop.core.checkout.checkout_session');
            if (is_object($checkoutSession) && method_exists($checkoutSession, 'setDeliveryOption')) {
                $checkoutSession->setDeliveryOption($deliveryOption);
            }
        }

        $cookie->write();
    }
}
