<?php
session_start();

if (!isset($_SESSION['cartz'])) {
    $_SESSION['cartz'] = [];
}

function generateCartHTML($cart) {
    $html = '';
    $itemCount = 0;
    $totl = 0;

    foreach ($cart as $index => $item) {
        $itemCount++;

        // Check if price and quantity are numeric
        if (is_numeric($item['price']) && is_numeric($item['quantity'])) {
            $subtotal = $item['price'] * $item['quantity'];
            $totl += $subtotal; // Add the current subtotal to $totl
        }

        $html .= '<tr>';
        $html .= '<td>' . $itemCount . '</td>';
        $html .= '<td>' . htmlspecialchars($item['item_name']) . '</td>';
        $html .= '<td>$' . number_format($item['price'], 2) . '</td>';
        $html .= '<td>' . $item['quantity'] . '</td>';
        $html .= '<td class="text-end">Ksh' . number_format($subtotal, 2) . '</td>';
        $html .= '</tr>';
    }

    $html .= '<tr>';
    $html .= '<th scope="row" colspan="5" class="border-0"></th>';
    $html .= '<th scope="row" class="border-0 text-end">Total</th>';
    $html .= '<td class="border-0 text-end"><h4 class="m-0 fw-semibold">' . number_format($totl, 2) . '</h4></td>';
    $html .= '</tr>';

    return $html;
}

// Return the HTML content for the cart
header('Content-Type: application/json');
echo json_encode(['success' => true, 'cartHTML' => generateCartHTML($_SESSION['cartz'])]);
?>
