<?php
session_start();
include "db.php";

// If cart empty
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
    echo json_encode([
        "html" => '<div style="text-align:center; padding:40px;">Your cart is empty.</div>',
        "total" => "0.00",
        "count" => 0
    ]);
    exit;
}

$html = "";
$total = 0;
$count = 0;

foreach ($_SESSION['cart'] as $key => $c) {
    $count += $c['qty'];
    $subtotal = $c['qty'] * $c['price'];
    $total += $subtotal;

    // fetch product for image + name
    $stmt = $pdo->prepare("SELECT product_name, images FROM products WHERE id=? LIMIT 1");
    $stmt->execute([$c['product_id']]);
    $p = $stmt->fetch();

    $imgs = json_decode($p['images'], true);
    $img = !empty($imgs[0]) ? "https://lalitavarahifoods.com/" . ltrim($imgs[0], "/") : "https://placehold.co/60";

    $html .= '
        <div class="mc-item">
            <img src="'.$img.'">
            <div class="details">
                <strong>'.$p['product_name'].'</strong><br>
                Qty: '.$c['qty'].'<br>
                Rs. '.number_format($subtotal,2).'
            </div>
        </div>
    ';
}

echo json_encode([
    "html" => $html,
    "total" => number_format($total, 2),
    "count" => $count
]);
exit;
