<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

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

$itemId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$action = $_GET['action'] ?? '';

if ($itemId <= 0) {
    exit('Invalid item');
}

if (!isset($_SESSION['cart'][$itemId])) {
    exit('Item not in cart');
}

$stmt = $db->prepare("SELECT stock FROM items WHERE id = ?");
$stmt->execute([$itemId]);
$item = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$item) {
    exit('Item not found');
}

$currentQty = $_SESSION['cart'][$itemId];

if ($action === 'plus') {
    if ($currentQty < (float)$item['stock']) {
        $_SESSION['cart'][$itemId]++;
    }
}

if ($action === 'minus') {
    $_SESSION['cart'][$itemId]--;

    if ($_SESSION['cart'][$itemId] <= 0) {
        unset($_SESSION['cart'][$itemId]);
    }
}

echo 'success';
?>