<?php
session_start();
include(__DIR__ . '/../config.php');
include(__DIR__ . '/../header/header.php');

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

<section class="py-5">
<div class="container">

<h2 class="mb-4">🛒 Your Cart</h2>

<!-- ALERT MESSAGES -->
<?php if(isset($_SESSION['error'])): ?>
<div class="alert alert-danger">
    <?= $_SESSION['error']; unset($_SESSION['error']); ?>
</div>
<?php endif; ?>

<?php if(isset($_SESSION['success'])): ?>
<div class="alert alert-success">
    <?= $_SESSION['success']; unset($_SESSION['success']); ?>
</div>
<?php endif; ?>

<?php if(empty($cart)): ?>

<div class="alert alert-warning">
    Your cart is empty.
</div>

<a href="products.php" class="btn btn-primary">Continue Shopping</a>

<?php else: ?>

<form method="POST" action="cart.php">

<div class="table-responsive">
<table class="table table-bordered align-middle">

<thead class="table-light">
<tr>
<th>Product</th>
<th>Price</th>
<th>Stock</th>
<th>Quantity</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>

<tbody>

<?php
$total = 0;
$totalItems = 0;

foreach($cart as $id => $qty):

$stmt = $pdo->prepare("SELECT * FROM products WHERE id=?");
$stmt->execute([$id]);
$p = $stmt->fetch();

if(!$p) continue;

$subtotal = $p['price'] * $qty;
$total += $subtotal;
$totalItems += $qty;
?>

<tr>

<td>
    <strong><?= htmlspecialchars($p['name']); ?></strong>
</td>

<td>
    KES <?= number_format($p['price']); ?>
</td>

<td>
    <?= $p['stock']; ?>
</td>

<td style="width:120px;">
    <input type="number" 
           name="qty[<?= $id ?>]" 
           value="<?= $qty ?>" 
           min="1" 
           max="<?= $p['stock']; ?>"
           class="form-control">
</td>

<td>
    KES <?= number_format($subtotal); ?>
</td>

<td>
    <a href="cart.php?remove=<?= $id ?>" 
       class="btn btn-danger btn-sm">
       Remove
    </a>
</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>
</div>

<!-- SUMMARY -->
<div class="row mt-4">

<div class="col-md-6">
    <button type="submit" name="update" class="btn btn-primary">
        🔄 Update Cart
    </button>

    <a href="products.php" class="btn btn-outline-secondary">
        ← Continue Shopping
    </a>
</div>

<div class="col-md-6 text-end">

    <h5>Total Items: <strong><?= $totalItems; ?></strong></h5>

    <h4>
        Total: 
        <span class="text-primary">
            KES <?= number_format($total); ?>
        </span>
    </h4>

    <form method="POST" action="place_order.php">
        <input type="hidden" name="total" value="<?= $total; ?>">

        <button type="submit" class="btn btn-success mt-2">
            ✅ Place Order
        </button>
    </form>

</div>

</div>

</form>

<?php endif; ?>

</div>
</section>

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