<?php
require_once __DIR__ . '/includes/header.php';

// Handle Cart Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    
    if ($product_id > 0) {
        if ($action === 'update' && isset($_POST['quantity'])) {
            $qty = intval($_POST['quantity']);
            if ($qty <= 0) {
                unset($_SESSION['cart'][$product_id]);
            } else {
                $_SESSION['cart'][$product_id] = $qty;
            }
            header("Location: cart.php");
            exit;
        } elseif ($action === 'remove') {
            unset($_SESSION['cart'][$product_id]);
            header("Location: cart.php");
            exit;
        }
    }
}

// Fetch all product details for items in the cart
$cart_items = [];
$subtotal = 0;

if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
    $placeholders = implode(',', array_fill(0, count($_SESSION['cart']), '?'));
    
    try {
        $stmt = $pdo->prepare("SELECT id, name, price, image, stock FROM products WHERE id IN ($placeholders)");
        $stmt->execute(array_keys($_SESSION['cart']));
        $db_items = $stmt->fetchAll();
        
        foreach ($db_items as $item) {
            $pid = $item['id'];
            $qty = $_SESSION['cart'][$pid];
            $item_total = $item['price'] * $qty;
            $subtotal += $item_total;
            
            $cart_items[] = [
                'id' => $pid,
                'name' => $item['name'],
                'price' => $item['price'],
                'image' => $item['image'],
                'quantity' => $qty,
                'total' => $item_total
            ];
        }
    } catch (Exception $e) {
        // Silently clear or handle database issues
    }
}

$shipping = ($subtotal > 20000 || $subtotal == 0) ? 0 : 450;
$grand_total = $subtotal + $shipping;
?>

<!-- Banner -->
<section class="py-4 bg-black border-bottom border-dark">
    <div class="container text-center">
        <h1 class="text-white fw-bold mb-0">Your Shopping Bag</h1>
        <p class="text-warning small text-uppercase fw-bold mb-0 mt-1" style="letter-spacing: 2px;">Atelier Concierge</p>
    </div>
</section>

