<?php
session_start();

// Check if the cart exists in the session
if (!isset($_SESSION['cartz'])) {
    $_SESSION['cartz'] = [];
}

// Function to generate HTML content for the cart
function generateCartHTML($cart) {
    $html = '';

    foreach ($cart as $index => $item) {
        $html .= '<tr>';
        $html .= '<td>' . ($index + 1) . '</td>'; // Index + 1 for item count
        $html .= '<td>' . $item['item_name'] . '</td>';
        $html .= '<td>$' . number_format($item['price'], 2) . '</td>';
        $html .= '<td>' . $item['quantity'] . '</td>';
        $subtotal = $item['price'] * $item['quantity'];
        $html .= '<td class="text-right">$' . number_format($subtotal, 2) . '</td>';
        $html .= '</tr>';
    }

    return $html;
}

// Check the action parameter
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'getCartHTML') {
        // Generate HTML content for the cart
        $cartHTML = generateCartHTML($_SESSION['cartz']);

        // Return the HTML content in the response
        header('Content-Type: application/json');
        $response = ['success' => true, 'cartHTML' => $cartHTML];
        echo json_encode($response);
        exit;
    }
}
?>
