
<div class="block" x-data="bloc_cart">
    <div class="card-body p-2 bg-white">

        <div class="row" id="bloc-display-order">
            <template x-if="$store.cart.count" x-transition>

                <div class="col-lg-12 m-b-10"  style="display: table-row">
                    <center class="m-b-5">
                        <img src="{{url("img/logo-bw.png")}}" alt="Logo" style="height: 50px; width:150px;">
                    </center>
                   <div class="rows d-flex justify-content-between">
                       <div classs="col-lg-6 col-sm-6 col-xs-6s "
                            styles="display: table-cell ; width: 50% ; align-content: start; border-right: 2px solid #eee">
                           <div class="float-left">
                               <h6 class="m-b-1 fs-14"><strong>Owner Infos</strong></h6>
                               {{--                            <div><strong>{{getSettingsOf("owner_name")}}</strong></div>--}}
                               <div class="fs-11 order-head-info">Phone : <strong>{{getSettingsOf("phone_number")}}</strong></div>
                               <div class="fs-11 order-head-info">Adress : <strong>{{getSettingsOf("address2")}}</strong></div>
                               <div class="fs-11 order-head-info">Email : <strong>{{getSettingsOf("site_email")}}</strong></div>
                           </div>
                       </div>
                       <div classs="col-lg-6 col-sm-6 col-xs-6" styles="display: table-cell ; width: 50%;">
                           <template x-if="$store.cart.customer">
                               <div class="float-right fs-11" >
                                   <h6 class="m-b-1 fs-13"><strong>Customer Infos</strong></h6>
                                   <div class="fs-11 order-head-info">Full Name : <strong x-text="$store.cart.customer.full_name ?? '---'"></strong></div>
                                   <div class="fs-11 order-head-info">Email : <strong x-text="$store.cart.customer.email ?? '---'"></strong></div>
                                   <div class="fs-11 order-head-info">Phone : <strong x-text="$store.cart.customer.phone ?? '---'"></strong></div>
                                   {{--                                                   <div>Address : <strong x-text="$store.cart.customer.full_default_address"></strong></div>--}}
                               </div>
                           </template>
                       </div>
                   </div>
                </div>
            </template>

            <div class="col-lg-12 m-b-5">
                <table class="table table-bordereds table-condensed" id="table-cart" style="border: none">
                    <thead>
                    <tr>
                        <th class="left fs-12">Product</th>
                        <th class="right fs-12">P.U</th>
                        {{-- <th class="right fs-12">Qty</th> --}}
                        <th class="right fs-12">Amount</th>
                        <th class="right fs-12 d-print-none" width="2%">---</th>
                    </tr>
                    </thead>
                    <tbody>
                    <template x-for="(item,index) in $store.cart.items" :key="index">
                        <tr class="fs-12">
                            <td class="fs-12 cursor-pointer" @click="updateQty($el,item)">
                                                    <span class="text-success text-underline">
                                                        <span x-text="formatNumber(item.qty)"></span>
                                                        <span> x </span>
                                                        <span class="text-uppercase" x-text="item.name"></span>
        {{--                                                <span class="float-right fa fa-edit"></span>--}}
                                                    </span>
                            </td>
                            {{-- <td class="fs-12 right"> <span x-text="formatNumber(item.qry)"></span></td> --}}
                            <td class="fs-12 right"> <span x-text="formatNumber(item.price)"></span></td>
                            <td class="fs-12 right">
                                <span x-text="formatNumber(item.amount)"></span>
                            </td>
                            <td class="fs-12 right d-print-none">
                                <div class="pull-right">
                                    <small class="text-danger btn btn-sm"
                                           @click="$store.cart.remove(item)">
                                        <i class="fa fa-times"></i>
                                    </small>
                                </div>
                            </td>
                        </tr>
                    </template>
                    <template x-if="$store.cart.count <= 0">
                        <tr>
                            <td colspan="3" class="center">
                                <div>
                                    <h5 class="fs-14 text-danger"><strong>No Product in cart.</strong></h5>
                                    <p class="text-muted fs-10">For add product in order, you may to click on any item in products list</p>
                                </div>
                            </td>
                        </tr>
                    </template>
                    </tbody>
                </table>

                <template x-if="$store.cart.items.length > 0">
                    <table class="table table-borderedq table-condensed">
                        <thead>
                            <template x-for="T in Object.values(allTotal)">
                                <tr>
                                    <th :class="T.className" class="left" x-text="T.label"></th>
                                    <th :class="T.className" class="right" x-text="formatNumber(T.value,currency)"></th>
                                </tr>
                            </template>
                        </thead>
                    </table>
                </template>
            </div>

            <template x-if="$store.cart.count > 0">
                <div class="col-lg-12 d-print-none">
                    <div class="border border-dark p-2 rounded-sm d-flex justify-content-between">
                        <div x-data="{is_checked : true}" x-init="$watch('is_checked', value => { $store.cart.setConfig({check_stock : value}) } )">
                            <div class="custom-control custom-switch cursor-pointer">
                                <input type="checkbox"
                                       checked
                                       class="custom-control-input cursor-pointer"
                                       data-on-color="success"
                                       datas-offs-colors="info"
                                       x-model="is_checked"
{{--                                       @click="$store.cart.setConfig({check_stock : $event.target.value})"--}}
                                       id="switch-check-stock">
                                <label class="custom-control-label fs-14 cursor-pointer" for="switch-check-stock">Check Stock</label>
                            </div>
                        </div>
                        <div  x-data="{is_checked : true}" x-init="$watch('is_checked', value => { $store.cart.setConfig({payment_required : value}) } )">
                            <div class="custom-control custom-switch cursor-pointer">
                                <input type="checkbox"
                                       checked
                                       x-model="is_checked"
{{--                                       @click="$store.cart.setConfig({payment_required : $event.target.value})"--}}
                                       class="custom-control-input cursor-pointer"
                                       id="switch-payment-required">
                                <label class="custom-control-label fs-14 cursor-pointer" for="switch-payment-required">Payment</label>
                            </div>
                        </div>
                    </div>
                </div>
            </template>

            <template x-if="paymentMethods.length >0 && $store.cart.count > 0">
                <div class="col-lg-12 d-print-none m-t-5">
                    <template x-if="$store.cart.config.payment_required">
                        <div class="row">
                            <template x-for="(method,index) in paymentMethods" :key="index">

                                <div class="col-lg-6 col-sm-6 m-b-5">
                                    <div class="card cursor-pointer p-2" style="max-height: 150px;">
                                        <div class="media">
                                            <div>
                                                <div class="custom-control custom-radio mr-sm-1 cursor-pointer">
                                                    <input type="radio"
                                                           x-model="paymentMethodCode"
                                                           :value="method.code"
                                                           class="custom-control-input"
                                                           :id="'radio-'+index"
                                                    />
                                                    <label class="custom-control-label fs-12 cursor-pointer" :for="'radio-'+index"></label>
                                                </div>
                                            </div>
                                            <div class="media-body">
                                                <h5 class="mt-0 mb-1 fs-12" x-text="method.name"></h5>
                                            </div>
                                            <div  class="float-right my-s1">
                                                <img class="mr-3s" :src="`${method.image}`" :alt="method.name" style="width: 70px; height: 50px">
                                            </div>
                                        </div>

                                    </div>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>
            </template>
        </div>
    </div>

    <template x-if="$store.cart.count">
        <div class="card-footer p-1 d-print-none">
            <template x-if="$store.cart.config.payment_required">
                <button class="m-b-5 btn btn-success rounded-sm btn-block text-uppercase"
                        :disabled="$.isEmptyObject(paymentMethod)"
                        @click="payOrder">
                    Pay this Order
                    <i class="m-l-2 fa fa-money-bill-alt"></i>
                </button>
            </template>
            <template x-if="!$store.cart.config.payment_required">
                <button  class="btn btn-success rounded-sm btn-block text-uppercase"
                         @click="submitOrder">
                    Submit this Order <i class="m-l-2 fa fa-send-o"></i>
                </button>
            </template>
            <button class="btn btn-warning rounded-sm btn-block text-uppercase"
                    @click="printHtmlBlock('bloc-display-order')">
                Print this order
                <i class="m-l-2 fa fa-print"></i>
            </button>
            <button class="btn btn-primary rounded-sm btn-block text-uppercase"
                    @click="addOrderToDraft">
                Copy this order to Draft
                <i class="m-l-2 fa fa-archway"></i>
            </button>
        </div>
    </template>
