<?php
session_start();
include "db.php";

if (!isset($_POST['id'])) {
    echo json_encode(["status" => "error", "message" => "Missing product ID"]);
    exit;
}

$id     = intval($_POST['id']);
$size   = $_POST['size'];
$garlic = $_POST['garlic'];  // with / without
$spice  = $_POST['spice'];
$qty    = intval($_POST['qty']);

if ($qty < 1) $qty = 1;

/* -------------------------------------------
   FETCH PRODUCT FROM DATABASE
-------------------------------------------- */
$stmt = $pdo->prepare("SELECT price_variants FROM products WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo json_encode(["status" => "error", "message" => "Product not found"]);
    exit;
}

/* -------------------------------------------
   DECODE PRICE VARIANTS
   Example:
   {
     "250g":{"with":220,"without":240},
     "500g":{"with":520,"without":570}
   }
-------------------------------------------- */
$price_variants = json_decode($product['price_variants'], true);

if (!isset($price_variants[$size][$garlic])) {
    echo json_encode(["status" => "error", "message" => "Invalid price variant"]);
    exit;
}

$price = $price_variants[$size][$garlic]; // THIS IS THE REAL PRICE

/* -------------------------------------------
   CREATE CART ARRAY
-------------------------------------------- */
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

$key = $id . "_" . $size . "_" . $garlic . "_" . $spice;

/* If item already exists → update qty */
if (isset($_SESSION['cart'][$key])) {
    $_SESSION['cart'][$key]['qty'] += $qty;
} else {
    $_SESSION['cart'][$key] = [
        "product_id" => $id,
        "size"       => $size,
        "garlic"     => $garlic,
        "spice"      => $spice,
        "qty"        => $qty,
        "price"      => $price   // ⭐ VERY IMPORTANT
    ];
}

/* -------------------------------------------
   UPDATE CART COUNT FOR FRONTEND
-------------------------------------------- */
$cartCount = array_sum(array_column($_SESSION['cart'], 'qty'));

echo json_encode([
    "status" => "success",
    "count" => $cartCount
]);
exit;

?>
