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

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

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

// Get product_id
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;

// Validate product_id
if ($product_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
    exit;
}

// Remove product from cart
remove_from_cart($product_id);

// Calculate cart totals
$cart_subtotal = get_cart_total();
$cart_total = $cart_subtotal; // In case we add shipping or discounts later

// Get cart count
$cart = get_cart();
$cart_count = 0;
foreach ($cart as $qty) {
    $cart_count += $qty;
}

// Return success response
echo json_encode([
    'success' => true,
    'message' => 'Product removed from cart',
    'cart_subtotal' => format_price($cart_subtotal),
    'cart_total' => format_price($cart_total),
    'cart_count' => $cart_count
]);