</div>


@push("js")
    <script>
        const editor =  DataTableEditor( {
            fields: [
                {
                    label: "{{__('Qty')}} : ",
                    name: "qty" ,
                    type: "text",
                    attr : {  type:"number" },
                },

            ],
        } );


        const paymentMethods = @json($paymentMethods);

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

            Alpine.data("switch",() => ({
                init (){
                    const component = this;
                    // component.$watch('checked', (value) => {
                    //     console.log(value)
                    //
                    //     // component.paymentMethod = component.paymentMethods.find(method => method.code === value)
                    // })
                },
                is_checked : true,

            }))

            Alpine.store('cart', {
                init (){
                    const cart = this.content;
                    this.items = cart.items ?? [] ;
                    this.customer = cart.customer ?? null ;
                    this.config = {
                        check_stock : true,
                        payment_required : true,
                    };
                },
                customer : null,
                items :  [],
                config: {},

                get count () {
                    return this.items.length
                }  ,

                get content  () {
                    return  JSON.parse(localStorage.getItem("CART")) ?? {};
                },
                reset () {
                    this.setItems([])
                },

                setCart ( cart = {}){

                    localStorage.setItem("CART",JSON.stringify(cart))

                    if ("customer" in cart){
                        this.customer = cart.customer;
                    }
                    if ("config" in cart){
                        this.config = cart.config ;
                    }
                },

                setCustomer (customer){
                    const cart = this.content;
                    cart.customer = customer;
                    this.setCart(cart)

                },
                setConfig (param = {}){
                    const cart = this.content;
                    const {config} = cart;
                    cart.config = {...config,...param};

                    // console.log(cart.config)
                    this.setCart(cart)
                },

                setItems (items){
                    const cart  = this.content ;
                    if(items) {
                        items.forEach(item => item.amount = item.price * item.qty);
                        cart.items = items;
                        this.setCart(cart)
                    }
                    this.items = cart.items;
                },

                find (item){
                    return (this.items.length) ? this.items.find( ({id}) => (id === item.id)) : null
                },

                get total () {
                    return getSum(this.items,"amount")
                }  ,

                add(item){
                    const items = this.items;
                    const product = this.find(item)
                    if (product){
                        this.update(product,++product.qty)
                        item = product
                    }else{
                        item.qty = 1;
                        items.push(item)
                    }

                    toast({title : "<span class='fs-13 m-b-1'> " + item.qty +" x "+ item.name.toUpperCase()+"</span>"})
                    this.setItems(items)
                },
                update (item, qty){
                    const items = this.items;
                    if (typeof item === 'object' && ('id' in item)){
                        item = item.id;
                    }
                    items.forEach( cart_item => {
                        if (cart_item.id === item) {
                            cart_item.qty = qty
                        }
                    })
                    this.setItems(items)
                },
                remove (product){
                    let items = this.items;
                    items =  items.filter(item => item.id !== product.id);
                    this.setItems(items)
                },
            });

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

                init(){
                    this.paymentMethods = paymentMethods;

                    // this.paymentMethod = this.paymentMethods.find(method => method.code === "NO_PAYMENT")

                    const component = this;
                    component.$watch('paymentMethodCode', (value) => {
                        component.paymentMethod = component.paymentMethods.find(method => method.code === value);
                        component.$store.cart.setConfig({payment_method_id :component.paymentMethod.id })
                    })
                },
                paymentMethods : [],
                paymentMethod : null,
                paymentMethodCode : null,

                updateQty (td,item) {
                    const alpine = this;
                    const qty = item.qty;

                    editor.field('qty').s.def = qty
                    editor.field('qty').set(qty)
                    editor.field('qty').dom.inputControl.value = qty;

                    editor.bubble( td,["qty"], {
                        message: item.name.toUpperCase(),
                        buttons: {
                            label: '{{__("OK")}}',
                            className : "btn-success fs-11",
                            fn : function (e) {
                                const new_qty = parseFloat(this.field('qty').get());

                                if(new_qty > 0){
                                    alpine.$store.cart.update(item, new_qty)
                                    this.close();
                                }else{
                                    this.field('qty').error("{{__('This value is invalid.')}}");
                                }
                                // $(".DTE_Form_Error").css("display","none")
                            },
                        },
                    } );

                },

                get payable(){
                    const paymentMethod= this.paymentMethod;

                    const {net_payable} = this.allTotal;

                    let result = true;

                    if (paymentMethod || net_payable ===0){
                        result = false;
                    }
                    else if (paymentMethod && net_payable > 0){
                        result = true;
                    }
                    return result;
                },

                get allTotal (){

                    const cart = this.$store.cart;
                    const {total,customer} = cart;

                    const  balance = customer?.balance ?? 0;
                    const  tax = 0;

                    const  discount = 0;

                    const cartTotal = (total + tax) - discount;
                    let    net_payable = cartTotal;

                    const result = {
                        sub_total : {
                            label: "Sub Total",
                            className: "fs-12",
                            value : total,
                        },
                        tax  : {
                            label: "Tax",
                            className: "fs-12",
                            value :  tax
                        },
                        discount  : {
                            label: "Discount"+" ("+discount/100+"%)",
                            className: "fs-12 text-success",
                            value : discount
                        },
                        total  : {
                            label: "Total",
                            className: "fs-13 text-success",
                            value : cartTotal
                        },
                    };

                    if (balance <= cartTotal){
                        net_payable = cartTotal - balance;
                    }else if ( balance > cartTotal){
                        net_payable = 0;
                    }
                    result.net_payable = {
                        label: "Net Payable",
                        className: "fs-14 text-danger",
                        value : net_payable
                    }
                    return result;
                },

                addOrderToDraft(){
                    const order = this.$store.cart.content;
                    if (order){
                        this.$store.draft.add(order)
                    }
                },

                printOrder(order = null){

                },

                submitOrder (){
                    return confirmAction({
                        text : "{{__("Submit this order ?")}}",
                        preConfirm : () => {
                            this.sendOrder();

                            swal.fire({
                                title: '{{__("In Progress ...")}}',
                                text: "Don't close this popup !",
                                icon: 'info',
                                showLoaderOnConfirm : true,
                                reverseButtons : true,
                                allowOutsideClick : false,
                            })

                        },
                        didClose () {

                        }
                    });
                },

                sendOrder(orderP = null){
                    const alpine = this
                    const cart = alpine.$store.cart;

                    const content = cart.content;
                    const customer = cart.customer;

                    const order = content;

                    const allTotal = alpine.allTotal;
                    const {net_payable} = allTotal;

                    order.allTotal = allTotal;

                    if(!content.config.payment_required){
                        delete  order.config.payment_method_id;
                    }
                   // order.config.payment_method_id

                    const url = "{{route("admin.orders.store")}}";

                    const body = {
                        order , customer
                    }

                    request(url,{body,method:"post"},false)
                    .then( response => {
                        const success = response.success ?? false;
                        if(success){
                            alpine.$store.cart.reset();
                        }
                        toast({title : "<span class='fs-14'>"+response.message+"</span>" , icon : success ? "success" : "error"})
                    })
                    .catch (error => {
                        swal.showValidationMessage(`${error}`)
                    });
                },

                payOrder(orderP = null){
                    const alpine = this

                    const paymentMethod = alpine.paymentMethod;
                    const cart = alpine.$store.cart;

                    const order = cart.content;
                    const customer = cart.customer;

                    const allTotal = alpine.allTotal;
                    const {net_payable} = allTotal;

                    order.allTotal = allTotal;
                    order.config.payment_method_id = paymentMethod.id;

                    const widget = paymentWidget({
                        paymentMethods,
                        onCompleted (){
                            alpine.sendOrder(order)
                        },
                        processPayData : {
                            amount : net_payable.value,
                            param : {
                                order ,
                                customer,
                            }
                        },
                    })

                    if (!$.isEmptyObject(paymentMethods)) {
                        return widget.startPaymentProcess();
                    }

                },


            })  );

        });
    </script>
@endpush
