<?php

/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

declare(strict_types=1);

namespace Resursbank\MerchantApi\Service;

use Cart as PrestaCart;
use Context;
use Order;
use PrestaShopException;

/**
 * Cart service.
 */
class Cart
{
    /**
     * Rebuilds the shopping cart.
     *
     * @param Order $order
     * @return void
     * @throws PrestaShopException
     */
    public static function reinstate(Order $order): void
    {
        // Create a new cart
        $cart = new PrestaCart();
        $cart->id_customer = $order->id_customer;
        $cart->id_address_delivery = $order->id_address_delivery;
        $cart->id_address_invoice = $order->id_address_invoice;
        $cart->id_carrier = $order->id_carrier;
        $cart->id_currency = $order->id_currency;
        $cart->id_lang = $order->id_lang;

        // Save the new cart
        $cart->save();

        // Add products to the new cart
        foreach ($order->getProducts() as $orderProduct) {
            $cart->updateQty(
                quantity: (int) $orderProduct['product_quantity'],
                id_product: $orderProduct['id_product'],
                id_product_attribute: $orderProduct['product_attribute_id'],
                id_address_delivery: $order->id_address_delivery,
                skipAvailabilityCheckOutOfStock: true
            );
        }

        // Update the context and cookie with the new cart
        $context = Context::getContext();
        $context->cart = $cart;
        $context->cookie->id_cart = $cart->id;
        \CartRule::autoAddToCart(context: $context);
        $context->cookie->write();
    }
}
