<?php

// Sepet oturumda "ürünId-varyantId" => adet şeklinde tutulur.
function cart()
{
    return sess('cart', []);
}

function cart_key($product_id, $variant_id = 0)
{
    return (int) $product_id . '-' . (int) $variant_id;
}

function cart_qty($key)
{
    return cart()[$key] ?? 0;
}

function cart_set($key, $qty)
{
    $cart = cart();
    if ($qty < 1) {
        unset($cart[$key]);
    } else {
        $cart[$key] = (int) $qty;
    }
    sess_set('cart', $cart);
}

function cart_add($key, $qty = 1)
{
    cart_set($key, cart_qty($key) + max(1, (int) $qty));
}

function cart_remove($key)
{
    cart_set($key, 0);
}

function cart_clear()
{
    sess_forget('cart');
    sess_forget('coupon');
}

function cart_count()
{
    return array_sum(cart());
}

// Sepete eklenecek ürün ve varyantı bulur, fiyat ve stokla birlikte döner.
function cart_product($product_id, $variant_id = 0)
{
    $product = db_one('SELECT * FROM products WHERE id = ? AND status = 1', [$product_id]);
    if (!$product) {
        return null;
    }

    $variants = product_variants($product['id']);
    if ($variants) {
        $variant = $variants[$variant_id] ?? null;
        if (!$variant) {
            return null;
        }
        $product['variant_id'] = $variant['id'];
        $product['variant'] = $variant['name'];
        $product['price'] = $variant['price'] ?? $product['price'];
        $product['stock'] = $variant['stock'];
    } else {
        $product['variant_id'] = null;
        $product['variant'] = null;
    }

    $product['key'] = cart_key($product['id'], $product['variant_id']);
    return $product;
}

// Sepetteki ürünleri güncel fiyat ve stokla getirir, oturumdaki adetleri de düzeltir.
function cart_items()
{
    $items = [];
    $clean = [];
    foreach (cart() as $key => $qty) {
        [$product_id, $variant_id] = array_map('intval', explode('-', $key) + [0, 0]);
        $item = cart_product($product_id, $variant_id);
        if (!$item) {
            continue;
        }
        $item['qty'] = min($qty, max(0, $item['stock']));
        if ($item['qty'] < 1) {
            continue;
        }
        $item['line_total'] = $item['price'] * $item['qty'];
        $items[] = $item;
        $clean[$key] = $item['qty'];
    }

    sess_set('cart', $clean);
    return $items;
}

// $city verilirse o şehre özel kargo kuralı uygulanır.
function cart_totals($items = null, $city = null)
{
    $items = $items ?? cart_items();
    $subtotal = array_sum(array_column($items, 'line_total'));
    $coupon = $items ? cart_coupon($subtotal) : null;
    $discount = $coupon ? $coupon['discount'] : 0;

    $rule = shipping_rule($city);
    $free_limit = (float) ($rule && $rule['free_limit'] !== null ? $rule['free_limit'] : setting('free_shipping_limit', 0));
    $shipping = (float) ($rule ? $rule['cost'] : setting('shipping_cost', 0));
    if (!$items || ($free_limit > 0 && $subtotal - $discount >= $free_limit)) {
        $shipping = 0;
    }

    return [
        'subtotal'  => $subtotal,
        'discount'  => $discount,
        'coupon'    => $coupon,
        'shipping'  => $shipping,
        'total'     => max(0, $subtotal - $discount) + $shipping,
        'free_left' => $free_limit > 0 && $items ? max(0, $free_limit - ($subtotal - $discount)) : 0,
        'free_limit' => $free_limit,
        'tax'        => tax_included(max(0, $subtotal - $discount) + $shipping),
    ];
}

// AJAX cevaplarına sepetin güncel hâlini ekler.
function cart_payload()
{
    return [
        'cart_count' => cart_count(),
        'mini_cart'  => render('mini-cart'),
        'cart_html'  => render('cart-content'),
    ];
}
