<?php
session_start();
require 'config/db.php';
require_once 'includes/functions.php';
include 'includes/header.php';

// 1. LOAD CART & VALIDATE ITEMS (Self-Cleaning Logic)
$cart_items = $_SESSION['cart'] ?? [];
$cart_details = [];
$subtotal = 0;
$valid_ids = []; // To store only existing products

if (!empty($cart_items)) {
    foreach ($cart_items as $variant_id => $qty) {
        // Fetch product details
        $stmt = $pdo->prepare("
            SELECT v.id as vid, v.name as v_name, v.price, p.name as p_name, p.thumbnail_url 
            FROM product_variants v 
            JOIN products p ON v.product_id = p.id 
            WHERE v.id = ?
        ");
        $stmt->execute([$variant_id]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($item) {
            // Valid Item Found
            $item['qty'] = $qty;
            $item['line_total'] = $item['price'] * $qty;
            $subtotal += $item['line_total'];
            $cart_details[] = $item;
            $valid_ids[$variant_id] = $qty; // Keep this ID
        }
    }
}

// 2. UPDATE SESSION (Remove Ghost Items)
// If the DB had fewer items than the session, update the session to match reality
if (count($valid_ids) !== count($cart_items)) {
    $_SESSION['cart'] = $valid_ids;
    // Optional: Refresh to update the header badge immediately
    // header("Location: cart.php"); 
}

// 3. COUPON LOGIC
$discount = 0;
if (isset($_SESSION['coupon'])) {
    if ($_SESSION['coupon']['type'] == 'fixed') {
        $discount = $_SESSION['coupon']['value'];
    } else {
        $discount = ($subtotal * $_SESSION['coupon']['value']) / 100;
    }
}

// 4. FINAL TOTAL
$final_total = max(0, $subtotal - $discount);

?>

<div class="container" style="min-height: 60vh; padding-top: 40px;">
    
    <?php if (empty($cart_details)): ?>
        
        <div style="text-align: center; padding: 60px 20px;">
            <i class="fas fa-shopping-cart" style="font-size: 60px; color: #eee; margin-bottom: 20px;"></i>
            <h2 style="color: #555;">Your Cart is Empty</h2>
            <p style="color: #888;">Looks like you haven't added any tools yet.</p>
            <a href="index.php" class="btn btn-primary" style="display: inline-block; margin-top: 20px; padding: 10px 30px;">Browse Shop</a>
        </div>

    <?php else: ?>
        
        <h1 style="margin-bottom: 30px;">Your Shopping Cart</h1>
        
        <form action="/cart_action.php" method="POST">
            <div style="overflow-x: auto;">
                <table style="width: 100%; border-collapse: collapse; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
                    <thead style="background: #f9f9f9; border-bottom: 2px solid #eee;">
                        <tr>
                            <th style="padding: 15px; text-align: left;">Product</th>
                            <th style="padding: 15px;">Price</th>
                            <th style="padding: 15px;">Quantity</th>
                            <th style="padding: 15px;">Total</th>
                            <th style="padding: 15px;"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($cart_details as $item): ?>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 15px; display: flex; align-items: center; gap: 15px;">
                                <img src="<?php echo !empty($item['thumbnail_url']) ? $item['thumbnail_url'] : 'assets/images/no-image.png'; ?>" 
                                     style="width: 50px; height: 50px; object-fit: cover; border-radius: 5px;">
                                <div>
                                    <strong style="display: block; color: #2c3e50;"><?php echo htmlspecialchars($item['p_name']); ?></strong>
                                    <small style="color: #888;"><?php echo htmlspecialchars($item['v_name']); ?></small>
                                </div>
                            </td>
                            <td style="padding: 15px;"><?php echo convertPrice($item['price']); ?></td>
                            <td style="padding: 15px;">
                                <input type="number" name="qty[<?php echo $item['vid']; ?>]" value="<?php echo $item['qty']; ?>" min="1" 
                                       style="width: 60px; padding: 5px; text-align: center; border: 1px solid #ddd; border-radius: 4px;">
                            </td>
                            <td style="padding: 15px; font-weight: bold; color: #2c3e50;"><?php echo convertPrice($item['line_total']); ?></td>
                            <td style="padding: 15px; text-align: center;">
                                <a href="/cart_action.php?remove=<?php echo $item['vid']; ?>" style="color: #e74c3c;">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div style="display: flex; flex-wrap: wrap; gap: 30px; margin-top: 30px;">
                
                <div style="flex: 1; min-width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
                    <h4 style="margin-top: 0;">Have a Coupon?</h4>
                    
                    <?php if(isset($_GET['msg']) && $_GET['msg']=='coupon_applied'): ?>
                        <p style="color: green; font-size: 14px;">Coupon Applied Successfully!</p>
                    <?php endif; ?>
                    
                    <div style="display: flex; gap: 10px;">
                        <input type="text" form="coupon-form" name="code" placeholder="Enter Code" style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <button type="submit" form="coupon-form" name="apply_coupon" class="btn btn-secondary">Apply</button>
                    </div>
                </div>

                <div style="flex: 1; min-width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); text-align: right;">
                    <p style="margin: 5px 0;">Subtotal: <strong><?php echo convertPrice($subtotal); ?></strong></p>
                    
                    <?php if($discount > 0): ?>
                        <p style="margin: 5px 0; color: green;">Discount: <strong>- <?php echo convertPrice($discount); ?></strong> 
                        <a href="/cart_action.php?remove_coupon=1" style="color: red; font-size: 12px;">[Remove]</a></p>
                    <?php endif; ?>
                    
                    <h2 style="margin: 15px 0; color: #2c3e50;"><?php echo convertPrice($final_total); ?></h2>
                    
                    <div style="display: flex; gap: 10px; justify-content: flex-end;">
                        <button type="submit" name="update_qty" class="btn btn-secondary">Update Qty</button>
                        <a href="/checkout.php" class="btn btn-buy">Checkout <i class="fas fa-arrow-right"></i></a>
                    </div>
                </div>
            </div>
        </form>
        
        <form action="/cart_action.php" method="POST" id="coupon-form"></form>

    <?php endif; ?>

</div>

<?php include 'includes/footer.php'; ?>