<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

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

$cart = $_SESSION['cart'];

if (empty($cart)) {
    echo json_encode([
        'html' => '
            <div class="alert alert-info">
                Cart is empty.
            </div>
        ',
        'total' => number_format(0, 2)
    ]);
    exit;
}

$itemIds = array_keys($cart);
$placeholders = implode(',', array_fill(0, count($itemIds), '?'));

$sql = "SELECT * FROM items WHERE id IN ($placeholders)";
$stmt = $db->prepare($sql);
$stmt->execute($itemIds);

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

$itemMap = [];
foreach ($items as $item) {
    $itemMap[$item['id']] = $item;
}

$html = '
<table class="table table-bordered cart-table">
    <thead>
        <tr>
            <th>Item</th>
            <th width="80">Qty</th>
            <th width="100">Rate</th>
            <th width="100">Total</th>
            <th width="120">Action</th>
        </tr>
    </thead>
    <tbody>
';

$grandTotal = 0;
$totalGst = 0;

foreach ($cart as $itemId => $qty) {
    if (!isset($itemMap[$itemId])) {
        continue;
    }

    $item = $itemMap[$itemId];

    $name = htmlspecialchars($item['name']);
    $price = (float)$item['price'];
    $gst = isset($item['gst']) ? (float)$item['gst'] : 0;

    $lineTotal = $price * $qty;
    $lineGst = ($lineTotal * $gst) / 100;

    $grandTotal += $lineTotal + $lineGst;
    $totalGst += $lineGst;

    $html .= '
        <tr>
            <td>' . $name . '</td>

            <td class="text-center">
                ' . $qty . '
            </td>

            <td>
                ₹ ' . number_format($price, 2) . '
            </td>

            <td>
                ₹ ' . number_format($lineTotal + $lineGst, 2) . '
            </td>

            <td>
                <button
                    class="btn btn-sm btn-success"
                    onclick="updateCart(' . $itemId . ', \'plus\')"
                >
                    +
                </button>

                <button
                    class="btn btn-sm btn-warning"
                    onclick="updateCart(' . $itemId . ', \'minus\')"
                >
                    -
                </button>

                <button
                    class="btn btn-sm btn-danger"
                    onclick="removeCart(' . $itemId . ')"
                >
                    X
                </button>
            </td>
        </tr>
    ';
}

$html .= '
    </tbody>
</table>

<div class="text-end">
    <p><strong>GST:</strong> ₹ ' . number_format($totalGst, 2) . '</p>
</div>
';

echo json_encode([
    'html' => $html,
    'total' => number_format($grandTotal, 2)
]);
?>