<?php
session_start();
$is_guest = !isset($_SESSION['user_id']);
$user_name = $is_guest ? 'Guest User' : htmlspecialchars($_SESSION['user_name']);
$page_title = 'Shopping Cart';
include 'header-section.html';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script></style>
    <style>
        /* ========== RESET & BASE STYLES ========== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
        }

        body {
            padding: 0;
        }

        /* ========== CONTAINER & LAYOUT ========== */
        .cart-wrapper {
            margin-top: 300px;
            padding: 1rem;
        }

        .cart-container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 1rem;
        }

        /* ========== HEADER SECTION ========== */
        .cart-header {
            background: linear-gradient(135deg, #333 0%, #555 100%);
            color: white;
            padding: 2rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .cart-header h1 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .cart-header p {
            font-size: 1rem;
            opacity: 0.9;
            margin: 0;
        }

        /* ========== MAIN CONTENT LAYOUT ========== */
        .cart-layout {
            display: grid;
            grid-template-columns: 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }

        @media (min-width: 768px) {
            .cart-layout {
                grid-template-columns: 1fr 350px;
            }
        }

        /* ========== CART ITEMS SECTION ========== */
        .cart-items-section {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            order: 1;
        }

        @media (min-width: 768px) {
            .cart-items-section {
                order: 0;
            }
        }

        .items-header {
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #e0e0e0;
        }

        .items-header strong {
            font-size: 1.1rem;
            color: #333;
        }

        /* ========== CART ITEM ========== */
        .cart-item {
            display: grid;
            grid-template-columns: 80px 1fr auto;
            gap: 1rem;
            align-items: start;
            padding: 1rem 0;
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.3s ease;
        }

        .cart-item:hover {
            background-color: #f8f9fa;
            border-radius: 6px;
            padding: 1rem;
            margin: 0 -1rem;
            padding-left: 1rem;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        @media (max-width: 480px) {
            .cart-item {
                grid-template-columns: 60px 1fr;
                gap: 0.75rem;
            }

            .item-actions {
                grid-column: 1 / -1;
                margin-top: 0.5rem;
                text-align: left;
            }
        }

        .item-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 6px;
            background: #f5f5f5;
        }

        @media (min-width: 576px) {
            .cart-item {
                grid-template-columns: 100px 1fr auto;
            }

            .item-image {
                width: 100px;
                height: 100px;
            }
        }

        @media (min-width: 768px) {
            .cart-item {
                grid-template-columns: 120px 1fr auto;
            }

            .item-image {
                width: 120px;
                height: 120px;
            }
        }

        .item-details {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .item-name {
            font-weight: 600;
            font-size: 1rem;
            color: #333;
            line-height: 1.4;
        }

        @media (max-width: 480px) {
            .item-name {
                font-size: 0.9rem;
            }
        }

        .item-id {
            font-size: 0.85rem;
            color: #999;
        }

        .item-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            font-size: 0.9rem;
            color: #666;
        }

        @media (max-width: 480px) {
            .item-meta {
                flex-direction: column;
                gap: 0.25rem;
            }
        }

        .item-actions {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            text-align: right;
        }

        @media (max-width: 480px) {
            .item-actions {
                text-align: left;
                flex-direction: row;
            }
        }

        .item-price {
            font-size: 1.2rem;
            color: #d4a574;
            font-weight: 700;
        }

        @media (max-width: 480px) {
            .item-price {
                font-size: 1rem;
            }
        }

        .item-qty {
            font-size: 0.9rem;
            color: #666;
        }

        .btn-remove {
            background: #dc3545;
            color: white;
            border: none;
            padding: 0.5rem 0.75rem;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.85rem;
            font-weight: 600;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        @media (max-width: 480px) {
            .btn-remove {
                padding: 0.5rem 0.6rem;
                font-size: 0.8rem;
            }
        }

        .btn-remove:hover:not(:disabled) {
            background: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 2px 6px rgba(220, 53, 69, 0.3);
        }

        .btn-remove:active:not(:disabled) {
            transform: translateY(0);
        }

        .btn-remove:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        /* ========== EMPTY CART ========== */
        /* ========== EMPTY CART ========== */
        .empty-cart {
            background: white;
            border-radius: 8px;
            padding: 3rem 1.5rem;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        @media (max-width: 480px) {
            .empty-cart {
                padding: 2rem 1rem;
            }
        }

        .empty-cart h2 {
            font-size: 1.5rem;
            color: #666;
            margin-bottom: 1rem;
        }

        @media (max-width: 480px) {
            .empty-cart h2 {
                font-size: 1.25rem;
            }
        }

        .empty-cart p {
            color: #999;
            margin-bottom: 1.5rem;
            font-size: 1rem;
        }

        @media (max-width: 480px) {
            .empty-cart p {
                font-size: 0.9rem;
            }
        }

        /* ========== CART SUMMARY/SIDEBAR ========== */
        .cart-summary {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            height: fit-content;
            position: static;
            top: 120px;
        }

        @media (max-width: 767px) {
            .cart-summary {
                position: static;
                top: auto;
                padding: 1.25rem;
            }
        }

        @media (max-width: 480px) {
            .cart-summary {
                padding: 1rem;
            }
        }

        .summary-header {
            font-size: 1.1rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #e0e0e0;
        }

        @media (max-width: 480px) {
            .summary-header {
                font-size: 1rem;
                margin-bottom: 0.75rem;
                padding-bottom: 0.75rem;
            }
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            font-size: 0.95rem;
            color: #666;
        }

        @media (max-width: 480px) {
            .summary-row {
                font-size: 0.85rem;
                padding: 0.5rem 0;
            }
        }

        .summary-row span:first-child {
            flex: 1;
        }

        .summary-row span:last-child {
            text-align: right;
            font-weight: 600;
            color: #333;
        }

        .summary-divider {
            border-top: 1px solid #e0e0e0;
            margin: 0.75rem 0;
        }

        @media (max-width: 480px) {
            .summary-total {
                font-size: 1rem;
                padding: 0.75rem 0;
                margin-top: 0.5rem;
            }
        }

        /* ========== ACTION BUTTONS ========== */
        .action-bar {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            margin-top: 1.5rem;
        }

        @media (max-width: 480px) {
            .action-bar {
                gap: 0.5rem;
                margin-top: 1rem;
            }
        }

        .btn-action {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            transition: all 0.3s ease;
            min-height: 44px;
        }

        @media (max-width: 480px) {
            .btn-action {
                padding: 0.65rem 1rem;
                font-size: 0.95rem;
            }
        }

        .btn-checkout {
            background: #d4a574;
            color: white;
        }

        .btn-checkout:hover {
            background: #b8905a;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(212, 165, 116, 0.3);
        }

        .btn-checkout:active {
            transform: translateY(0);
        }

        .btn-shop {
            background: #333;
            color: white;
        }

        .btn-shop:hover {
            background: #555;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .btn-shop:active {
            transform: translateY(0);
        }

        .btn-logout {
            background: #dc3545;
            color: white;
        }

        .btn-logout {
            background: #dc3545;
            color: white;
        }

        .btn-logout:hover {
            background: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(220, 53, 69, 0.3);
        }

        .btn-logout:active {
            transform: translateY(0);
        }

        .action-bar-bottom {
            display: flex;
            flex-wrap: wrap;
            gap: 0.75rem;
            justify-content: center;
            margin-top: 2rem;
        }

        @media (max-width: 480px) {
            .action-bar-bottom {
                flex-direction: column;
                gap: 0.5rem;
                margin-top: 1.5rem;
            }
        }

        .btn-secondary {
            padding: 0.75rem 1.5rem;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 600;
            display: inline-block;
            transition: all 0.3s ease;
            min-height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        @media (max-width: 480px) {
            .btn-secondary {
                padding: 0.65rem 1rem;
                font-size: 0.95rem;
                width: 100%;
            }
        }

        /* ========== TOAST NOTIFICATIONS ========== */
        .toast {
            position: fixed;
            top: 1rem;
            right: 1rem;
            padding: 1rem 1.5rem;
            color: white;
            border-radius: 6px;
            z-index: 9999;
            display: none;
            font-weight: 600;
            animation: slideIn 0.3s ease-out;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            max-width: 90%;
        }

        @media (max-width: 480px) {
            .toast {
                top: auto;
                bottom: 1rem;
                right: 0.75rem;
                left: 0.75rem;
                max-width: none;
                padding: 0.75rem 1rem;
                font-size: 0.9rem;
            }
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        @keyframes slideIn {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* ========== RESPONSIVE ADJUSTMENTS ========== */
        @media (max-width: 1024px) {
            .cart-container {
                max-width: 100%;
            }

            .cart-layout {
                gap: 1.5rem;
            }
        }

        @media (max-width: 767px) {
            .cart-wrapper {
                padding: 0.75rem;
                margin-top: 80px;
            }

            .cart-container {
                padding: 0.5rem;
            }

            .cart-header {
                padding: 1.5rem 1rem;
                margin-bottom: 1.5rem;
            }

            .cart-header h1 {
                font-size: 1.5rem;
            }

            .cart-header p {
                font-size: 0.95rem;
            }

            .cart-items-section,
            .cart-summary {
                padding: 1rem;
            }

            .items-header {
                margin-bottom: 1rem;
                padding-bottom: 0.75rem;
            }

            .items-header strong {
                font-size: 1rem;
            }

            .cart-item {
                padding: 0.75rem 0;
                gap: 0.75rem;
            }

            .item-image {
                width: 70px;
                height: 70px;
            }

            .item-name {
                font-size: 0.95rem;
            }

            .btn-action {
                padding: 0.65rem 1rem;
                font-size: 0.95rem;
            }

            .action-bar-bottom {
                flex-direction: column;
            }

            .btn-secondary {
                width: 100%;
                text-align: center;
            }

            .cart-summary {
                position: static;
                top: auto;
            }
        }

        @media (max-width: 576px) {
            .cart-wrapper {
                margin-top: 0;
                padding: 0.5rem;
            }

            .cart-container {
                padding: 0.25rem;
            }

            .cart-header {
                padding: 1.25rem 0.75rem;
                margin-bottom: 1rem;
                border-radius: 6px;
            }

            .cart-header h1 {
                font-size: 1.25rem;
                margin-bottom: 0.25rem;
            }

            .cart-header p {
                font-size: 0.85rem;
            }

            .cart-layout {
                gap: 1rem;
            }

            .cart-items-section,
            .cart-summary {
                padding: 0.75rem;
                border-radius: 6px;
            }

            .items-header {
                margin-bottom: 0.75rem;
                padding-bottom: 0.5rem;
            }

            .items-header strong {
                font-size: 0.95rem;
            }

            .cart-item {
                padding: 0.5rem 0;
                gap: 0.5rem;
                grid-template-columns: 60px 1fr;
            }

            .item-details {
                gap: 0.25rem;
            }

            .item-name {
                font-size: 0.85rem;
                line-height: 1.3;
            }

            .item-id {
                font-size: 0.75rem;
            }

            .item-meta {
                flex-direction: column;
                gap: 0.15rem;
                font-size: 0.8rem;
            }

            .item-price {
                font-size: 0.95rem;
            }

            .item-qty {
                font-size: 0.8rem;
            }

            .item-actions {
                grid-column: 1 / -1;
                flex-direction: row;
                margin-top: 0.5rem;
                text-align: left;
                gap: 0.25rem;
            }

            .btn-remove {
                padding: 0.4rem 0.5rem;
                font-size: 0.75rem;
            }

            .empty-cart {
                padding: 1.5rem 0.75rem;
            }

            .empty-cart h2 {
                font-size: 1.1rem;
            }

            .empty-cart p {
                font-size: 0.85rem;
            }

            .summary-header {
                font-size: 0.95rem;
                margin-bottom: 0.5rem;
                padding-bottom: 0.5rem;
            }

            .summary-row {
                font-size: 0.8rem;
                padding: 0.4rem 0;
            }

            .summary-divider {
                margin: 0.5rem 0;
            }

            .summary-total {
                font-size: 0.95rem;
                padding: 0.5rem 0;
                margin-top: 0.25rem;
            }

            .action-bar-bottom {
                margin-top: 1rem;
                gap: 0.5rem;
            }

            .btn-secondary {
                padding: 0.6rem 0.8rem;
                font-size: 0.9rem;
            }
        }

        @media (max-width: 360px) {
            .cart-header {
                padding: 1rem 0.6rem;
            }

            .cart-header h1 {
                font-size: 1.1rem;
            }

            .cart-items-section,
            .cart-summary {
                padding: 0.6rem;
            }

            .item-image {
                width: 50px;
                height: 50px;
            }

            .item-name {
                font-size: 0.8rem;
            }

            .item-price {
                font-size: 0.85rem;
            }

            .btn-remove {
                padding: 0.35rem 0.4rem;
                font-size: 0.7rem;
            }

            .summary-row {
                font-size: 0.75rem;
            }

            .summary-total {
                font-size: 0.9rem;
            }

            .btn-secondary {
                padding: 0.5rem 0.6rem;
                font-size: 0.85rem;
            }
        }

        /* ========== PRINT STYLES ========== */
        @media print {
            .action-bar, .toast, .btn-remove {
                display: none;
            }

            .cart-item {
                page-break-inside: avoid;
            }
        }
    </style>
</head>
<body>
    <!-- Toast Notification -->
    <div class="toast" id="toast"></div>

    <!-- Cart Wrapper -->
    <div class="cart-wrapper">
        <div class="cart-container">
            <!-- Header -->
            <div class="cart-header">
                <h1>🛒 Shopping Cart</h1>
                <p>User: <?php echo $user_name; ?></p>
            </div>

            <!-- Main Content -->
            <div class="cart-layout">
                <!-- Cart Items -->
                <div id="cart-content"></div>

                <!-- Cart Summary Sidebar -->
                <div id="summary-content"></div>
            </div>

            <!-- Action Bar -->
            <div class="action-bar-bottom" id="action-buttons">
                <a href="shop.php" class="btn-secondary btn-shop">← Continue Shopping</a>
            </div>
        </div>
    </div>

    <script>
        /**
         * Load cart items and summary
         */
        function loadCart() {
            const container = document.getElementById('cart-content');
            const summaryContainer = document.getElementById('summary-content');
            const isLoggedIn = localStorage.getItem('userLoggedIn');
            
            console.log('Loading cart... isLoggedIn:', isLoggedIn);
            
            if (isLoggedIn) {
                // Fetch cart from database for authenticated users
                console.log('Fetching cart from database...');
                fetch('auth-system/cart-api.php?action=get')
                    .then(response => {
                        console.log('Response status:', response.status);
                        return response.json();
                    })
                    .then(data => {
                        console.log('API Response:', data);
                        if (data.success && data.items && data.items.length > 0) {
                            console.log('Rendering cart with', data.items.length, 'items');
                            renderCart(data.items, container, summaryContainer, true);
                        } else {
                            console.log('No items found, showing empty cart');
                            showEmptyCart(container, summaryContainer);
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching cart:', error);
                        showEmptyCart(container, summaryContainer);
                    });
            } else {
                // Load from localStorage for guest users
                const cartData = localStorage.getItem('guestCart');
                const items = cartData ? JSON.parse(cartData) : [];
                
                console.log('Guest cart items:', items);
                
                if (items && items.length > 0) {
                    console.log('Rendering guest cart with', items.length, 'items');
                    renderCart(items, container, summaryContainer, false);
                } else {
                    console.log('Guest cart is empty');
                    showEmptyCart(container, summaryContainer);
                }
            }
        }
        
        /**
         * Render cart items on page
         */
        function renderCart(items, container, summaryContainer, isLoggedIn) {
            console.log('renderCart called with items:', items);
            console.log('First item structure:', items[0]);
            
            // Render cart items
            let itemsHtml = `
                <div class="cart-items-section">
                    <div class="items-header">
                        <strong>📦 Items in Cart (${items.length})</strong>
                    </div>
            `;
            
            let subtotal = 0;
            items.forEach((item, index) => {
                const itemTotal = parseInt(item.price) * item.quantity;
                subtotal += itemTotal;
                const cartItemId = item.id; // Use id directly - MUST exist from DB
                console.log('Rendering item:', index, 'id:', cartItemId, 'name:', item.product_name);
                
                itemsHtml += `
                    <div class="cart-item" data-cart-id="${cartItemId}">
                        <img src="${item.image}" alt="${item.product_name}" class="item-image">
                        <div class="item-details">
                            <div class="item-name">${item.product_name}</div>
                            <div class="item-id">ID: ${item.product_id}</div>
                            <div class="item-meta">
                                <span class="item-price">Rs. ${parseInt(item.price).toLocaleString()}</span>
                                <span class="item-qty">× ${item.quantity} = Rs. ${itemTotal.toLocaleString()}</span>
                            </div>
                        </div>
                        <div class="item-actions">
                            <button class="btn-remove" data-product-name="${item.product_name}" data-is-logged-in="${isLoggedIn}">🗑️ Remove</button>
                        </div>
                    </div>
                `;
            });
            
            itemsHtml += '</div>';
            container.innerHTML = itemsHtml;
            
            // Render summary
            const shipping = 500;
            const tax = Math.round(subtotal * 0.05);
            const total = subtotal + shipping + tax;
            
            const summaryHtml = `
                <div class="cart-summary">
                    <div class="summary-header">💰 Order Summary</div>
                    <div class="summary-row">
                        <span>Subtotal:</span>
                        <span>Rs. ${subtotal.toLocaleString()}</span>
                    </div>
                    <div class="summary-row">
                        <span>Shipping:</span>
                        <span>Rs. ${shipping.toLocaleString()}</span>
                    </div>
                    <div class="summary-row">
                        <span>Tax (5%):</span>
                        <span>Rs. ${tax.toLocaleString()}</span>
                    </div>
                    <div class="summary-divider"></div>
                    <div class="summary-total">
                        <span>TOTAL:</span>
                        <span>Rs. ${total.toLocaleString()}</span>
                    </div>
                    <div class="action-bar">
                        <button onclick="proceedToCheckout()" class="btn-action btn-checkout">💳 Proceed to Checkout</button>
                    </div>
                </div>
            `;
            
            summaryContainer.innerHTML = summaryHtml;
            
            // Attach event listeners to remove buttons
            document.querySelectorAll('.btn-remove').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const cartItem = this.closest('.cart-item');
                    const itemId = cartItem.getAttribute('data-cart-id');
                    const productName = this.getAttribute('data-product-name');
                    const isLoggedIn = this.getAttribute('data-is-logged-in');
                    
                    removeItem(itemId, productName, isLoggedIn);
                });
            });
        }
        
        /**
         * Show empty cart message
         */
        function showEmptyCart(container, summaryContainer) {
            container.innerHTML = `
                <div class="empty-cart">
                    <h2>🛒 Your Cart is Empty</h2>
                    <p>Start shopping to add items!</p>
                    <a href="shop.php" class="btn-secondary btn-shop">← Go to Shop</a>
                </div>
            `;
            summaryContainer.innerHTML = '';
        }

        /**
         * Remove item from cart
         */
        function removeItem(itemId, productName, isLoggedIn) {
            console.log('===== REMOVE ITEM CALLED =====');
            console.log('itemId:', itemId, 'Product:', productName);
            
            if (!confirm('Remove ' + productName + ' from cart?')) {
                console.log('User cancelled removal');
                return;
            }
            
            // PAUSE auto-refresh while removing
            autoRefreshEnabled = false;
            console.log('Auto-refresh disabled');
            
            // IMMEDIATELY remove from DOM (real-time)
            const itemElement = document.querySelector(`[data-cart-id="${itemId}"]`);
            if (itemElement) {
                console.log('Removing element from DOM immediately');
                itemElement.style.opacity = '0';
                itemElement.style.transition = 'opacity 0.3s ease-out';
                setTimeout(() => {
                    itemElement.remove();
                    console.log('Item DOM element removed');
                }, 300);
            }
            
            // Show success message immediately
            showToast('✅ Item removed from cart', 'success');
            
            // Convert string "true" to boolean
            const loggedIn = isLoggedIn === true || isLoggedIn === 'true';
            
            if (loggedIn) {
                console.log('Syncing with database...');
                // Send delete to database in background
                fetch('auth-system/cart-api.php?action=remove', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        cart_id: parseInt(itemId)
                    })
                })
                .then(response => {
                    console.log('Delete response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Delete response:', data);
                    if (data.success) {
                        console.log('✅ Item successfully deleted from database');
                        // Re-enable auto-refresh after successful delete
                        setTimeout(() => {
                            autoRefreshEnabled = true;
                            console.log('Auto-refresh re-enabled');
                            loadCart();
                        }, 500);
                    } else {
                        console.error('❌ Delete failed:', data.message);
                        showToast('❌ Failed to delete: ' + data.message, 'error');
                        // Re-enable and reload on error
                        setTimeout(() => {
                            autoRefreshEnabled = true;
                            loadCart();
                        }, 1000);
                    }
                })
                .catch(error => {
                    console.error('❌ Delete request error:', error);
                    showToast('❌ Error: ' + error.message, 'error');
                    // Re-enable and reload on error
                    setTimeout(() => {
                        autoRefreshEnabled = true;
                        loadCart();
                    }, 1000);
                });
            } else {
                console.log('Syncing guest cart with localStorage...');
                // Sync guest cart
                const cartData = localStorage.getItem('guestCart');
                let items = cartData ? JSON.parse(cartData) : [];
                const indexToRemove = parseInt(itemId);
                
                if (indexToRemove >= 0 && indexToRemove < items.length) {
                    items.splice(indexToRemove, 1);
                    localStorage.setItem('guestCart', JSON.stringify(items));
                    console.log('Guest cart synced, items remaining:', items.length);
                }
                
                // Re-enable auto-refresh for guests
                setTimeout(() => {
                    autoRefreshEnabled = true;
                    console.log('Auto-refresh re-enabled for guest');
                }, 500);
            }
            console.log('===== REMOVE ITEM END =====');
        }

        /**
         * Proceed to checkout
         */
        function proceedToCheckout() {
            const isLoggedIn = localStorage.getItem('userLoggedIn');
            
            if (!isLoggedIn) {
                Swal.fire({
                    title: '🔐 Login Required',
                    text: 'Please login to complete your purchase.',
                    icon: 'warning',
                    confirmButtonText: 'Go to Login',
                    confirmButtonColor: '#d4a574',
                    showCancelButton: true,
                    cancelButtonText: 'Continue Shopping'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'auth-system/login.php';
                    }
                });
            } else {
                window.location.href = 'checkout.php';
            }
        }

        /**
         * Display toast notification
         */
        function showToast(message, type) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast ' + type;
            toast.style.display = 'block';
            setTimeout(() => {
                toast.style.display = 'none';
            }, 3000);
        }

        // Load cart on page load
        document.addEventListener('DOMContentLoaded', loadCart);
        
        // Auto-refresh flag
        let autoRefreshEnabled = true;
        
        // Refresh cart every 3 seconds (only if not removing items)
        setInterval(() => {
            if (autoRefreshEnabled) {
                loadCart();
            }
        }, 3000);
    </script>

    <?php include 'footer-section.html'; ?>
</body>
</html>
