<?php
require_once '../config.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false]);
    exit;
}

$cart_item_id = isset($_POST['cart_item_id']) ? (int)$_POST['cart_item_id'] : 0;
$change = isset($_POST['change']) ? (int)$_POST['change'] : 0;

if (!$cart_item_id) {
    echo json_encode(['success' => false]);
    exit;
}

try {
    // Get current quantity and equipment
    $stmt = $pdo->prepare("
        SELECT ci.quantity, ci.equipment_id, e.stock_quantity 
        FROM cart_items ci 
        JOIN equipment e ON ci.equipment_id = e.id 
        WHERE ci.id = ?
    ");
    $stmt->execute([$cart_item_id]);
    $item = $stmt->fetch();
    
    if ($item) {
        $new_quantity = $item['quantity'] + $change;
        
        if ($new_quantity <= 0) {
            $stmt = $pdo->prepare("DELETE FROM cart_items WHERE id = ?");
            $stmt->execute([$cart_item_id]);
        } elseif ($new_quantity > $item['stock_quantity']) {
            echo json_encode(['success' => false, 'message' => 'Insufficient stock']);
            exit;
        } else {
            $stmt = $pdo->prepare("UPDATE cart_items SET quantity = ? WHERE id = ?");
            $stmt->execute([$new_quantity, $cart_item_id]);
        }
        
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
} catch(PDOException $e) {
    echo json_encode(['success' => false]);
}
?>