<style>
    .draft-item .visible {
        border: 1px solid var(--success) !important;
    }
    .draft-item .visible h5{
        color: var(--success) !important;
    }

</style>

<div class="block" >
    <div class="card-body p-2 bg-white">
        <div class="row">
            <div class="col-lg-12 m-b-10">
                @include("backend.orders.create.blocs.order.settings-schedule-draft")
            </div>

            <div class="col-lg-12">
                <template x-if="$store.draft.count <= 0">
                    <div class="text-center p-5" >
                        <h5 class="text-danger m-b-0 fs-15"><strong>No items in draft</strong></h5>
                        <p class="fs-11 text-muted">Go to cart tab, add products, and add order in draft.</p>
                    </div>
                </template>
            </div>

            <div class="col-lg-12" x-show='$store.draft.count > 0'>
                <div class="p-1s cards border-left-successs">
                    <div class="row" x-data="displayed_draft_item">

                        <template x-if="visible">
                           <div class="cards p-1s borde shadows">

                                <div class="col-lg-12 m-b-20">
                                    <div class="float-right">
                                        <button type="button" class="ml-2 mb-1 close text-dangers"
                                                @click="closeDraftItem(displayed_index)"
                                                aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                </div>
                                <div class="col-lg-12" id="block-display-draft-item">
                                    <div x-transition x-data="order_details(displayed_order,false)">
                                        @include("backend.orders.create.blocs.order-details")
                                    </div>
                                </div>

                           </div>
                        </template>

                        <template x-if="!visible">
                            <div class="col-lg-12">

                                <div class="row">
                                    <div class="col-lg-12"></div>

                                    <div class="col-lg-12">
                                        <template x-if="$store.draft.count > 0 && !displayed_order">
                                            <div x-transition style="max-height: 400px; overflow-y: scroll" class="list-group">
                                                <template x-for="(order,index) in $store.draft.orders" :key="index">

                                                    <div class="list-group-item shadow" x-data="draft_item(index)">
                                                        <div class="d-flex w-100 justify-content-between">
                                                            <h5 class="mb-1 fs-15" x-text="order?.customer?.full_name ?? '----'"></h5>
                                                            <small class="fs-10" x-text="order?.config?.date ?? '---'"></small>
                                                            {{-- <button type="button" class="btn ml-2 text-danger mb-1 cursor-pointer btn "
                                                                    @click="$store.draft.remove(index)">
                                                                <span class="fa fa-trash fs-12"></span>
                                                            </button> --}}
                                                            <span class="float-right">
                                                                <a class="nav-link dropdown-toggle"
                                                                    href="#"
                                                                    :id="'dropdown-draft-item-options-'+index"
                                                                    role="button">

                                                                </a>
                                                                <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in"
                                                                    :aria-labelledby="'dropdown-draft-item-options-'+index">

                                                                    <a class="dropdown-item" href="javascript:void(0)">
                                                                        <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
                                                                        {{__("Profile")}}
                                                                    </a>

                                                                    <div class="dropdown-divider"></div>

                                                                    <a class="dropdown-item"
                                                                            href="javascript:void(0)"
                                                                            onclick="disconnection('{{ route('logout') }}')">
                                                                            <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
                                                                            {{__("Logout")}}
                                                                        </a>
                                                                </div>
                                                            </span>
                                                        </div>
                                                        <p class="mb-1 fs-13 text-muted">
                                                             <strong>
                                                                <span class="border-right m-r-2">
                                                                    <i class="fs-11 fa fa-briefcase"></i>
                                                                    <span x-text="formatNumber(order.items.length)"></span>
                                                                    <span> x Item(s) </span>
                                                                </span>
                                                                <span class="m-r-2">
                                                                    <i class="fs-11 fa fa-money"></i>
                                                                    <span x-text="formatNumber(order.allTotal.total.value,currency)"></span>
                                                                </span>
                                                             </strong>
                                                        </p>
                                                        <template x-if="('error' in order)">
                                                            <small class="text-danger fs-10" x-text="order.error"></small>
                                                        </template>
                                                        <div>

                                                            <div class="float-left">
                                                                <div class="custom-control custom-switch cursor-pointer">
                                                                    <input type="checkbox"
                                                                           disabled
                                                                           :ckecked="(order.config.check_stock)"
                                                                           class="custom-control-input cursor-pointer"
                                                                           :id="'switch-displayed-order-draft-'+index">
                                                                    <label class="custom-control-label fs-13 cursor-pointer m-t-5"
                                                                           :for="'switch-displayed-order-draft-'+index">
                                                                        Check Stock
                                                                    </label>
                                                                </div>
                                                            </div>

                                                            <div class="float-right" >
                                                               <span x-data="draft_item_actions(index)">
                                                                    <button type="button"
                                                                            class="btn btn-default btn-sm fs-12"
                                                                            @click="displayDraftItem(index)">
                                                                        <i class="fa fa-eye fs-12"></i>
                                                                    </button>
                                                                    <button type="button"
                                                                            class="btn btn-primary btn-sm fs-12"
                                                                            @click="submitOrder">
                                                                        <i class="fa fa-send fs-12"></i>
                                                                    </button>
                                                                    <button type="button"
                                                                        class="btn btn-warning btn-sm fs-12"
                                                                        @click="printOrder">
                                                                        <i class="fa fa-print fs-12"></i>
                                                                    </button>
                                                               </span>
                                                                <button type="button"
                                                                        class="btn btn-dark btn-sm fs-12"
                                                                        @click="actions.openInCart">
                                                                    <i class="fa fa-luggage-cart fs-12"></i>
                                                                </button>
                                                                <button type="button"
                                                                        class="btn btn-danger btn-sm fs-12"
                                                                        @click="$store.draft.remove(index)">
                                                                    <i class="fa fa-trash fs-12"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </template>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>



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



