<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
include __DIR__ . '/../includes/header.php';

$cart = $_SESSION['cart'] ?? [];
$total = 0; $items = [];
if (!empty($cart)) {
  $ids = implode(',', array_map('intval', array_keys($cart)));
  $res = db()->query("SELECT id, title, price, image_main FROM products WHERE id IN ($ids)");
  while ($row = $res->fetch_assoc()) {
    $qty = $cart[$row['id']];
    $row['qty'] = $qty;
    $row['line_total'] = $qty * $row['price'];
    $total += $row['line_total'];
    $items[] = $row;
  }
}
?>
<div class="container glass-card" style="padding: 16px;">
  <div class="section-title">
    <h2>Cart</h2>
    <p>Review your selected products</p>
  </div>
  <?php if (!$items): ?>
    <div class="alert">Your cart is empty.</div>
  <?php else: ?>
    <table class="table">
      <thead><tr><th>Product</th><th>Qty</th><th>Price</th><th>Total</th></tr></thead>
      <tbody>
        <?php foreach ($items as $it): ?>
          <tr>
            <td>
              <img src="<?php echo htmlspecialchars($it['image_main']); ?>" alt="" style="width:60px;height:60px;object-fit:cover;border-radius:8px;margin-right:8px;vertical-align:middle">
              <?php echo htmlspecialchars($it['title']); ?>
            </td>
            <td><?php echo (int)$it['qty']; ?></td>
            <td>BDT <?php echo number_format($it['price'], 2); ?></td>
            <td>BDT <?php echo number_format($it['line_total'], 2); ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <div style="text-align:right;margin-top:10px;">
      <strong>Grand Total: BDT <?php echo number_format($total, 2); ?></strong>
    </div>
    <div style="text-align:right;margin-top:10px;">
      <a class="btn" href="/WATCHING/pages/checkout.php">Proceed to Checkout</a>
    </div>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>