@extends('layout.template')
@section('title','Cusella Home Furnishing | Curtains, Sofas, Wallpapers & Interior Solutions')
@section('content')

<div class="shop-area shop-page-responsive pt-100 pb-100">
    <div class="container">
        <div class="row flex-row-reverse">
            <div class="col-lg-9">
                <div class="shop-topbar-wrapper mb-40">
                    <div class="shop-topbar-left">
                        <div class="showing-item">
                            <span id="result-count">
                                Showing {{ ($meta['current_page'] - 1) * $meta['per_page'] + 1 }}
                                –
                                {{ min($meta['current_page'] * $meta['per_page'], $meta['total']) }}
                                of {{ $meta['total'] }} results
                            </span>
                        </div>
                    </div>
                    <div class="shop-topbar-right">
                        <div class="shop-sorting-area">
                            <select id="sort-select">
                                <option value="relevance">Relevance</option>
                                <option value="price_low_high">Price Low → High</option>
                                <option value="price_high_low">Price High → Low</option>
                                <option value="latest">Latest</option>
                                <option value="recommended">Recommended</option>
                            </select>
                        </div>
                        <div class="shop-view-mode nav">
                            <a class="active" href="#shop-1" data-bs-toggle="tab"><i class=" ti-layout-grid3 "></i> </a>
                            <a href="#shop-2" data-bs-toggle="tab" class=""><i class=" ti-view-list-alt "></i></a>
                        </div>
                    </div>
                </div>
                <div class="shop-bottom-area">
                    <div class="tab-content jump">
                        <div id="shop-1" class="tab-pane active">
                            <div class="row" id="product-list">
                                @foreach($products as $product)
                                <div class="col-lg-4 col-md-4 col-sm-6 col-12">
                                    <div class="product-wrap mb-35">

                                        <div class="product-img img-zoom mb-25">
                                            <a href="{{ route('product', Str::slug($product['name']).'-'.$product['product_id']) }}">
                                                <img src="{{ $product['image'] ?? asset('assets/images/default.png') }}">
                                            </a>

                                            @if(!empty($product['offer_price']))
                                            <div class="product-badge badge-top badge-right badge-pink">
                                                <span>{{ $product['offer_percent'] }}%</span>
                                            </div>
                                            @endif

                                            {{-- ACTION BUTTONS --}}
                                            <div class="product-action-wrap">
                                                <button class="product-action-btn-1" title="Wishlist">
                                                    <i class="pe-7s-like"></i>
                                                </button>

                                                <a href="{{ route('product', Str::slug($product['name']).'-'.$product['product_id']) }}" class="product-action-btn-1" title="Quick View">
                                                    <i class="pe-7s-look"></i>
                                                </a>
                                            </div>
                                        </div>
                                        <div class="mb-1">
                                            @if(!empty($product['category']))
                                            <span class="text-muted">
                                                {{ $product['category'] }}
                                            </span>
                                            @endif

                                            @if(!empty($product['subcategory']))
                                            <span>
                                                > {{ $product['subcategory'] }}
                                            </span>
                                            @endif
                                        </div>

                                        <div class="product-content">
                                            <h3><a href="{{ route('product', Str::slug($product['name']).'-'.$product['product_id']) }}">
                                                    {{ $product['name'] }}
                                                </a></h3>

                                            <div class="product-price">
                                                <span class="old-price">₹{{ $product['price'] }} </span>
                                                <span>₹{{ $product['offer_price'] }}</span>
                                            </div>


                                        </div>

                                    </div>
                                </div>
                                @endforeach
                            </div>
                            <div class="pagination-style-1" id="pagination">
                                <ul>
                                    @for($i = 1; $i <= $meta['last_page']; $i++)
                                        <li>
                                        <a href="{{ request()->fullUrlWithQuery(['page' => $i]) }}"
                                            class="{{ $meta['current_page'] == $i ? 'active' : '' }}">
                                            {{ $i }}
                                        </a>
                                        </li>
                                        @endfor
                                </ul>
                            </div>
                        </div>
                        <div id="shop-2" class="tab-pane">
                            @foreach($products as $product)
                            <div class="shop-list-wrap mb-30">
                                <div class="row">
                                    <div class="col-lg-4 col-sm-5">
                                        <div class="product-list-img">
                                            <a href="{{ route('product', Str::slug($product['name']).'-'.$product['product_id']) }}">
                                                <img src="{{ $product['image'] ?? asset('assets/images/default.png') }}" alt=" {{ $product['name'] }}">
                                            </a>

                                            @if(!empty($product['offer_price']))
                                            <div class="product-list-badge badge-right badge-pink">
                                                <span>{{ $product['offer_percent'] }}%</span>
                                            </div>
                                            @endif

                                            <div class="product-list-quickview">
                                                <button class="product-action-btn-2" title="Quick View">
                                                    <i class="pe-7s-look"></i>
                                                </button>
                                            </div>
                                        </div>




                                    </div>

                                    <div class="col-lg-8 col-sm-7">
                                        <div class="mb-3">
                                            @if(!empty($product['category']))
                                            <span class="text-muted">
                                                {{ $product['category'] }}
                                            </span>
                                            @endif

                                            @if(!empty($product['subcategory']))
                                            <span>
                                                > {{ $product['subcategory'] }}
                                            </span>
                                            @endif
                                        </div>
                                        <div class="shop-list-content">
                                            <h3><a href="{{ route('product', Str::slug($product['name']).'-'.$product['product_id']) }}">
                                                    {{ $product['name'] }}
                                                </a></h3>

                                            <div class="product-price">
                                                <span class="old-price">₹{{ $product['price'] }} </span>
                                                <span>₹{{ $product['offer_price'] }}</span>
                                            </div>

                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endforeach

                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3">
                <div class="sidebar-wrapper">
                    <div class="sidebar-widget mb-40" data-aos="fade-up">
                        <div class="search-wrap-2">
                            <input type="text"
                                id="search-input"
                                name="search"
                                placeholder="Search..."
                                value="{{ request('search') }}"
                                class="form-control">
                        </div>
                    </div>
                    <div class="sidebar-widget sidebar-widget-border mb-40 pb-35">
                        <div class="sidebar-widget-title mb-30">
                            <h3>Filter By Price</h3>
                        </div>

                        <div class="price-filter">
                            <div class="price-slider-amount">

                                <div class="label-input" style="display:flex; gap:10px;">
                                    <input type="number"
                                        id="min_price"
                                        placeholder="Min"
                                        value="{{ request('min_price') }}"
                                        class="form-control">

                                    <input type="number"
                                        id="max_price"
                                        placeholder="Max"
                                        value="{{ request('max_price') }}"
                                        class="form-control">
                                </div>

                                <button type="button"
                                    id="price-filter-btn"
                                    class="btn btn-primary mt-2">
                                    Apply
                                </button>

                            </div>
                        </div>
                    </div>
                    <div class="sidebar-widget sidebar-widget-border mb-40 pb-35">
                        <div class="sidebar-widget-title mb-25">
                            <h3>Product Subcategories</h3>
                        </div>

                        <div class="sidebar-list-style">
                            <ul>

                                @foreach($sub_categories as $sub)
                                <li>
                                    <label class="filter-item">
                                        <input type="checkbox"
                                            class="filter-checkbox"
                                            name="subcategory_id[]"
                                            value="{{ $sub['id'] }}"
                                            {{ (isset($selected_subcategory) && $selected_subcategory == $sub['id']) ? 'checked' : '' }}>
                                        <span>{{ $sub['name'] }}</span>
                                    </label>
                                </li>
                                @endforeach

                            </ul>
                        </div>
                    </div>
                    <div class="sidebar-widget sidebar-widget-border mb-40 pb-35" data-aos="fade-up">
                        <div class="sidebar-widget-title mb-25">
                            <h3>Room</h3>
                        </div>
                        <div class=" sidebar-list-style">
                            <ul>
                                @foreach($rooms as $room)
                                <li>
                                    <label class="filter-item">
                                        <input type="checkbox" class="filter-checkbox" name="room_id[]" value="{{ $room['id'] }}">
                                        <span> {{ $room['name'] }}</span>
                                    </label>
                                </li>

                                @endforeach
                            </ul>
                        </div>
                    </div>

                    <div class="sidebar-widget" data-aos="fade-up">
                        <div class="sidebar-widget-title mb-25">
                            <h3>Tags</h3>
                        </div>
                        <div class="sidebar-list-style">
                            <ul>
                                @foreach($tags as $tag)
                                <li>
                                    <label class="filter-item">
                                        <input type="checkbox" class="filter-checkbox" name="tag_id[]" value="{{ $tag['id'] }}">
                                        <span>{{ $tag['name'] }}</span>
                                    </label>
                                </li>
                                @endforeach
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>

    const productBaseUrl = "{{ url('/product') }}";

