<!-- Breadcrumb Section -->
<section class="z-index-2 position-relative pb-2 mb-12">
    <div class="bg-body-secondary mb-3">
        <div class="container">
            <nav class="py-4 lh-30px" aria-label="breadcrumb">
                <ol class="breadcrumb justify-content-center py-1 mb-0">
                    <li class="breadcrumb-item"><a title="Home" href="<?=base_url()?>">Home</a></li>
                    <li class="breadcrumb-item"><a title="Shop" href="<?=base_url('products')?>">Shop</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Your Pre-Orders</li>
                </ol>
            </nav>
        </div>
    </div>
</section>

<!-- Shopping Cart Section -->
<section class="container">
    <div class="shopping-cart">
        <h2 class="text-center fs-2 mt-12 mb-13">Your Pre-Orders</h2>
        
        <?php if($cart_items && count($cart_items) > 0): ?>
            <?php 
                $subtotal = 0;
                foreach($cart_items as $item) {
                    $item_price = $item->amount;
                    if($item->discount_percentage) {
                        $item_price = $item->amount - ($item->amount * ($item->discount_percentage / 100));
                    }
                    $subtotal += $item_price * $item->quantity;
                }
            ?>
            
            <!-- Cart Table -->
            <div class="table-responsive-md pb-8 pb-lg-10">
                <table class="table border" id="cartTable">
                    <thead class="bg-body-secondary">
                        <tr class="fs-15px letter-spacing-01 fw-semibold text-uppercase text-body-emphasis">
                            <th scope="col" class="fw-semibold border-1 ps-8">Product</th>
                            <th scope="col" class="fw-semibold border-1 text-center">Quantity</th>
                            <th scope="col" class="fw-semibold border-1">Price</th>
                            <th scope="col" class="fw-semibold border-1 text-center">Total</th>
                            <th scope="col" class="fw-semibold border-1 text-center" style="width: 60px;"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($cart_items as $item): ?>
                            <?php 
                                $item_price = $item->amount;
                                if($item->discount_percentage) {
                                    $item_price = $item->amount - ($item->amount * ($item->discount_percentage / 100));
                                }
                                $line_total = $item_price * $item->quantity;
                            ?>
                            <tr class="position-relative cart-row" data-cart-id="<?=$item->cartId?>">
                                <th scope="row" class="pe-5 ps-8 py-7 shop-product">
                                    <div class="d-flex align-items-center">
                                        <div class="me-6">
                                            <a href="<?=base_url('products/view/'.$item->slug.'/'.$item->productUnique)?>">
                                                <img src="<?=PRODUCT_ASSETS_URL.$item->image?>" width="75" height="100" alt="<?=$item->name?>" class="rounded">
                                            </a>
                                        </div>
                                        <div>
                                            <p class="fw-500 mb-1 text-body-emphasis">
                                                <a href="<?=base_url('products/view/'.$item->slug.'/'.$item->productUnique)?>" class="text-decoration-none text-reset">
                                                    <?=$item->name?>
                                                </a>
                                            </p>
                                            <?php if($item->colorName): ?>
                                                <p class="mb-1 fs-13px text-muted">Color: <?=$item->colorName?></p>
                                            <?php endif; ?>
                                            <?php if($item->size): ?>
                                                <p class="mb-0 fs-13px text-muted">Size: <?=$item->size?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </th>
                                <td class="align-middle">
                                    <div class="d-flex align-items-center justify-content-center">
                                        <div class="quantity-selector d-flex align-items-center border rounded">
                                            <button type="button" class="btn btn-sm px-3 py-2 border-0 qty-decrease" data-cart-id="<?=$item->cartId?>">
                                                <i class="fas fa-minus"></i>
                                            </button>
                                            <input type="number" min="1" class="form-control form-control-sm text-center border-0 cart-qty" 
                                                   id="qty_<?=$item->cartId?>" 
                                                   data-cart-id="<?=$item->cartId?>"
                                                   data-price="<?=$item_price?>"
                                                   value="<?=$item->quantity?>" 
                                                   style="width: 50px;" readonly>
                                            <button type="button" class="btn btn-sm px-3 py-2 border-0 qty-increase" data-cart-id="<?=$item->cartId?>">
                                                <i class="fas fa-plus"></i>
                                            </button>
                                        </div>
                                    </div>
                                </td>
                                <td class="align-middle">
                                    <?php if($item->discount_percentage): ?>
                                        <span class="fs-13px text-decoration-line-through text-muted d-block"><?=currency_main_symbol($item->amount, 1)?></span>
                                        <span class="text-body-emphasis fw-bold"><?=currency_main_symbol($item_price, 1)?></span>
                                    <?php else: ?>
                                        <span class="text-body-emphasis fw-bold"><?=currency_main_symbol($item->amount, 1)?></span>
                                    <?php endif; ?>
                                </td>
                                <td class="align-middle text-center">
                                    <p class="mb-0 text-body-emphasis fw-bold line-total" id="total_<?=$item->cartId?>">
                                        <?=currency_main_symbol($line_total, 1)?>
                                    </p>
                                </td>
                                <td class="align-middle text-center">
                                    <button type="button" class="btn btn-link text-danger p-0 remove-item" data-cart-id="<?=$item->cartId?>">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        
                        <!-- Action Row -->
                        <tr>
                            <td colspan="2" class="pt-5 pb-10 position-relative bg-body ps-0">
                                <a href="<?=base_url('products')?>" title="Continue Shopping" class="btn btn-outline-dark me-4 ms-6 text-nowrap my-2">
                                    <i class="fas fa-arrow-left me-2"></i> Continue Shopping
                                </a>
                                <button type="button" id="clearCart" class="btn btn-link p-0 border-0 text-decoration-none my-2 fw-semibold text-danger">
                                    <i class="fas fa-trash me-2"></i> Clear All
                                </button>
                            </td>
                            <td colspan="3" class="text-end pt-5 pb-10 position-relative bg-body pe-0">
                                <!-- Empty for now -->
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- Cart Summary Row -->
            <div class="row pt-8 pt-lg-11 pb-16 pb-lg-18">
                <!-- Coupon Code -->
                <div class="col-lg-4 pt-2">
                    <h4 class="fs-24 mb-6">Have a Coupon?</h4>
                    <p class="mb-7">Enter your coupon code if you have one.</p>
                    <form id="couponForm">
                        <input type="text" name="coupon_code" id="couponCode" class="form-control mb-7" placeholder="Enter coupon code here">
                        <button type="submit" class="btn btn-dark btn-hover-bg-primary btn-hover-border-primary">
                            Apply Coupon
                        </button>
                    </form>
                    <div id="couponMessage" class="mt-4"></div>
                </div>
                
                <!-- Shipping Info -->
                <div class="col-lg-4 pt-lg-2 pt-10">
                    <h4 class="fs-24 mb-6">Pre-Order Information</h4>
                    <div class="bg-body-secondary p-6 rounded">
                        <p class="mb-4"><i class="fas fa-info-circle me-2 text-primary"></i> <strong>Pre-Order Note:</strong></p>
                        <ul class="mb-0 ps-4">
                            <li class="mb-2">Products will be shipped once they become available</li>
                            <li class="mb-2">You will receive a shipping notification via email</li>
                            <li class="mb-2">Estimated delivery: 2-4 weeks after launch</li>
                        </ul>
                    </div>
                </div>
                
                <!-- Order Summary -->
                <div class="col-lg-4 pt-lg-0 pt-11">
                    <div class="card border-0" style="box-shadow: 0 0 10px 0 rgba(0,0,0,0.1)">
                        <div class="card-body px-9 pt-6">
                            <h4 class="fs-24 mb-6">Order Summary</h4>
                            <div class="d-flex align-items-center justify-content-between mb-5">
                                <span>Subtotal:</span>
                                <span class="d-block ml-auto text-body-emphasis fw-bold" id="cartSubtotal"><?=currency_main_symbol($subtotal, 1)?></span>
                            </div>
                            <div class="d-flex align-items-center justify-content-between mb-5" id="discountRow" style="display: none !important;">
                                <span>Discount:</span>
                                <span class="d-block ml-auto text-success fw-bold" id="cartDiscount">-$0.00</span>
                            </div>
                            <div class="d-flex align-items-center justify-content-between">
                                <span>Shipping:</span>
                                <span class="d-block ml-auto text-body-emphasis fw-bold">Calculated at checkout</span>
                            </div>
                        </div>
                        <div class="card-footer bg-transparent px-0 pt-5 pb-7 mx-9">
                            <div class="d-flex align-items-center justify-content-between fw-bold mb-7">
                                <span class="text-body-emphasis">Total:</span>
                                <span class="d-block ml-auto text-body-emphasis fs-4 fw-bold" id="cartTotal"><?=currency_main_symbol($subtotal, 1)?></span>
                            </div>
                            <a href="<?=base_url('checkout')?>" class="btn w-100 btn-dark btn-hover-bg-primary btn-hover-border-primary" title="Proceed to Checkout">
                                <i class="fas fa-lock me-2"></i> Proceed to Checkout
                            </a>
                            <p class="text-center text-muted fs-13px mt-4 mb-0">
                                <i class="fas fa-shield-alt me-1"></i> Secure Checkout
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            
        <?php else: ?>
            <!-- Empty Cart -->
            <div class="text-center py-20">
                <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" fill="currentColor" class="bi bi-cart-x text-muted mb-8" viewBox="0 0 16 16">
                    <path d="M7.354 5.646a.5.5 0 1 0-.708.708L7.793 7.5 6.646 8.646a.5.5 0 1 0 .708.708L8.5 8.207l1.146 1.147a.5.5 0 0 0 .708-.708L9.207 7.5l1.147-1.146a.5.5 0 0 0-.708-.708L8.5 6.793 7.354 5.646z"/>
                    <path d="M.5 1a.5.5 0 0 0 0 1h1.11l.401 1.607 1.498 7.985A.5.5 0 0 0 4 12h1a2 2 0 1 0 0 4 2 2 0 0 0 0-4h7a2 2 0 1 0 0 4 2 2 0 0 0 0-4h1a.5.5 0 0 0 .491-.408l1.5-8A.5.5 0 0 0 14.5 3H2.89l-.405-1.621A.5.5 0 0 0 2 1H.5zm3.915 10L3.102 4h10.796l-1.313 7h-8.17zM6 14a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm7 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
                </svg>
                <h3 class="mb-4">No Pre-Orders Yet</h3>
                <p class="text-muted mb-8 fs-18px">Looks like you haven't added any products to your pre-order list yet.</p>
                <a href="<?=base_url('products')?>" class="btn btn-dark btn-lg px-12">
                    <i class="fas fa-shopping-bag me-2"></i> Browse Products
                </a>
            </div>
        <?php endif; ?>
    </div>
