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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401); // Unauthorized
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit();
}

try {
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    
    if ($product_id <= 0) {
        throw new Exception('Invalid product ID');
    }
    
    // Verify the item exists in the user's cart before attempting to delete
    $stmt = $pdo->prepare("SELECT id FROM cart WHERE user_id = ? AND product_id = ?");
    $stmt->execute([$_SESSION['user_id'], $product_id]);
    $cart_item = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$cart_item) {
        throw new Exception('Item not found in your cart');
    }
    
    // Remove cart item from database
    $result = removeCartItem($pdo, $_SESSION['user_id'], $product_id);
    
    if (!$result) {
        throw new Exception('Failed to remove item from cart');
    }
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Item removed from cart successfully',
        'product_id' => $product_id
    ]);
    
} catch (Exception $e) {
    error_log("Cart remove error: " . $e->getMessage());
    http_response_code(500); // Internal Server Error
    echo json_encode(['success' => false, 'message' => 'Error removing item from cart: ' . $e->getMessage()]);
}

exit();
?>