
<div class="card block" x-data="block_products">
    <div class="card-body" >
        <div class="row mb-2">
            <div class="col-lg-12">
                <span class="float-left">
                    <h4 class="block-title">
                         <i class="fa fa-list-alt text-success"></i>
                        {{__("Products")}}
                    </h4>
                </span>
            </div>
        </div>
        <div class="row mt-10">

            <div class="col-lg-12 m-b-5">
                <div class="pull-right">
                    <div class="form-group">
                        <input type="text" x-model="search" class="form-control form-control-sm"
                               placeholder="Product Name, Ref ...">
                         <small class="float-right">
                              <strong class="fs-10 text-blue">
                                <strong x-text="'Found : '+ formatNumber(filteredProducts.length)+' / '"></strong>
                               <strong x-text="'Total : '+formatNumber(products.length)">/</strong>
                            </strong>
                         </small>
                    </div>
                </div>
            </div>

            <div class="col-lg-12">
                <template x-if="blank(filteredProducts)">
                    <x-not-found>
                        <x-slot name="tittle">{{__("No Product found.")}}</x-slot>
                        <x-slot name="desc">'{{__('Make sure your typing a correct value filter, or click to refresh products list.')}}'</x-slot>
                    </x-not-found>
                </template>
            </div>
            <div class="col-lg-12">
                <div class="row" style="max-height:500px; overflow-y:scroll">
                    <template x-for="product in filteredProducts" :key="product.id">

                        <div class="col-lg-4 col-xl-4 col-xxl-3 col-6 form-group"
                             x-data="product_availability(product)">
                            <div class="product-card cursor-pointer rounded "
                                @click="addToCart(product,is_available);">
                                <div x-transition x-show="!is_available" class="badge badge-danger fs-8 badge-nav">{{__("Unavailable")}}</div>
                                <div class="product-tumb"
                                :styleliste="'background: no-repeat center url('+product.image+');'">
                                    <img class="rounded" :src="`${product.image}`" :alt="product.name">
                                </div>
                                <div class="product-details p-2 text-center">
                                    <div class="font-weight-bold fs-12 text-uppercase product-name" x-text="product.name"></div>
                                    <div class="product-price text-success">
                                        <div class="font-weight-bold" x-text="formatNumber(product?.price ?? 0,currency)"></div>
                                    </div>
                                </div>
                                {{-- <div class="card-footer">
                                    <button class="btn btn-success btn-block"><i class="fa fa-shopping-cart"></i></button>
                                </div> --}}
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</div>



@push("js")
    <script>

        document.addEventListener('alpine:init', () => {

            // document.dispatchEvent(new CustomEvent('open-modal', {}));

            document.addEventListener("open-modal", ()=>{

            })

            Alpine.data('product_availability' , (product) => ({

                product : product,

                get is_available(){
                    const product = this.product;
                    let available = true;
                    @if(getSettingsOf("check_stock_when_ordering_backend"))
                        if ( product){
                            const stocks = this.$store.data_page?.stocks?.filter(s => (s.product_id === product.id) ) ?? [];
                            if (stocks.length){
                                available = (getSum(stocks,"qty") > 0)
                            }else{
                                available = false;
                            }

                        }
                    @endif
                    return available;
                },

                productIsAvailable(order_qty){
                    const warehouse_id = this.warehouse_id;
                    let available = true;

                    @if(getSettingsOf("check_stock_when_ordering_backend"))
                        if (warehouse_id && product){
                            const stocks = this.$store.data_page.stocks?.filter(s => ( (s.warehouse_id === warehouse_id) && (s.product_id === product.id) ) );
                            if (stocks.length){
                                const stock_qty = getSum(stocks,"qty")
                                console.log("id = "+product.id+" stock_qty = "+stock_qty)
                                available = (order_qty <= stock_qty)
                            }else{
                                available = false;
                            }
                        }
                    @endif


                    return available;

                },
            }))

            Alpine.data('block_products', () => ({

                async init (){
                //    await this.refresh();
                    const alpine = this;

                },

                search : "",
                // products : [],

                get products(){
                    return this.$store.data_page?.products ?? [];
                },

                get filteredProducts (){
                    const search = this.search.toLowerCase()
                    if(search){
                        return this.products.filter(
                                        product =>
                                            ( product.id.toString().startsWith(search) ||
                                            product.name.toLowerCase().startsWith(search) ||
                                            product.full_name.toLowerCase().includes(search)

                                            )
                                )
                    }
                    return this.products;
                },

                addToCart(item,is_available = true) {
                    //document.dispatchEvent(new CustomEvent('cart.item.added', { detail : item}));
                    if (is_available) {
                      return  this.$dispatch('cart.order.items.added', item);
                    }
                    return swal.fire({
                        icon : "warning",
                        title : item.full_name,
                        text : "{{__("Not Available")}}",
                    })
                }

            }));

        });
    </script>
@endpush
