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

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

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

$equipment_id = isset($_POST['equipment_id']) ? (int)$_POST['equipment_id'] : 0;
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;

if (!$equipment_id) {
    echo json_encode(['success' => false, 'message' => 'Equipment ID required']);
    exit;
}

try {
    $cart_id = $_SESSION['cart_id'];
    
    // Check stock
    $stmt = $pdo->prepare("SELECT stock_quantity FROM equipment WHERE id = ?");
    $stmt->execute([$equipment_id]);
    $equipment = $stmt->fetch();
    
    if (!$equipment) {
        echo json_encode(['success' => false, 'message' => 'Equipment not found']);
        exit;
    }
    
    if ($equipment['stock_quantity'] < $quantity) {
        echo json_encode(['success' => false, 'message' => 'Insufficient stock. Only ' . $equipment['stock_quantity'] . ' available']);
        exit;
    }
    
    // Check if item already in cart
    $stmt = $pdo->prepare("SELECT id, quantity FROM cart_items WHERE cart_id = ? AND equipment_id = ?");
    $stmt->execute([$cart_id, $equipment_id]);
    $existing = $stmt->fetch();
    
    if ($existing) {
        $new_quantity = $existing['quantity'] + $quantity;
        if ($new_quantity > $equipment['stock_quantity']) {
            echo json_encode(['success' => false, 'message' => 'Cannot add more than available stock']);
            exit;
        }
        $stmt = $pdo->prepare("UPDATE cart_items SET quantity = ? WHERE id = ?");
        $stmt->execute([$new_quantity, $existing['id']]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO cart_items (cart_id, equipment_id, quantity) VALUES (?, ?, ?)");
        $stmt->execute([$cart_id, $equipment_id, $quantity]);
    }
    
    // Get updated cart count
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(quantity), 0) as total FROM cart_items WHERE cart_id = ?");
    $stmt->execute([$cart_id]);
    $count = $stmt->fetch();
    
    echo json_encode([
        'success' => true,
        'cart_count' => (int)$count['total'],
        'message' => 'Item added to cart successfully'
    ]);
    
} catch(PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>