<?php
// sales/cart.php
session_start();
$pageTitle = 'Cart';
require_once('./config/db.php');
require_once("./includes/auth.php");
include('./includes/header.php');

$cart = $_SESSION['cart'] ?? [];
$total = 0;
foreach ($cart as $c) $total += (float)$c['Total'];
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h3><i class="bi bi-basket3"></i> Cart</h3>
  <div>
    <a href="sales.php" class="btn btn-outline-secondary">Continue shopping</a>
    <a href="checkout.php" class="btn btn-success ms-2 <?= empty($cart) ? 'disabled' : '' ?>">Checkout</a>
  </div>
</div>

<div class="card shadow-sm border-0">
  <div class="card-body">
    <?php if (empty($cart)): ?>
      <div class="text-center py-4 text-muted">Your cart is empty</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
            <tr><th>Product</th><th>Price</th><th>Qty</th><th>Total</th><th></th></tr>
          </thead>
          <tbody>
            <?php foreach ($cart as $index => $c): ?>
              <tr>
                <td><?= htmlspecialchars($c['Name']) ?></td>
                <td><?= number_format($c['Price'],2) ?></td>
                <td>
                  <form method="post" action="./actions/update_cart.php" class="d-flex gap-2 align-items-center">
                    <input type="hidden" name="index" value="<?= $index ?>">
                    <input type="number" name="Qty" value="<?= (int)$c['Qty'] ?>" min="1" class="form-control form-control-sm" style="width:90px">
                    <button class="btn btn-sm btn-primary" type="submit">Update</button>
                  </form>
                </td>
                <td><?= number_format($c['Total'],2) ?></td>
                <td>
                  <form method="post" action="./actions/remove_from_cart.php" onsubmit="return confirm('Remove item?');">
                    <input type="hidden" name="index" value="<?= $index ?>">
                    <button class="btn btn-sm btn-danger">Remove</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="d-flex justify-content-end mt-3">
        <div class="text-end">
          <div class="fw-semibold">Subtotal: <?= number_format($total,2) ?></div>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php include('./includes/footer.php'); ?>
