<?php
session_start();

// Check if index is received via POST
if (isset($_POST['index'])) {
    $index = (int) $_POST['index'];

    // Check if the cart exists in the session
    if (isset($_SESSION['purchaseCart']) && isset($_SESSION['purchaseCart'][$index])) {
        // Remove the item from the cart
        unset($_SESSION['purchaseCart'][$index]);

        // Re-index the array to prevent gaps in the indices
        $_SESSION['purchaseCart'] = array_values($_SESSION['purchaseCart']);

        // Response
        echo json_encode(['status' => 'success', 'message' => 'Item removed from cart']);
    } else {
        // Response for invalid index or empty cart
        echo json_encode(['status' => 'error', 'message' => 'Item not found in cart']);
    }
} else {
    // Invalid request handling
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}
?>
