<?php

function get_cart()
{
    return $_SESSION['cart'] ?? [];
}

function save_cart($cart)
{
    $_SESSION['cart'] = $cart;
}

function cart_item_key($productId, $variationId = null)
{
    $productId = (int) $productId;
    $variationId = $variationId ? (int) $variationId : 0;

    return $productId . ':' . $variationId;
}

function add_to_cart($productId, $quantity = 1, $variationId = null)
{
    $cart = get_cart();

    $productId = (int) $productId;
    $variationId = $variationId ? (int) $variationId : null;
    $quantity = max(1, (int) $quantity);

    $key = cart_item_key($productId, $variationId);

    if (isset($cart[$key])) {
        $cart[$key]['quantity'] += $quantity;
    } else {
        $cart[$key] = [
            'product_id' => $productId,
            'variation_id' => $variationId,
            'quantity' => $quantity,
        ];
    }

    save_cart($cart);
}

function update_cart_item($cartKey, $quantity)
{
    $cart = get_cart();
    $quantity = (int) $quantity;

    if ($quantity <= 0) {
        unset($cart[$cartKey]);
    } elseif (isset($cart[$cartKey])) {
        $cart[$cartKey]['quantity'] = $quantity;
    }

    save_cart($cart);
}

function remove_cart_item($cartKey)
{
    $cart = get_cart();

    unset($cart[$cartKey]);

    save_cart($cart);
}

function clear_cart()
{
    unset($_SESSION['cart']);
}

function cart_count()
{
    $count = 0;

    foreach (get_cart() as $item) {
        $count += (int) $item['quantity'];
    }

    return $count;
}