<?php

declare (strict_types=1);
namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout;

use Automattic\WooCommerce\StoreApi\SessionHandler;
use Automattic\WooCommerce\StoreApi\Utilities\CartController;
use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
/**
 * Loads WooCommerce session from session ID.
 */
final class SessionLoader
{
    private CartController $cart_controller;
    public function __construct(CartController $cart_controller)
    {
        $this->cart_controller = $cart_controller;
    }
    /**
     * Load WC session for the given session ID.
     *
     * We can not extend store API session handler, nor use cookie based session handler cleanly.
     * This is a bit hacky, but at least we do not have to deal with session table.
     */
    public function load(string $session_id): void
    {
        $_SERVER['HTTP_CART_TOKEN'] = CartTokenUtils::get_cart_token($session_id);
        \add_filter('woocommerce_session_handler', $session_callback = fn() => SessionHandler::class);
        $this->cart_controller->load_cart();
        $this->cart_controller->normalize_cart();
        \remove_filter('woocommerce_session_handler', $session_callback);
        unset($_SERVER['HTTP_CART_TOKEN']);
    }
    /**
     * Generate a new session ID.
     */
    public function generate_session_id(): string
    {
        return \wc_rand_hash('ucp_', 28);
    }
}
