<?php
// Use require_once with __DIR__ to prevent path issues
require_once __DIR__ . '/includes/header.php';

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'];
    $pid = $_POST['product_id'];

    if ($action == 'add') {
        $qty = $_POST['qty'] ?? 1;
        if (isset($_SESSION['cart'][$pid])) {
            $_SESSION['cart'][$pid] += $qty;
        } else {
            $_SESSION['cart'][$pid] = $qty;
        }
    } elseif ($action == 'remove') {
        unset($_SESSION['cart'][$pid]);
    } elseif ($action == 'update') {
        $qty = $_POST['qty'];
        if ($qty > 0) {
            $_SESSION['cart'][$pid] = $qty;
        } else {
            unset($_SESSION['cart'][$pid]);
        }
    }
    
    // Redirect to avoid resubmission
    header("Location: cart.php");
    exit;
}

// Fetch Cart Details
$cartItems = [];
$total = 0;
if (!empty($_SESSION['cart'])) {
    $ids = implode(',', array_keys($_SESSION['cart']));
    // Safe because keys come from session
    if ($ids) {
        $in  = str_repeat('?,', count($_SESSION['cart']) - 1) . '?';
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($in)");
        $stmt->execute(array_keys($_SESSION['cart']));
        $products = $stmt->fetchAll();

        foreach ($products as $p) {
            $p['qty'] = $_SESSION['cart'][$p['id']];
            $p['subtotal'] = $p['price'] * $p['qty'];
            $total += $p['subtotal'];
            $cartItems[] = $p;
        }
    }
}
?>

<style>
    /* --- Cart Custom Design --- */
    .cart-container {
        min-height: 60vh;
    }
    .cart-item-card {
        border: none;
        border-radius: 16px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.03);
        background: #fff;
        margin-bottom: 20px;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
        padding: 20px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
    }
    .cart-item-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.06);
    }
    
    .cart-img-wrapper {
        width: 100px;
        height: 100px;
        background-color: #f9f9f9;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        padding: 10px;
    }
    .cart-img-wrapper img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
        filter: drop-shadow(0 4px 6px rgba(0,0,0,0.05));
    }
    
    .item-details {
        flex: 1;
        min-width: 200px;
    }
    .item-title {
        font-weight: 700;
        font-size: 1.1rem;
        color: #2c3e50;
        margin-bottom: 5px;
    }
    .item-id {
        font-size: 0.85rem;
        color: #95a5a6;
    }
    
    .qty-control {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-top: 10px;
    }
    .qty-input {
        width: 60px;
        text-align: center;
        border: 1px solid #eee;
        border-radius: 8px;
        padding: 5px;
        font-weight: 600;
        color: #2c3e50;
    }
    .btn-update {
        font-size: 0.8rem;
        text-transform: uppercase;
        font-weight: 700;
        color: #3498db;
        background: none;
        border: none;
        padding: 0;
        cursor: pointer;
    }
    .btn-update:hover { text-decoration: underline; }
    
    .price-display {
        text-align: right;
        min-width: 100px;
    }
    .item-price {
        font-size: 1.2rem;
        font-weight: 800;
        color: #2c3e50;
    }
    .btn-remove {
        color: #e74c3c;
        background: rgba(231, 76, 60, 0.1);
        border: none;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        margin-left: auto; /* Push to right on mobile if wrapped */
    }
    .btn-remove:hover {
        background: #e74c3c;
        color: white;
    }

    /* Summary Card */
    .summary-card {
        border: none;
        border-radius: 20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.05);
        background: #fff;
        padding: 30px;
        position: sticky;
        top: 20px;
    }
    .summary-title {
        font-weight: 800;
        letter-spacing: 1px;
        color: #2c3e50;
        margin-bottom: 25px;
        text-transform: uppercase;
        font-size: 1.1rem;
    }
    .summary-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
        color: #555;
    }
    .summary-total {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 2px solid #f5f5f5;
        font-size: 1.4rem;
        font-weight: 800;
        color: #2c3e50;
    }
    .btn-checkout-custom {
        display: block;
        width: 100%;
        background-color: #2c3e50;
        color: white;
        text-align: center;
        padding: 15px;
        border-radius: 12px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-top: 25px;
        text-decoration: none;
        transition: background 0.3s;
    }
    .btn-checkout-custom:hover {
        background-color: #1a252f;
        color: #fff;
    }
</style>

<div class="container my-5 cart-container">
    <h2 class="mb-5 text-center fw-bold" style="letter-spacing: 2px;">SHOPPING BAG</h2>

    <?php if (empty($cartItems)): ?>
        <div class="text-center py-5">
            <div class="mb-4 text-muted" style="font-size: 3rem;"><i class="fas fa-shopping-basket"></i></div>
            <p class="lead mb-4">Your bag is currently empty.</p>
            <a href="index.php" class="btn btn-dark btn-lg px-5" style="border-radius: 50px;">Start Shopping</a>
        </div>
    <?php else: ?>
        <div class="row">
            <!-- Cart Items Column -->
            <div class="col-lg-8">
                <?php foreach ($cartItems as $item): ?>
                <div class="cart-item-card">
                    <!-- Image -->
                    <div class="cart-img-wrapper">
                        <img src="../../<?= $item['image'] ?>" alt="<?= htmlspecialchars($item['name']) ?>">
                    </div>
                    
                    <!-- Details -->
                    <div class="item-details">
                        <div class="item-title"><?= htmlspecialchars($item['name']) ?></div>
                        <div class="item-id">Item <?= $item['id'] ?></div>
                        
                        <!-- Qty Form -->
                        <form action="cart.php" method="POST" class="qty-control">
                            <input type="hidden" name="action" value="update">
                            <input type="hidden" name="product_id" value="<?= $item['id'] ?>">
                            <label class="small text-muted mb-0">Qty:</label>
                            <input type="number" name="qty" value="<?= $item['qty'] ?>" min="1" class="qty-input">
                            <button type="submit" class="btn-update">Update</button>
                        </form>
                    </div>

                    <!-- Price & Actions -->
                    <div class="price-display d-flex flex-column align-items-end justify-content-between h-100">
                        <div class="item-price">$<?= number_format($item['subtotal'], 2) ?></div>
                        
                        <form action="cart.php" method="POST" class="mt-3">
                            <input type="hidden" name="action" value="remove">
                            <input type="hidden" name="product_id" value="<?= $item['id'] ?>">
                            <button type="submit" class="btn-remove" title="Remove Item">
                                <i class="fas fa-times"></i>
                            </button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Summary Column -->
            <div class="col-lg-4">
                <div class="summary-card">
                    <div class="summary-title">Order Summary</div>
                    
                    <div class="summary-row">
                        <span>Subtotal</span>
                        <span>$<?= number_format($total, 2) ?></span>
                    </div>

                    
                    <div class="summary-total">
                        <span>Total</span>
                        <span>$<?= number_format($total, 2) ?></span>
                    </div>
                    
                    <a href="checkout.php" class="btn-checkout-custom">
                        Checkout Now
                    </a>
                    
                    <div class="text-center mt-3 text-muted small">
                        <i class="fas fa-lock me-1"></i> Secure Checkout
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php 
// Safely include footer at the end
require_once __DIR__ . '/includes/footer.php'; 
?>