// ✅ SLUG FUNCTION
function slugify(text) {
    return text.toString().toLowerCase()
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '');
}


    function getFilters(page = 1) {

        let data = {
            search: $('#search-input').val(),
            min_price: $('#min_price').val(),
            max_price: $('#max_price').val(),
            sort: $('#sort-select').val(),
            page: page,

            // ✅ CHANGE HERE
            subcategory_id: [],
            room_id: [],
            tag_id: []
        };

        // ✅ MULTIPLE CHECKBOX VALUES
        $('.filter-checkbox:checked').each(function() {

            let name = $(this).attr('name');

            // ✅ SUBCATEGORY
            if (name === 'subcategory_id[]') {
                data.subcategory_id.push($(this).val());
            }

            if (name === 'room_id[]') {
                data.room_id.push($(this).val());
            }

            if (name === 'tag_id[]') {
                data.tag_id.push($(this).val());
            }
        });

        $.ajax({
            url: "{{ route('filter-products') }}",
            type: "GET",
            data: data,


            beforeSend: function() {
                $('#product-list').html('<p>Loading...</p>');
            },
            success: function(res) {

                let gridHtml = '';
                let listHtml = '';

                if (res.products.length === 0) {

                    gridHtml = '<p>No products found</p>';
                    listHtml = '<p>No products found</p>';

                } else {

                    $.each(res.products, function(i, product) {

                        // ✅ GRID VIEW
                        gridHtml += `
            <div class="col-lg-4 col-md-4 col-sm-6 col-12">
                <div class="product-wrap mb-35">
                    <div class="product-img img-zoom mb-25">
                        <img src="${product.image ?? '/assets/images/default.png'}">
                    </div>
                      <div class="mb-2 text-muted">
                            ${product.category ?? ''}
                            ${product.subcategory ? ' > ' + product.subcategory : ''}
                        </div>
                    <div class="product-content">
                        <h3>
                             <a href="${productUrl}">
                                        ${product.name}
                                    </a>
                        </h3>
                         
                       <div class="product-price">
    ${
        product.price && product.offer_price && product.price > product.offer_price
        ? `<span class="old-price">₹${product.price}</span>`
        : ''
    }
    <span>₹${product.offer_price ?? product.price ?? ''}</span>
        </div>
                       
                    </div>
                </div>
            </div>`;

                        // ✅ LIST VIEW
                        listHtml += `
            <div class="shop-list-wrap mb-30">
                <div class="row">
                    
                    <div class="col-lg-4 col-sm-5">
                        <div class="product-list-img">
                            <img src="${product.image ?? '/assets/images/default.png'}">
                        </div>
                    </div>

                    <div class="col-lg-8 col-sm-7">

                        <div class="mb-2 text-muted">
                            ${product.category ?? ''}
                            ${product.subcategory ? ' > ' + product.subcategory : ''}
                        </div>

                        <div class="shop-list-content">
                            <h3>
    <a href="${productBaseUrl}/${slugify(product.name)}-${product.product_id}">
        ${product.name}
    </a>
</h3>

                            <div class="product-price">
    ${
        product.price && product.offer_price && product.price > product.offer_price
        ? `<span class="old-price">₹${product.price}</span>`
        : ''
    }
    <span>₹${product.offer_price ?? product.price ?? ''}</span>
        </div>

                           

                        </div>
                    </div>

                </div>
            </div>`;
                    });
                }

                // ✅ UPDATE BOTH VIEWS
                $('#product-list').html(gridHtml); // Grid
                $('#shop-2').html(listHtml); // List

                // ✅ RESULT COUNT
                let start = (res.meta.current_page - 1) * res.meta.per_page + 1;
                let end = Math.min(res.meta.current_page * res.meta.per_page, res.meta.total);

                $('#result-count').html(`
        Showing ${res.meta.total === 0 ? 0 : start}
        –
        ${end}
        of ${res.meta.total} results
    `);

                // ✅ PAGINATION
                let pagination = '';
                for (let i = 1; i <= res.meta.last_page; i++) {
                    pagination += `
        <li>
            <a href="javascript:void(0)" onclick="getFilters(${i})"
               class="${res.meta.current_page == i ? 'active' : ''}">
                ${i}
            </a>
        </li>`;
                }

                $('#pagination').html('<ul>' + pagination + '</ul>');
            }

        });
    }

    // ✅ EVENTS
    $('#sort-select').on('change', function() {
        getFilters(); // reload products via ajax
    });
    // checkbox change
    $(document).on('change', '.filter-checkbox', function() {
        getFilters();
    });

    // 🔍 SEARCH (debounce)
    let timer;
    $('#search-input').on('keyup', function() {
        clearTimeout(timer);
        timer = setTimeout(() => {
            getFilters();
        }, 500);
    });

    // 💰 PRICE FILTER
    $('#price-filter-btn').on('click', function() {
        getFilters();
    });

    // 🔽 SORT
</script>
@endsection