<?php
require_once "includes/config.php";
require_once "includes/functions.php";
include "includes/header.php";

$cart = $_SESSION['cart'] ?? [];

if (empty($cart)) {
  echo '<div class="alert alert-info">Your cart is empty.</div>';
  echo '<a href="/myukstore/index.php" class="btn btn-dark">Continue Shopping</a>';
  include "includes/footer.php";
  exit;
}

$ids = implode(',', array_keys($cart));
$stmt = $pdo->query("SELECT * FROM products WHERE id IN ($ids)");
$products = $stmt->fetchAll();

$total = 0;
?>

<h2>Your Cart</h2>

<table class="table table-bordered align-middle">
  <thead class="table-dark">
    <tr>
      <th>Product</th>
      <th>Price</th>
      <th width="120">Qty</th>
      <th>Subtotal</th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <?php foreach ($products as $p): 
      $qty = $cart[$p['id']];
      $sub = $qty * $p['price'];
      $total += $sub;
    ?>
    <tr>
      <td>
        <img src="<?= product_image($p['image_url']) ?>" width="60">
        <?= e($p['title']) ?>
      </td>
      <td>£<?= e($p['price']) ?></td>
      <td><?= $qty ?></td>
      <td>£<?= number_format($sub,2) ?></td>
      <td>
        <a href="/myukstore/cart_remove.php?id=<?= $p['id'] ?>"
           class="btn btn-sm btn-danger">Remove</a>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<h4>Total: £<?= number_format($total,2) ?></h4>

<?php if (!is_logged_in()): ?>
  <a href="/myukstore/auth/login.php?redirect=/myukstore/checkout.php"
     class="btn btn-success">
     Login to Checkout
  </a>
<?php else: ?>
  <a href="/myukstore/checkout.php" class="btn btn-success">
    Proceed to Checkout
  </a>
<?php endif; ?>

<?php include "includes/footer.php"; ?>
