<!-- Page Title Section -->
<section class="page-title z-index-2 position-relative">
    <div class="bg-body-secondary">
        <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 href="<?=base_url()?>">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page"><?=$page_title ?? 'Shop'?></li>
                </ol>
            </nav>
        </div>
    </div>
    <div class="text-center py-13">
        <div class="container">
            <h2 class="mb-0"><?=$page_title ?? 'Shop'?></h2>
        </div>
    </div>
</section>

<!-- Toolbar Section -->
<section class="container container-xxl">
    <div class="tool-bar mb-11 align-items-center justify-content-between d-lg-flex">
        <div class="tool-bar-left mb-6 mb-lg-0 fs-18px">
            We found <span class="text-body-emphasis fw-semibold"><?=count($products)?></span> products available for you
        </div>
        <div class="tool-bar-right align-items-center d-lg-flex">
            <ul class="list-unstyled d-flex align-items-center list-inline me-lg-7 me-0 mb-6 mb-lg-0">
                <li class="list-inline-item me-7">
                    <a class="fs-32px text-body-emphasis" href="#">
                        <svg class="icon icon-squares-four"><use xlink:href="#icon-squares-four"></use></svg>
                    </a>
                </li>
                <li class="list-inline-item d-lg-none ms-auto">
                    <a data-bs-toggle="offcanvas" href="#filterSidebar" role="button" class="btn btn-hover-border-primary btn-hover-bg-primary btn-hover-text-light btn-dark">
                        <i class="fas fa-sliders-h me-2"></i> Filter
                    </a>
                </li>
            </ul>
            <ul class="list-unstyled d-flex align-items-center list-inline mb-0">
                <li class="list-inline-item me-0 w-100 w-lg-auto">
                    <form method="get" action="<?=base_url('products')?>" id="sortForm">
                        <?php if($this->input->get('category')): ?>
                            <input type="hidden" name="category" value="<?=$this->input->get('category')?>">
                        <?php endif; ?>
                        <?php if($this->input->get('name')): ?>
                            <input type="hidden" name="name" value="<?=$this->input->get('name')?>">
                        <?php endif; ?>
                        <select class="form-select w-100 w-lg-auto" name="sort" onchange="document.getElementById('sortForm').submit()">
                            <option value="" <?=!$this->input->get('sort') ? 'selected' : ''?>>Default sorting</option>
                            <option value="latest" <?=$this->input->get('sort') == 'latest' ? 'selected' : ''?>>Sort by latest</option>
                            <option value="price_low" <?=$this->input->get('sort') == 'price_low' ? 'selected' : ''?>>Sort by price: low to high</option>
                            <option value="price_high" <?=$this->input->get('sort') == 'price_high' ? 'selected' : ''?>>Sort by price: high to low</option>
                            <option value="name_asc" <?=$this->input->get('sort') == 'name_asc' ? 'selected' : ''?>>Sort by name: A-Z</option>
                            <option value="name_desc" <?=$this->input->get('sort') == 'name_desc' ? 'selected' : ''?>>Sort by name: Z-A</option>
                        </select>
                    </form>
                </li>
                <li class="list-inline-item d-none d-lg-block ms-7">
                    <a data-bs-toggle="offcanvas" href="#filterSidebar" role="button" class="btn btn-hover-border-primary btn-hover-bg-primary btn-hover-text-light btn-dark">
                        <i class="fas fa-sliders-h me-2"></i> Filter
                    </a>
                </li>
            </ul>
        </div>
    </div>
</section>

