<?php
require_once __DIR__ . '/config/database.php';
header('Content-Type: application/json');

$idx = (int)($_POST['idx'] ?? -1);
$qty = (int)($_POST['qty'] ?? 0);

if (!isset($_SESSION['checkout_items']) || !array_key_exists($idx, $_SESSION['checkout_items'])) {
    echo json_encode(['success' => false]);
    exit;
}

if ($qty <= 0) {
    // Remove item
    array_splice($_SESSION['checkout_items'], $idx, 1);
} else {
    $_SESSION['checkout_items'][$idx]['quantity'] = $qty;
}

$count = 0;
foreach ($_SESSION['checkout_items'] as $item) $count += $item['quantity'];

echo json_encode(['success' => true, 'count' => $count]);
