<?php
require_once __DIR__ . '/../includes/auth.php';
require_customer();
require_once __DIR__ . '/../includes/header_customer.php';
require_once __DIR__ . '/../includes/cart.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$cartId = get_or_create_cart($pdo, (int) current_user()['id']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $productId = (int) ($_POST['product_id'] ?? 0);
    $qty = (int) ($_POST['qty'] ?? 0);

    if ($action === 'update') {
        $stockStmt = $pdo->prepare('SELECT stock FROM products WHERE id = ? LIMIT 1');
        $stockStmt->execute([$productId]);
        $stock = (int) ($stockStmt->fetch()['stock'] ?? 0);
        $qty = min($qty, $stock);

        update_cart_item($pdo, $cartId, $productId, $qty);
        flash_message('success', 'Keranjang diperbarui.');
        redirect(base_url('public/index.php?page=cart'));
    }

    if ($action === 'remove') {
        update_cart_item($pdo, $cartId, $productId, 0);
        flash_message('success', 'Item dihapus dari keranjang.');
        redirect(base_url('public/index.php?page=cart'));
    }
}

$items = get_cart_items($pdo, $cartId);
$total = 0;
?>

<h2 class="fw-bold mb-3">Keranjang</h2>

<?php if (!$items): ?>
    <div class="alert error">Keranjang masih kosong.</div>
    <a class="btn" href="<?= base_url('public/index.php?page=products'); ?>">Belanja Sekarang</a>
<?php else: ?>
    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Produk</th>
                    <th>Harga</th>
                    <th>Qty</th>
                    <th>Subtotal</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $item): ?>
                    <?php $subtotal = $item['price'] * $item['qty']; $total += $subtotal; ?>
                    <tr>
                        <td>
                            <strong><?= sanitize($item['name']); ?></strong>
                        </td>
                        <td><?= format_currency($item['price']); ?></td>
                        <td style="max-width: 140px;">
                            <form method="post" class="d-flex gap-2">
                                <input type="hidden" name="action" value="update">
                                <input type="hidden" name="product_id" value="<?= (int) $item['product_id']; ?>">
                                <input class="form-control" type="number" name="qty" value="<?= (int) $item['qty']; ?>" min="1" max="<?= (int) $item['stock']; ?>">
                                <button class="btn btn-sm" type="submit">Update</button>
                            </form>
                        </td>
                        <td><?= format_currency($subtotal); ?></td>
                        <td>
                            <form method="post">
                                <input type="hidden" name="action" value="remove">
                                <input type="hidden" name="product_id" value="<?= (int) $item['product_id']; ?>">
                                <button class="btn btn-sm" type="submit">Hapus</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="d-flex justify-content-end">
        <div class="card p-3" style="min-width: 280px;">
            <div class="d-flex justify-content-between">
                <span>Total</span>
                <strong><?= format_currency($total); ?></strong>
            </div>
            <a class="btn btn-primary w-100 py-3 mt-3 shadow rounded-3 fw-bold fs-5 d-flex align-items-center justify-content-center" href="<?= base_url('public/index.php?page=checkout'); ?>" style="background: linear-gradient(135deg, var(--primary-start), var(--primary-end)); border: none;">
                <i class="bi bi-cart-check-fill me-2"></i> Checkout Sekarang
            </a>
        </div>
    </div>
<?php endif; ?>

<?php require_once __DIR__ . '/../includes/footer_customer.php'; ?>
