<?php
// Include DB connection
include './db.php';

// Start session
session_start();

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit();
}

$user_id = $_SESSION['user_id']; // Get user ID

// Decode JSON request body
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);
$cart_item_id = $data['id'] ?? null; // Get cart item ID from JSON input

if ($cart_item_id) {
    // Delete item from cart
    $stmt = $conn->prepare("DELETE FROM cart WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $cart_item_id, $user_id);
    if ($stmt->execute()) {
        // Query updated cart items
        $cart_html = '';
        $fetch_cart = $conn->prepare("SELECT id, machine_id, machine_type, price FROM cart WHERE user_id = ?");
        $fetch_cart->bind_param("i", $user_id);
        $fetch_cart->execute();
        $fetch_cart->bind_result($id, $machine_id, $machine_type, $item_price);

        while ($fetch_cart->fetch()) {
            $cart_html .= "
                <tr>
                    <td>" . htmlspecialchars($machine_type) . "</td>
                    <td>" . htmlspecialchars($machine_id) . "</td>
                    <td>Rp " . number_format($item_price, 0, ',', '.') . "</td>
                    <td>
                        <button class='btn btn-danger shadow btn-xs sharp remove-from-cart' data-id='" . htmlspecialchars($id) . "'>
                            <i class='fa fa-trash'></i>
                        </button>
                    </td>
                </tr>
            ";
        }
        $fetch_cart->close();

        echo json_encode(['success' => true, 'cart_html' => $cart_html]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to remove item from cart']);
    }
    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid cart item ID']);
}

$conn->close();
?>