<!-- Filter Sidebar (Offcanvas) -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="filterSidebar" aria-labelledby="filterSidebarLabel">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title fs-3" id="filterSidebarLabel">Filter</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body">
        <aside class="primary-sidebar">
            <!-- Category Filter -->
            <div class="widget widget-product-category mb-10">
                <h4 class="widget-title fs-5 mb-6">Category</h4>
                <ul class="navbar-nav navbar-nav-cate list-unstyled">
                    <li class="nav-item mb-3">
                        <a href="<?=base_url('products')?>" 
                           class="text-reset d-block text-decoration-none text-body-emphasis-hover text-uppercase fs-14px fw-semibold <?=!$this->input->get('category') ? 'text-primary' : ''?>">
                            <span class="text-hover-underline">All Products</span>
                        </a>
                    </li>
                    <?php if($categories): foreach($categories as $category): ?>
                        <li class="nav-item mb-3">
                            <a href="<?=base_url('products?category='.$category->categoryUnique)?>" 
                               class="text-reset d-block text-decoration-none text-body-emphasis-hover text-uppercase fs-14px fw-semibold <?=$this->input->get('category') == $category->categoryUnique ? 'text-primary' : ''?>">
                                <span class="text-hover-underline"><?=$category->category_name?></span>
                            </a>
                        </li>
                    <?php endforeach; endif; ?>
                </ul>
            </div>
            
            <!-- Price Filter -->
            <div class="widget widget-product-price mb-10">
                <h4 class="widget-title fs-5 mb-6">Price Range</h4>
                <ul class="navbar-nav navbar-nav-cate list-unstyled">
                    <li class="nav-item mb-3">
                        <a href="<?=base_url('products')?>" class="text-reset d-block text-decoration-none text-body-emphasis-hover">
                            <span class="text-hover-underline">All Prices</span>
                        </a>
                    </li>
                    <li class="nav-item mb-3">
                        <a href="<?=base_url('products?price_min=0&price_max=50')?>" class="text-reset d-block text-decoration-none text-body-emphasis-hover">
                            <span class="text-hover-underline">Under $50</span>
                        </a>
                    </li>
                    <li class="nav-item mb-3">
                        <a href="<?=base_url('products?price_min=50&price_max=100')?>" class="text-reset d-block text-decoration-none text-body-emphasis-hover">
                            <span class="text-hover-underline">$50 - $100</span>
                        </a>
                    </li>
                    <li class="nav-item mb-3">
                        <a href="<?=base_url('products?price_min=100&price_max=200')?>" class="text-reset d-block text-decoration-none text-body-emphasis-hover">
                            <span class="text-hover-underline">$100 - $200</span>
                        </a>
                    </li>
                    <li class="nav-item mb-3">
                        <a href="<?=base_url('products?price_min=200')?>" class="text-reset d-block text-decoration-none text-body-emphasis-hover">
                            <span class="text-hover-underline">Over $200</span>
                        </a>
                    </li>
                </ul>
            </div>
            
            <!-- Clear Filters -->
            <div class="widget">
                <a href="<?=base_url('products')?>" class="btn btn-outline-dark w-100">Clear All Filters</a>
            </div>
        </aside>
    </div>
</div>