@push("js")
    <script>
        document.addEventListener('alpine:init', () => {

            Alpine.data("displayed_draft_item", ()=>({

                visible : false,
                displayed_order : null,
                displayed_index : null,

                displayDraftItem(index){
                    const item = this.$store.draft.orders.find((item,i)=> i === index)
                    if(item){
                        this.displayed_order = this.$store.draft.orders.find((item,i)=> i === index);
                        this.displayed_index = index;
                     }
                     this.visible= true;
                },
                closeDraftItem(index){
                    this.displayed_order = null ;
                    this.displayed_index = null ;
                    this.visible= false;
                },
            }));

            Alpine.data("draft_item", (index = null)=> ({

                item : {},
                displayed : false,
                init(){
                    const component = this;
                    component.item = this.$store.draft.orders.find((item,i)=> i === index)
                    component.$watch('displayed', (value) => {

                        if(value){
                            this.$store.draft.setOrderDisplayed(index)
                        }else{
                            this.$store.draft.setOrderDisplayed(null)
                        }
                    })
                },

                get d (){

                },

                actions : {
                    submit () {
                        return  this.$store.cart.submitOrder(this.item);
                    },
                    openInCart () {
                        this.$store.cart.setCart(this.item);
                        $('#tab-cart').tab('show');
                    },

                    print () {
                        this.$store.cart.setCart(this.item);
                        $('#tab-cart').tab('show');
                    },

                    view () {
                        this.$store.draft.setOrderDisplayed(index)
                    },
                },
            }))
            Alpine.store('draft',{

                orders : JSON.parse(localStorage.getItem("ORDERS_DRAFT")) ?? [],

                order_displayed : null,

                get count (){
                    return this.orders.length;
                },

                add(order){
                    const orders = this.orders;
                    // order.id = orders.length + 1;
                    orders.push(order);
                    this.setOrders(orders);
                    const count = formatNumber(orders.length)
                    toast({title : "<span class='fs-13 m-b-1 text-uppercase'> " + count +" x order(s) in draft </span>"});
                },

                setOrderDisplayed(index){
                    const order = this.orders.find((item,i) => i === index)

                    if(order){
                        this.order_displayed = index;
                    }else {
                        this.order_displayed = null;
                    }

                },

                remove(index){
                    const orders = this.orders;
                    // order.id = orders.length + 1;
                    this.setOrders(orders.filter( (order,i) => i !== index));

                    const count = this.count;
                    toast({title : "<span class='fs-14'> 1 x Order was removed in draft.</span>"})
                },
                setOrders (orders){
                    if(orders) {
                        orders.forEach((order,i) => order.id = ++i)
                    }
                    localStorage.setItem("ORDERS_DRAFT",JSON.stringify(orders))
                    this.orders = orders
                },

                reset : () => this.setOrders([]),

            });

            Alpine.data("draft_item_actions",(index)=>({

                order : null ,
                init (){
                    const component = this;
                    component.order= this.$store.draft.orders.find((item,i)=> i === index)
                },

                printOrder(bloc_id="bloc-display-order",title = ""){
                    printHtmlBlock(bloc_id)
                },

                submitOrder ( params = {}){
                    const {customer} = this.order;
                    let options = {
                        onSuccess : () => {},
                        title : "{{__("Submit this order for ")}}"+customer.full_name+" ?",
                    };
                    const component = this;

                    options = {...options , ...params};

                    const {title} = options

                    return confirmAction({
                        text : title,
                        preConfirm : () => {
                            swal.fire({
                                text: '{{__("Do not close this popup !")}}',
                                icon: 'info',
                                showConfirmButton : false,
                                reverseButtons : true,
                                allowOutsideClick : false,
                                didOpen (){
                                    swal.showLoading();
                                    component.sendOrder();
                                },
                                willClose (){
                                    swal.showLoading();
                                },
                            })

                        },
                        didClose () {

                        }
                    });
                },

                async sendOrder(params = {}){
                    let options = {
                        onSuccess : () => {
                            alpine.$store.draft.remove(index);
                        },
                        onFailed : () => {},
                    };
                    const alpine = this;

                    const order = alpine.item;

                    const customer = order.customer;

                    options = {...options , ...params};

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

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

                    const body = {order , customer}

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

                },

            }));
        });
    </script>
@endpush