</section>

<!-- Cart Page Scripts -->
<script>
$(document).ready(function() {
    
    // Increase quantity
    $('.qty-increase').on('click', function() {
        var cartId = $(this).data('cart-id');
        var input = $('#qty_' + cartId);
        var currentVal = parseInt(input.val()) || 1;
        input.val(currentVal + 1);
        updateCartItem(cartId, currentVal + 1);
    });
    
    // Decrease quantity
    $('.qty-decrease').on('click', function() {
        var cartId = $(this).data('cart-id');
        var input = $('#qty_' + cartId);
        var currentVal = parseInt(input.val()) || 1;
        if (currentVal > 1) {
            input.val(currentVal - 1);
            updateCartItem(cartId, currentVal - 1);
        }
    });
    
    // Remove item
    $('.remove-item').on('click', function() {
        var cartId = $(this).data('cart-id');
        if (confirm('Are you sure you want to remove this item?')) {
            removeCartItem(cartId);
        }
    });
    
    // Clear all cart
    $('#clearCart').on('click', function() {
        if (confirm('Are you sure you want to clear all items from your pre-order?')) {
            clearAllCart();
        }
    });
    
    // Coupon form
    $('#couponForm').on('submit', function(e) {
        e.preventDefault();
        var couponCode = $('#couponCode').val();
        if (couponCode) {
            applyCoupon(couponCode);
        }
    });
    
    function updateCartItem(cartId, quantity) {
        $.ajax({
            type: 'POST',
            url: '<?=base_url("products/update_to_cart")?>',
            data: { cartId: cartId, quantity: quantity },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    // Update line total
                    var price = parseFloat($('#qty_' + cartId).data('price'));
                    var newTotal = (price * quantity).toFixed(2);
                    $('#total_' + cartId).text('$' + newTotal);
                    
                    // Recalculate cart totals
                    recalculateCartTotals();
                    
                    Toastify({
                        text: 'Pre-order updated',
                        duration: 2000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#28a745",
                    }).showToast();
                }
            }
        });
    }
    
    function removeCartItem(cartId) {
        $.ajax({
            type: 'POST',
            url: '<?=base_url("products/remove_from_cart")?>',
            data: { cartId: cartId },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    // Remove row from table
                    $('tr[data-cart-id="' + cartId + '"]').fadeOut(300, function() {
                        $(this).remove();
                        recalculateCartTotals();
                        
                        // Check if cart is empty
                        if ($('.cart-row').length === 0) {
                            location.reload();
                        }
                    });
                    
                    // Update header cart count
                    var currentCount = parseInt($('.cart-count').text()) || 0;
                    $('.cart-count').text(Math.max(0, currentCount - 1));
                    
                    Toastify({
                        text: 'Item removed from pre-order',
                        duration: 2000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#dc3545",
                    }).showToast();
                }
            }
        });
    }
    
    function clearAllCart() {
        $.ajax({
            type: 'POST',
            url: '<?=base_url("products/clear_cart")?>',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $('.cart-count').text('0');
                    location.reload();
                }
            }
        });
    }
    
    function applyCoupon(code) {
        $.ajax({
            type: 'POST',
            url: '<?=base_url("products/apply_coupon")?>',
            data: { coupon_code: code },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $('#couponMessage').html('<div class="alert alert-success">' + response.message + '</div>');
                    // Update totals if discount applied
                    if (response.discount) {
                        $('#discountRow').show();
                        $('#cartDiscount').text('-$' + response.discount);
                        $('#cartTotal').text('$' + response.new_total);
                    }
                } else {
                    $('#couponMessage').html('<div class="alert alert-danger">' + response.message + '</div>');
                }
            }
        });
    }
    
    function recalculateCartTotals() {
        var subtotal = 0;
        $('.cart-row').each(function() {
            var cartId = $(this).data('cart-id');
            var qty = parseInt($('#qty_' + cartId).val()) || 1;
            var price = parseFloat($('#qty_' + cartId).data('price')) || 0;
            subtotal += qty * price;
        });
        
        $('#cartSubtotal').text('$' + subtotal.toFixed(2));
        $('#cartTotal').text('$' + subtotal.toFixed(2));
    }
});
</script>