<!-- Cart Section -->
<section class="py-5" style="background-color: var(--bg-dark); min-height: 60vh;">
    <div class="container">
        
        <?php if (empty($cart_items)): ?>
            <!-- Empty Cart -->
            <div class="text-center py-5">
                <div class="py-5" style="background-color: var(--bg-card); border-radius: 15px; border: 1px solid rgba(255,255,255,0.05); max-width: 600px; margin: 0 auto;">
                    <i class="fa-solid fa-bag-shopping text-warning display-1 mb-4"></i>
                    <h3 class="text-white fw-bold">Your Atelier Bag is Empty</h3>
                    <p class="text-gray small px-4 mb-4">You have no items in your boutique bag. Browse our curated seasonal collections of bespoke clothing, footwear, and accessory masterpieces.</p>
                    <a href="shop.php" class="btn btn-warning rounded-pill px-5 py-3 fw-bold text-uppercase fs-7 text-black" style="letter-spacing: 1px;">Start Shopping</a>
                </div>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <!-- Cart Items List (Left) -->
                <div class="col-lg-8">
                    <div class="card bg-black border-secondary text-white p-4 rounded-4" style="border-color: rgba(255,255,255,0.08) !important;">
                        <h4 class="fw-bold mb-4" style="font-family: var(--font-heading);">Couture Items</h4>
                        
                        <div class="table-responsive">
                            <table class="table table-dark table-hover align-middle border-secondary m-0">
                                <thead>
                                    <tr class="text-uppercase small text-muted border-secondary" style="font-size: 0.75rem; letter-spacing: 1px;">
                                        <th scope="col" style="background: transparent;">Product</th>
                                        <th scope="col" class="text-center" style="background: transparent;">Price</th>
                                        <th scope="col" class="text-center" style="background: transparent;">Quantity</th>
                                        <th scope="col" class="text-end" style="background: transparent;">Total</th>
                                        <th scope="col" style="background: transparent;"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($cart_items as $item): ?>
                                        <tr class="border-secondary">
                                            <!-- Product Details -->
                                            <td style="background: transparent;">
                                                <div class="d-flex align-items-center gap-3">
                                                    <img src="assets/images/<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" class="rounded" style="width: 70px; height: 70px; object-fit: cover; border: 1px solid rgba(255,255,255,0.1);">
                                                    <div>
                                                        <h5 class="fs-6 fw-bold mb-1"><a href="product.php?id=<?php echo $item['id']; ?>" class="text-white text-decoration-none hover-gold"><?php echo htmlspecialchars($item['name']); ?></a></h5>
                                                        <span class="text-muted small d-block mt-1" style="font-size: 0.7rem;">
                                                            Couture Chosen: Size <strong class="text-white"><?php echo htmlspecialchars($_SESSION['cart_details'][$item['id']]['size'] ?? 'M'); ?></strong> &nbsp;|&nbsp; Color <strong class="text-white"><?php echo htmlspecialchars($_SESSION['cart_details'][$item['id']]['color'] ?? 'Midnight Black'); ?></strong>
                                                        </span>
                                                    </div>
                                                </div>
                                            </td>
                                            
                                            <!-- Price -->
                                            <td class="text-center" style="background: transparent;">
                                                LKR <?php echo number_format($item['price'], 2); ?>
                                            </td>
                                            
                                            <!-- Quantity Update Form -->
                                            <td class="text-center" style="background: transparent;">
                                                <form action="cart.php" method="POST" class="d-inline-block">
                                                    <input type="hidden" name="action" value="update">
                                                    <input type="hidden" name="product_id" value="<?php echo $item['id']; ?>">
                                                    <div class="input-group input-group-sm mx-auto" style="width: 110px;">
                                                        <button class="btn btn-outline-light" type="submit" name="quantity" value="<?php echo $item['quantity'] - 1; ?>">-</button>
                                                        <input type="text" class="form-control text-center bg-black border-light text-white" value="<?php echo $item['quantity']; ?>" readonly>
                                                        <button class="btn btn-outline-light" type="submit" name="quantity" value="<?php echo $item['quantity'] + 1; ?>">+</button>
                                                    </div>
                                                </form>
                                            </td>
                                            
                                            <!-- Total Item Price -->
                                            <td class="text-end" style="background: transparent;">
                                                LKR <?php echo number_format($item['total'], 2); ?>
                                            </td>
                                            
                                            <!-- Remove Action -->
                                            <td class="text-center" style="background: transparent;">
                                                <form action="cart.php" method="POST" class="m-0">
                                                    <input type="hidden" name="action" value="remove">
                                                    <input type="hidden" name="product_id" value="<?php echo $item['id']; ?>">
                                                    <button type="submit" class="text-danger border-0 bg-transparent p-0 hover-gold" style="font-size: 1rem; transition: all 0.2s ease-in-out;" title="Remove masterpiece from bag"><i class="fa-solid fa-trash-can"></i></button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Bag Summary (Right) -->
                <div class="col-lg-4">
                    <div class="card bg-black border-secondary text-white p-4 rounded-4" style="border-color: rgba(255,255,255,0.08) !important;">
                        <h4 class="fw-bold mb-4" style="font-family: var(--font-heading);">Atelier Summary</h4>
                        
                        <div class="d-flex justify-content-between mb-3 small">
                            <span class="text-muted">Subtotal</span>
                            <span>LKR <?php echo number_format($subtotal, 2); ?></span>
                        </div>
                        
                        <div class="d-flex justify-content-between mb-3 small">
                            <span class="text-muted">White-Glove Shipping</span>
                            <span>
                                <?php if ($shipping == 0): ?>
                                    <span class="text-warning">Complimentary</span>
                                <?php else: ?>
                                    LKR <?php echo number_format($shipping, 2); ?>
                                <?php endif; ?>
                            </span>
                        </div>
                        
                        <?php if ($shipping > 0): ?>
                            <div class="alert alert-dark text-muted small p-2 mb-4 border-secondary rounded" style="font-size: 0.75rem;">
                                <i class="fa-solid fa-circle-info text-warning me-1"></i> Add LKR <?php echo number_format(20000 - $subtotal, 2); ?> more to unlock free white-glove shipping!
                            </div>
                        <?php else: ?>
                            <div class="alert alert-dark text-warning small p-2 mb-4 border-warning rounded" style="font-size: 0.75rem; background-color: rgba(220,199,163,0.05);">
                                <i class="fa-solid fa-truck-fast me-1"></i> Excellent! Free delivery has been unlocked.
                            </div>
                        <?php endif; ?>
                        
                        <hr class="border-secondary opacity-25 mb-4">
                        
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <span class="fw-bold">Grand Total</span>
                            <span class="text-warning fw-bold fs-5">LKR <?php echo number_format($grand_total, 2); ?></span>
                        </div>
                        
                        <!-- Actions -->
                        <div class="d-flex flex-column gap-3">
                            <a href="checkout.php" class="btn btn-warning py-3 text-black rounded-pill fw-bold text-uppercase fs-7 shadow-lg" style="letter-spacing: 1px;">
                                Proceed to Checkout <i class="fa-solid fa-circle-arrow-right ms-2"></i>
                            </a>
                            <a href="shop.php" class="btn btn-outline-light py-3 rounded-pill fw-bold text-uppercase fs-7" style="letter-spacing: 1px;">
                                Continue Browsing
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
    </div>
</section>

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