<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    exit('Unauthorized');
}

include_once "../config/database.php";

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

if (
    !isset($_POST['id']) ||
    !isset($_POST['qty']) ||
    !is_numeric($_POST['id']) ||
    !is_numeric($_POST['qty'])
) {
    exit('Invalid Request');
}

$product_id = (int)$_POST['id'];
$qty        = (int)$_POST['qty'];

if ($qty <= 0) {
    unset($_SESSION['cart'][$product_id]);
    exit('success');
}

$sql = "SELECT
            stock
        FROM products
        WHERE id = {$product_id}
        AND status = 1
        LIMIT 1";

$result = mysqli_query($conn, $sql);

if (!$result || mysqli_num_rows($result) == 0) {
    exit('Product Not Found');
}

$product = mysqli_fetch_assoc($result);

if ($qty > (int)$product['stock']) {
    exit('Insufficient Stock');
}

if (isset($_SESSION['cart'][$product_id])) {
    $_SESSION['cart'][$product_id]['qty'] = $qty;
}

echo "success";
?>