<!-- Products Grid Section -->
<div class="container container-xxl pb-16 pb-lg-18 mb-lg-3">
    <?php if($products && count($products) > 0): ?>
        <div class="row gy-50px">
            <?php foreach($products as $product): ?>
                <div class="col-sm-6 col-lg-4 col-xl-3">
                    <div class="card card-product grid-1 bg-transparent border-0" data-animate="fadeInUp">
                        <figure class="card-img-top position-relative mb-7 overflow-hidden">
                            <a href="<?=base_url('products/view/'.$product->slug.'/'.$product->productUnique)?>" class="hover-zoom-in d-block" title="<?=$product->name?>">
                                <img src="<?=PRODUCT_ASSETS_URL.$product->image?>" class="img-fluid w-100" alt="<?=$product->name?>" width="330" height="440">
                            </a>
                            
                            <?php if($product->discount_percentage): ?>
                                <div class="position-absolute product-flash z-index-2">
                                    <span class="badge badge-product-flash on-sale bg-primary">-<?=$product->discount_percentage?>%</span>
                                </div>
                            <?php endif; ?>
                            
                            <div class="position-absolute d-flex z-index-2 product-actions horizontal">
                                <button type="button" 
                                        class="text-body-emphasis bg-body bg-dark-hover text-light-hover rounded-circle square product-action shadow-sm border-0 quick-add-to-cart" 
                                        data-product-unique="<?=$product->productUnique?>"
                                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Quick Pre-Order">
                                    <svg class="icon icon-shopping-bag-open-light">
                                        <use xlink:href="#icon-shopping-bag-open-light"></use>
                                    </svg>
                                </button>
                                <a class="text-body-emphasis bg-body bg-dark-hover text-light-hover rounded-circle square product-action shadow-sm wishlist" 
                                   href="#" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Add To Wishlist">
                                    <svg class="icon icon-star-light">
                                        <use xlink:href="#icon-star-light"></use>
                                    </svg>
                                </a>
                            </div>
                        </figure>
                        
                        <div class="card-body text-center p-0">
                            <!-- Price -->
                            <span class="d-flex align-items-center price text-body-emphasis fw-bold justify-content-center mb-3 fs-6">
                                <?php if($product->discount_percentage): ?>
                                    <del class="text-body fw-500 me-4 fs-13px"><?=currency_main_symbol($product->amount, 1)?></del>
                                    <ins class="text-decoration-none"><?=currency_main_symbol($product->amount, 1, true, $product->discount_percentage)?></ins>
                                <?php else: ?>
                                    <?=currency_main_symbol($product->amount, 1)?>
                                <?php endif; ?>
                            </span>
                            
                            <!-- Product Title -->
                            <h4 class="product-title card-title text-primary-hover text-body-emphasis fs-15px fw-500 mb-3">
                                <a class="text-decoration-none text-reset" href="<?=base_url('products/view/'.$product->slug.'/'.$product->productUnique)?>"><?=$product->name?></a>
                            </h4>
                            
                            <!-- Category -->
                            <?php if($product->category_name): ?>
                                <p class="text-muted fs-13px mb-0"><?=$product->category_name?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <!-- No Products Found -->
        <div class="text-center py-20">
            <div class="mb-8">
                <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" fill="currentColor" class="text-muted" viewBox="0 0 16 16">
                    <path d="M2.97 1.35A1 1 0 0 1 3.73 1h8.54a1 1 0 0 1 .76.35l2.609 3.044A1.5 1.5 0 0 1 16 5.37v.255a2.375 2.375 0 0 1-4.25 1.458A2.371 2.371 0 0 1 9.875 8 2.37 2.37 0 0 1 8 7.083 2.37 2.37 0 0 1 6.125 8a2.37 2.37 0 0 1-1.875-.917A2.375 2.375 0 0 1 0 5.625V5.37a1.5 1.5 0 0 1 .361-.976l2.61-3.045zm1.78 4.275a1.375 1.375 0 0 0 2.75 0 .5.5 0 0 1 1 0 1.375 1.375 0 0 0 2.75 0 .5.5 0 0 1 1 0 1.375 1.375 0 1 0 2.75 0V5.37a.5.5 0 0 0-.12-.325L12.27 2H3.73L1.12 5.045A.5.5 0 0 0 1 5.37v.255a1.375 1.375 0 0 0 2.75 0 .5.5 0 0 1 1 0zM1.5 8.5A.5.5 0 0 1 2 9v6h12V9a.5.5 0 0 1 1 0v6h.5a.5.5 0 0 1 0 1H.5a.5.5 0 0 1 0-1H1V9a.5.5 0 0 1 .5-.5zm2 .5a.5.5 0 0 1 .5.5V13h8V9.5a.5.5 0 0 1 1 0V13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9.5a.5.5 0 0 1 .5-.5z"/>
                </svg>
            </div>
            <h4 class="mb-4">No Products Found</h4>
            <p class="text-muted mb-8">We couldn't find any products matching your criteria.</p>
            <a href="<?=base_url('products')?>" class="btn btn-dark px-10">View All Products</a>
        </div>
    <?php endif; ?>
</div>

<script>
$(document).ready(function() {
    // Quick Add to Cart
    $('.quick-add-to-cart').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var btn = $(this);
        var productUnique = btn.data('product-unique');
        
        console.log('Adding product:', productUnique);
        
        if (!productUnique) {
            alert('Product not found');
            return;
        }
        
        btn.prop('disabled', true);
        
        $.ajax({
            type: 'POST',
            url: '<?=base_url("products/add_to_cart")?>',
            data: { 
                productUnique: productUnique,
                quantity: 1
            },
            dataType: 'json',
            success: function(response) {
                console.log('Response:', response);
                btn.prop('disabled', false);
                
                if (response.status === 'success') {
                    // Update cart count
                    $('.cart-count').text(response.cart_count);
                    
                    // Update cart sidebar HTML
                    if (response.cart_html) {
                        $('.result-cart').html(response.cart_html);
                    }
                    
                    if (typeof Toastify !== 'undefined') {
                        Toastify({
                            text: "Product added to pre-order!",
                            duration: 3000,
                            gravity: "top",
                            position: "right",
                            style: { background: "#28a745" },
                        }).showToast();
                    } else {
                        alert('Product added to pre-order!');
                    }
                } else {
                    if (typeof Toastify !== 'undefined') {
                        Toastify({
                            text: response.message || "Error adding product",
                            duration: 3000,
                            gravity: "top",
                            position: "right",
                            style: { background: "#dc3545" },
                        }).showToast();
                    } else {
                        alert(response.message || 'Error adding product');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', status, error);
                console.log('Response:', xhr.responseText);
                btn.prop('disabled', false);
                if (typeof Toastify !== 'undefined') {
                    Toastify({
                        text: "Error adding product to cart",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        style: { background: "#dc3545" },
                    }).showToast();
                } else {
                    alert('Error adding product to cart');
                }
            }
        });
    });
});
</script>

