<?php
// actions/update_cart.php
session_start();
require_once('../config/db.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../cart.php');
    exit;
}

$index = isset($_POST['index']) ? (int)$_POST['index'] : -1;
$qty = max(1, (int)($_POST['Qty'] ?? 1));

if (!isset($_SESSION['cart'][$index])) {
    header('Location: ../cart.php');
    exit;
}

$item = &$_SESSION['cart'][$index];

// validate against stock
$stmt = $pdo->prepare("SELECT StockQuantity FROM products WHERE ProductID = ?");
$stmt->execute([$item['ProductID']]);
$row = $stmt->fetch();
$stock = $row ? (int)$row['StockQuantity'] : 0;
if ($qty > $stock) {
    $_SESSION['error'] = 'Requested quantity exceeds stock.';
    header('Location: ../cart.php');
    exit;
}

$item['Qty'] = $qty;
$item['Total'] = number_format($qty * $item['Price'], 2, '.', '');

header('Location: ../cart.php');
exit;
