

<?php $__env->startPush('js'); ?>
    <script >

        var currency = '<?php echo e(getSettingsOf("currency")); ?>';

        const $nav_sales = $("#block-card-sales").find('nav.nav button[data-toggle="tab"]');

        const showOffcanvasBottom = (visible)=>{
            return showOffcanvas('offcanvasBottom',visible)
        }

        $(function () {
            $nav_sales.find("button[data-target='#tab-content-cart']").tab("show");
            // $nav_sales.eq(0).tab("show");

        })

        const initAssets = ()=>{
            $('[data-toggle="tooltip"]').tooltip({html:true,});
            $('[data-toggle="popover"]').popover({html:true,});
        }
        const OrderService =  ( args = {} ) => new class {
           // return {

                data = ('data' in args) ? args.data : {};

                submit_url = ('submit_url' in args) ? args.submit_url : "<?php echo e(route("admin.orders.store")); ?>";
                order = ('order' in args) ? args.order : null;
                displayMessageOnfailed = ('displayMessageOnFailed' in args) ? args.displayMessageOnFailed : true;
                displayMessageOnCompleted = ('displayMessageOnCompleted' in args) ? args.displayMessageOnCompleted : true;

                onSuccess (response,callback){
                    if (!callback) callback = (res) => { };
                    callback(response);
                }
                onCompleted (response,callback){
                    if (!callback) callback = (res)=> { };
                    callback(response);
                }
                onFailed (response,callback){
                    if (!callback) callback = (res) => { };
                    callback(response);
                }
                onError (error,callback){
                    if (!callback) callback = (err) => { };
                    callback(error);
                }

                onDisconnected (response,callback){
                    if (!callback) callback = (err) => { };
                    callback(response);
                }

                sendWithConfirmDialog (dialog_options = {}){
                    const that = this;
                    const default_options = {
                        title : "<?php echo e(__("Confirmation")); ?>",
                        text : "<?php echo e(__("Submit this Order ?")); ?>",
                    }
                    dialog_options = {...default_options , ...dialog_options};
                    const {title,text} = dialog_options;
                    return confirmAction({
                        title,
                        text,
                        preConfirm : () => {
                            swal.fire({
                                text: '<?php echo e(__("Do not close this popup !")); ?>',
                                icon: 'info',
                                showConfirmButton : false,
                                reverseButtons : true,
                                allowOutsideClick : false,
                                didOpen (){
                                    swal.showLoading();
                                    that.sendOrder();
                                },
                                willClose (){
                                    swal.hideLoading();
                                },
                            })

                        },
                    });

                }

                async sendOrder(){
                    const body = this.data

                    
                    if (isOnline()){

                        const response = await  request(this.submit_url,{ body, method:"post"},false)
                                                .catch (error => {
                                                    this.onError(error);
                                                    if (this.displayMessageOnfailed){
                                                        swal.showValidationMessage(`${error}`)
                                                        swal.hideLoading();
                                                        swal.enableButtons()
                                                    }
                                                });
                        const success = response?.success ?? false;
                        if(success){
                            this.onSuccess(response)
                        }else{
                            this.onFailed(response)
                        }

                        if (this.displayMessageOnCompleted){
                            swal.fire({
                                icon : success ? "success" : "error",
                                title : success ? "<?php echo e(__('Order Submitted')); ?>" : "Oops..." ,
                                html : "<span class='fs-14'>"+response.message+"</span>" ,
                                showConfirmButton : true,
                            });
                        }
                        this.onCompleted(response);
                         return response ;
                    }else{
                        this.onDisconnected({
                            code : "DISCONNECTED",
                            message : "<?php echo e(__('Internet not available.')); ?>"
                        });
                    }

                }
           // }
        };

        $("#sidebarToggle").trigger('click');

        const randomSystemCssVarColor =  ()=>{
            const bg_colors = [
                "blue",'green','red',"orange",
                "yellow","pink","purple","teal","cyan","indigo"
            ];
            return  randomValue(bg_colors)
        };

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

            Alpine.data('customer_show', (customer)=>({
                customer : null,

                init(){
                    this.customer = customer;

                    if (this.customer && !('fancy_image' in this.customer)){
                        this.customer.fancy_image = "bg-"+randomSystemCssVarColor()
                    }
                },
                get initials() {
                    if (this.customer){
                        const {first_name, last_name} = this.customer
                        if (!last_name) return first_name.charAt(0).toUpperCase()
                        return `${first_name.charAt(0).toUpperCase()}${last_name.charAt(0).toUpperCase()}`
                    }
                    return "--";
                }
            }));

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

                async init (){
                    // localStorage.setItem("CUSTOMERS_LIST",JSON.stringify(allCustomers))
                    //JSON.parse(localStorage.getItem("CUSTOMERS_LIST")) ?? []
                    //await this.refresh()
                    // const alpine = this;

                    //alpine.$watch( (value) => this.setCustomer())
                },


                search : "",
                active : false,
                get customers(){
                    const online_customers = this.$store.data_page?.customers ?? [];

                    return [...this.new_customers, ...online_customers]
                },

                get new_customers(){
                    return JSON.parse(localStorage.getItem("NEW_CUSTOMERS")) ?? [];
                },

                get filteredCustomers (){
                    const search = this.search.toLowerCase();

                    if(search && filled(this.customers)){
                        const customers = [];
                     return  this.customers.filter(
                                    customer => (
                                        customer.first_name.toLowerCase().startsWith(search) ||
                                        customer.last_name.toLowerCase().startsWith(search)
                                        // (filled(customer?.phone) && customer.phone.toLowerCase().startsWith(search))
                                        // customer?.phone?.includes(search)
                                        // customer.email.toLowerCase().includes(search) ||
                                        //customer.full_name.toLowerCase().includes(search)
                                    )
                                );



                    }
                    return this.customers;

                },

                addNewCustomer(customer){
                    const new_customers = this.new_customers;
                    new_customers.push(customer);
                    localStorage.setItem("NEW_CUSTOMERS",JSON.stringify(new_customers));
                    return this.new_customers;
                },

                selectCustomer(customer) {
                    this.$dispatch('cart.order.customer.selected', customer)
                    //document.dispatchEvent(new CustomEvent('cart.customer.added', { detail : customer}));
                    this.active = false;
                },

                addCustomer (){
                    const that = this;

                    const editor =  DataTableEditor( {
                        fields: [
                            {
                                label: "<?php echo e(__('First Name')); ?> * : ",
                                name: "first_name" ,
                                type: "text",
                                def: this.search,
                                attr : {  },
                            },
                            {
                                label: "<?php echo e(__('Last Name')); ?> : ",
                                name: "last_name" ,
                                type: "text",
                            },
                            {
                                label: "<?php echo e(__('Phone Number')); ?> : ",
                                name: "phone" ,
                                type: "text",
                                // def :  "2376",
                                attr : {  type:"number", required : true, placeholder : "Ex: 237683523318" },
                            },
                            {
                                label: "<?php echo e(__('Email')); ?> : ",
                                name: "email" ,
                                type: "text",
                            },

                        ],
                    } );

                    editor.create({
                        title : "<span class='fa fa-user-plus m-r-5'></span><?php echo e(__("Add Customer")); ?>",
                        message : "<small class='text-red fs-11 m-b-20'><?php echo e(__("(*) required fields")); ?></small>",
                        buttons: {
                            label: "<?php echo e(__("Add")); ?> <i class='fa fa-plus'></i>",
                            className : "btn-success",
                            fn : function (e) {
                                const first_name = this.field('first_name').get();
                                const last_name = this.field('last_name').get();
                                const phone = this.field('phone').get().toString();
                                const email = this.field('email').get();

                                const customer = {
                                    // id : ++alpine.customers.length,
                                    first_name,
                                    last_name,
                                    full_name : first_name + " " + last_name,
                                    email,
                                    phone,
                                    avatar : null,
                                    has_files : false,
                                    is_new : true,
                                }
                                let success = true;
                                let search = null

                                if (first_name === ""){
                                    this.field('first_name').error("<?php echo e(__('This field is required')); ?>");
                                    success = false;
                                }

                                if(email !== "" || phone !== ""){
                                    search = that.customers.filter( cus => {
                                        if (email !== "") return (cus.email === email);
                                        if (phone !== "") return (cus.phone === phone);
                                    });

                                    if (search.length){
                                        if (email !== ""){
                                            this.field('email').error("<?php echo e(__('This email already exist')); ?>");
                                        }
                                        if (phone !== ""){
                                            this.field('phone').error("<?php echo e(__('This phone already exist')); ?>");
                                        }
                                        success = false;
                                    }

                                }

                                if(!success){
                                    return ;
                                }
                                that.addNewCustomer(customer)
                                that.selectCustomer(customer);
                                that.active = false;
                                this.close();


                            },
                        },
                    })
                }
            }));

            Alpine.store("data_page",{

                async init (){
                    const that = this;
                    const time = 2000 * 60;
                    await that.refresh();
                    setInterval(async () => await that.refresh(), time)
                },

                async refresh (){
                    const that = this;
                    const body =  {};

                    // alert(that.$store.cart)

                    // if (that.$store.cart.warehouse){
                    //    body.warehouse_id =  that.$store.cart.warehouse.id;
                    // }
                    // if (that.$store.cart.billing_desk){
                    //     body.billing_desk_id =  that.$store.cart.billing_desk.id;
                    // }
                    const data = await request("<?php echo e(route("admin.orders.get-data-page")); ?>",{body},false);

                    if ( ('products' in data) && filled(data.products) )  that.products = data.products;
                    if ( ('customers' in data) && filled(data.customers) )  that.customers = data.customers;
                    if ( ('warehouses' in data) && filled(data.warehouses) )  that.warehouses = data.warehouses;
                    if ( ('billing_desks' in data) && filled(data.billing_desks))  that.billing_desks = data.billing_desks;
                    if ( ('stocks' in data) && filled(data.stocks) )  that.stocks = data.stocks;
                    if ( ('sales' in data) && filled(data.sales) )  that.sales = data.sales;
                    if ( ('payment_methods' in data) && filled(data.payment_methods.length) )  that.payment_methods = data.payment_methods;
                },
                products : null,
                customers : null,
                warehouses : null,
                sales : null,
                billing_desks : null,
                stocks :null,
                categories : null,
                payment_methods : null,
                admin : <?php echo json_encode($admin, 15, 512) ?>,

                
                
                
                
                
                
                
            })

            Alpine.data("order_details", (item = null,param = {})=>({

                init () {
                    const that = this;
                    if('storage' in param) that.storage = param.storage;
                    // if('editable' in param) this.editable = param.editable;

                    //if(!('ref' in item)) this.ref = this.$store.draft.generateNewReference();

                    that.admin = that.$store.data_page.admin;
                    if(!('config' in item)) {
                        this.config = {
                            payment_required : '<?php echo e(getSettingsOf("submit_order_with_payment_backend")); ?>',
                            error : null,
                            is_draft : false,
                            uses_order_setting : false,
                            is_offline : true,
                            status_code : null,
                            note : "",
                            new_payment : null,
                        }
                    }

                    if (item){
                        //that.order = {...that.order , ...item}
                        if('items' in item) that.items = item.items;
                        if('customer' in item) that.customer = item.customer;
                        if('config' in item) that.config = {...this.config , ...item.config};
                        if('items' in item) that.items = item.items;
                        if(('ref' in item)) that.ref = item.ref;
                        if(('billing_desk' in item)) that.billing_desk = item.billing_desk;
                        if(('warehouse' in item)) that.warehouse = item.warehouse;
                        if(('sync' in item)) that.sync = item.sync;
                        if(('response' in item)) that.response = item.response;
                        if(('payment_type_selected' in item)) that.payment_type_selected = item.payment_type_selected;
                    }

                    if(that.stored_in_cart){
                        document.addEventListener("cart.order.items.added", (e) => {
                            that.addItem(e.detail)
                        })

                        document.addEventListener("cart.order.customer.selected", (e) => {
                            that.setCustomer(e.detail)
                        });

                        document.addEventListener("cart.order.pos.selected", (e) => {
                            that.setBillingDesk(e.detail)
                        });

                        document.addEventListener("cart.order.warehouse.selected", (e) => {
                            that.setWarehouse(e.detail)
                        });

                        that.$nextTick(()=>{
                            $nav_sales.on('shown.bs.tab', function(e){
                                const $active_tab = $(e.target); // active tab
                                const id = $active_tab.attr("id");
                                //showOffcanvasBottom(( (id === "tab-cart") && (that.count > 0)))
                            });
                        })
                    }else{
                        document.addEventListener("cart.order.opened-from-draft", (e) => {
                            that.setOrder(e.detail)
                            $("#tab-draft").tab('hide')
                            $("#tab-cart").tab('show')
                        });
                    }

                },

                payment_types : [
                    {
                        name : "<?php echo e(__("Manual Payment")); ?>",
                        icon : "fa fa-money-bill",
                        desc : "fa fa-money-bill",
                        code : "manual-payment",
                        disabled : false,
                    },
                    // {
                    //     name : "Cash Payment",
                    //     icon : "fa fa-cash-register",
                    //     code : "cash-payment",
                    // },
                    {
                        name : "<?php echo e(__("Automatic Payment")); ?>",
                        icon : "fa fa-money-check",
                        code : "automatic-payment",
                        disabled : true,
                    }
                ],

                payment_type_selected : null,

                ref : null,
                customer : null,
                items :  [],
                config: null,

                storage : "cart",

                paymentMethods : [],
                paymentMethod : null,
                billing_desk : null,
                warehouse : null,
                admin : null,

                response : null,

                sync : {
                    success : false,
                    active : true,
                    date : null ,
                },
                get editable(){
                    return !this.ref_id && (this.config.is_draft || this.stored_in_cart)
                },
                get uses_automatic_payment(){
                    return (this.payment_type_selected === "automatic-payment")
                },
                get uses_cash_payment(){
                    return (this.payment_type_selected === "cash-payment")
                },
                get uses_manual_payment(){
                    return (this.payment_type_selected === "manual-payment")
                },

                get ref_id () {
                    return this.response?.order?.ref_id ?? null;
                },
                get synchronized () {
                    return this.sync.success;
                },
                get synchronizable () {
                    return this?.sync?.active;
                },
                get synchronisation_label () {
                    //A tanté la  synchronisation au moins 01 fois
                    if (this.response) {
                        if (this.synchronized) return "<?php echo e(__("Synchronized")); ?>";
                        if (!this.synchronized) return "<?php echo e(__("Not Synchronized")); ?>";
                    }
                    return "<?php echo e(__("Await Synchronization")); ?>"
                },

                get savable () {
                    return (!this.ref_id);
                },

                get order () {
                    return {
                        ref : this.ref,
                        items : this.items,
                        customer : this.customer,
                        allTotal : this.allTotal,
                        config : this.config ,
                        sync : this.sync ,
                        admin : this.admin ,
                        //synchronizable : this.synchronizable ,
                        // synchronized : this.synchronized ,
                        // ref_id : this.ref_id ,
                        response : this.response ,
                        payment_type_selected : this.payment_type_selected ,
                        billing_desk : this.billing_desk ,
                        warehouse : this.warehouse ,
                    }
                },

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

                get stored_in_cart (){
                    return (this.storage === "cart");
                },

                get allTotal (){

                    const {total,customer} = this;

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

                    const  discount = 0;

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

                    const result = {
                        sub_total : {
                            label: "Sub Total",
                            className: "fs-12",
                            value : total,
                            visible : total > 0,
                        },
                        tax  : {
                            label: "Tax",
                            className: "fs-12",
                            value :  arround(tax,2),
                            visible : tax > 0,
                        },
                        discount  : {
                            label: "<?php echo e(__("Discount")); ?>"+" ("+discount/100+"%)",
                            className: "fs-12 text-success",
                            value : arround(discount,2),
                            visible : discount > 0,
                            visible_if_less_zero : false,
                        },
                        total  : {
                            label: "Total",
                            className: "fs-13 text-success",
                            value : arround(cartTotal,2),
                            visible : cartTotal > 0,
                        },
                        balance : {
                            label: "<?php echo e(__("Balance")); ?>",
                            className: "fs-12 text-indigo",
                            value : arround(balance,2),
                            visible : balance > 0,
                        },
                    };

                    if (balance <= cartTotal){
                        net_amount = cartTotal - balance;
                    }else if ( balance > cartTotal){
                        net_amount = 0;
                    }
                    result.net_amount = {
                        label: "<?php echo e(__('Net Amount')); ?>",
                        className: "fs-14 text-red",
                        value : arround(net_amount,2),
                        visible : true,
                    }
                    return result;
                },

                get payable(){
                    const net_amount = this.allTotal.net_amount.value;
                   // const payment_required = this.order.config?.payment_required ?? false;
                    return (net_amount > 0);
                },

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

                get service () {
                    const that = this;
                    const order = that.order;
                    const {items, customer, config,billing_desk,allTotal,warehouse } = order;

                    const service =  OrderService({
                        data : {
                            order : {items , config,allTotal},
                            customer,
                            billing_desk_id : billing_desk?.id ?? null,
                            warehouse_id : warehouse?.id ?? null,
                        },

                        displayMessageOnfailed : false,
                        displayMessageOnCompleted : true ,
                    });

                    service.onDisconnected = (response)=> {
                        return that.saveOffline(false);
                    };


                    service.onCompleted = (response) => {
                        console.log("[submit-order] ==> completed")

                        const {success, message} = response

                        order.sync.success = response.success ?? false;
                        delete response.exception
                        order.response = response;
                        order.sync.date = moment().format("YYYY-MM-DD HH:ss:mm");

                        if (that.stored_in_cart){
                            if(success){
                                that.setItems([])
                                that.setCustomer(null)
                            }
                        }else{
                            that.setOrder(order);
                        }
                    };

                    service.onError = (error) => {
                        console.log("[submit-order] ==> error")
                        console.log(error)
                    }
                    service.onSuccess = (response) => {
                        console.log("[submit-order] ==> succes")
                        that.editor_order_settings.close()
                    }

                    return service;
                },

                get payment_fields(){
                    const that = this;
                    // const cart = that.$store.cart;

                    const order = that.order;
                    const customer = order?.customer ?? null;

                    const allTotal = order.allTotal;
                    const {net_amount} = allTotal;
                    let methods = that.$store.data_page.payment_methods;
                    const  payment_methods = methods.map(m => { return {label: m.name , value : m.id} });
                    const  payment_method_default = methods.find(m => m.code === "<?php echo e(\App\Models\PaymentManagement\PaymentMethod::CASH); ?>");

                    return [
                        {
                            label: "<?php echo e(__('Payment Method')); ?> * : ",
                            name: "payment_method_id" ,
                            type: "select",
                            options : payment_methods,
                            def : payment_method_default?.id ?? null,
                            attr : {  "data-plugin-multiselect":"",},
                        },
                        {
                            label: "<?php echo e(__('Reference')); ?> : ",
                            name: "provider_reference" ,
                            type: "text",
                            def: "",
                        },
                        {
                            label: "<?php echo e(__('Confirmation Reference')); ?> : ",
                            name: "provider_reference_confirmation" ,
                            compare : 'provider_reference',
                            type: "text",
                        },
                        {
                            label: "<?php echo e(__('Payer')); ?> : *",
                            name: "payer" ,
                            type: "text",
                            // options : users,
                            def : (filled(customer)) ? customer.full_name+" / "+customer.phone : "",
                            attr : {  "class":"text-white bg-success",readonly: true, disabled : true},
                        },
                        {
                            label: "<?php echo e(__('Payer Number')); ?> : ",
                            name: "payer_number" ,
                            type: "text",
                            def : (filled(customer)) ? customer.phone : "",
                        },
                        {
                            label: "<?php echo e(__('Paid At')); ?> : ",
                            name: "paid_at" ,
                            type: "datetime",
                            def : moment().format("DD-MM-YYYY"),
                            attr : {readonly:'true'}
                        },
                        {
                            label: "<?php echo e(__('Paid Amount')); ?> : ",
                            name: "paid_amount" ,
                            type: "text",
                            def: net_amount.value,
                            attr : { type:'number' },
                        },
                    ]
                },

                get setting_fields(){
                    const that = this;

                    let warehouses = that.$store.data_page?.warehouses ?? [];
                    let billing_desks= that.$store.data_page?.billing_desks ?? [] ;

                    if (warehouses) warehouses = warehouses.map( item => ({ label : item.name , value : item.id }) )
                    if (billing_desks) billing_desks = billing_desks.map( item => ({ label : item.name , value : item.id }) )

                    const default_status = that.$store.cart.content?.config?.status_code ?? "<?php echo e(\App\Models\SettingManagement\Status::UNPROCESSED); ?>";

                   // console.log("ssd = ",that.$store.data_page)
                    return  [
                        {
                            label: "<?php echo e(__('Status')); ?> : ",
                            name: "status_code" ,
                            type: "select",
                            options : <?php echo json_encode(get_values($statuses, 'name', "code")) ?>,
                            def : default_status,
                            attr : {  "data-plugin-multiselect":"",},
                            submit : false,
                            fieldInfo : "<?php echo e(__("Le status sous lequel la commande sera enregistrée")); ?>",
                        },
                        {
                            label: "<?php echo e(__('Note')); ?> : ",
                            name: "note" ,
                            
                            type: "textarea",
                            attr : {  rows: 3, cols : 3},
                            fieldInfo : "<?php echo e(__("Ajouter une note à la commande")); ?>",
                        },
                        {
                            label: "<?php echo e(__('Anti Date')); ?> : ",
                            name: "real_date" ,
                            type: "datetime",
                            def : moment().format("DD-MM-YYYY"),
                            attr : {readonly:'true'},
                            submit : false,
                            fieldInfo : "",
                        },
                        {
                            label: "<?php echo e(__('Billing Desk')); ?> : ",
                            name: "billing_desk_id" ,
                            type: "select",
                            options : billing_desks,
                            def : that.billing_desk?.id ?? null,
                            attr : {  "data-plugin-multiselects":"", "class" : "select2ss"},
                            submit : false,
                            fieldInfo : "<?php echo e(__("Bureau de facturation")); ?>",
                        },
                        {
                            label: "<?php echo e(__('Warehouse Of Stock')); ?> : ",
                            name: "warehouse_id" ,
                            type: "select",
                            options : warehouses,
                            def : that.warehouse?.id ?? null,
                            attr : {  "data-plugin-multiselects":"", "class" : "selects2"},
                            submit : false,
                            fieldInfo : "<?php echo e(__("Entrepôt das le quel le stock des produits sera débité")); ?>",
                        },
                        {
                            label: "<?php echo e(__('Filter prodcuts list after changes')); ?> : ",
                            name: "apply_filter" ,
                            type: "radio",
                            options : [
                                { label : "<?php echo e(__("Yes")); ?>" , value : 1},
                                { label : "<?php echo e(__("No")); ?>" , value : 0},
                            ],
                            def : 1,
                            submit : false,
                            fieldInfo : "<?php echo e(__("Determine si les produits doivent etre filtré en fonction de l'entrepot selectionné")); ?>",
                        },
                    ]
                },

                get editor_order_settings(){
                    const that = this;
                 //   console.log(that.setting_fields.concat(that.payment_fields))
                    return DataTableEditor( {
                                fields: that.payment_fields.concat(that.setting_fields),
                            } );
                },

                saveOrder () {
                    return this.submitOrder();
                },

                copyToDraft(){
                    const that = this;
                    const order = that.order;
                    return confirmAction({
                                text : "<?php echo e(__("Copy order of ")); ?>"+that.customer.full_name+" in draft?",
                                preConfirm : ()=>{

                                    order.config.is_draft = true;
                                    order.config.is_offline = false;
                                    if (order){
                                        that.$store.draft.add(order);
                                        that.setItems([])
                                         that.setCustomer(null)
                                    }
                                }
                            });
                },

                async payOrder(){
                    const that = this;
                    // const cart = that.$store.cart;
                    const order = that.order;
                    const customer = order.customer;

                    const allTotal = order.allTotal;
                    const {net_amount} = allTotal;
                    let methods = that.$store.data_page.payment_methods;
                    // let customers = that.$store.data_page.customers;

                    if(that.uses_manual_payment){
                        return that.submitOrder();
                    }
                    else if(that.uses_automatic_payment){

                        methods = methods.filter(m => m.code !== "<?php echo e(\App\Models\PaymentManagement\PaymentMethod::CASH); ?>")
                        const paymentMethod = methods.find(m=> m.code === "<?php echo e(\App\Models\PaymentManagement\PaymentMethod::MTN_MOMO_CMR); ?>");
                        // const paymentMethod = that.paymentMethod;

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

                        const Xpeedy_Widget = new XpeedyWidget({
                                                        theme : "swal",
                                                        init_url :"<?php echo e(route("gateway.payment.init")); ?>",
                                                        check_url :"<?php echo e(route("gateway.payment.check")); ?>",
                                                        paymentMethods : methods,

                                                        configs : {
                                                            paymentMethod,
                                                            amount : net_amount.value,
                                                            currency : "<?php echo e(getSettingsOf("currency")); ?>",
                                                            popup_options : {
                                                                cancelButtonColor: "var(--danger)",
                                                                confirmButtonColor: "var(--success)",
                                                            },
                                                            params : {  order , customer, },
                                                            onCompleted (response){
                                                                that.sendOrder(order)
                                                            },
                                                            onFailed (response){

                                                            },
                                                        }
                                                });
                        console.clear()
                        console.log(Xpeedy_Widget,paymentMethod);

                        if (!$.isEmptyObject(paymentMethod)) {
                            return await Xpeedy_Widget.init();
                        }
                    }
                },

                saveOffline(confirm = false){
                    const that = this;
                    const order = that.order;
                    order.config.is_offline = true;
                    order.config.is_draft = false;

                    const handleSave = () => {
                        that.$store.draft.add(order);
                        that.setItems([]);
                        that.setCustomer(null);
                    }

                    if (order){
                        if(confirm){
                            return confirmAction({
                                        text : "<?php echo e(__("Save offline order of ")); ?>"+that.customer.full_name+" ?",
                                        preConfirm : () => {
                                            handleSave();
                                        },
                                    });
                        }else{
                            handleSave();
                        }
                    }
                },

                submitOrder (){
                    const that = this;
                   // const service =  that.service;
                    const customer = that.customer;
                    const uses_manual_payment = (that.uses_manual_payment && that.config.payment_required);
                    let methods = that.$store.data_page.payment_methods;

                    const editor = that.editor_order_settings;

                    //  editor.field('qty').s.def = qty
                    //editor.s.ajax = qty
                    //editor.field('qty').set(qty)

                    const fields = editor.order(); // tous les champs du formulaire
                    editor.hide(fields)

                    const $DTE_Form_Error = $(".DTE_Form_Error");
                    const $DTE_Form_Buttons = $(".DTE_Form_Buttons button");

                    if(that.config.uses_order_setting){
                        editor.show(['status_code',"note"])
                    }
                    if(uses_manual_payment){
                       // affiche tous les champs liés au paiement
                        editor.show(that.payment_fields.map( f=> f.name) )
                      //  editor.hide(['payer_number','paid_at'])
                    }else{

                    }

                    editor.field('status_code').input().on('change',(e)=> {
                        that.setConfig({
                            status_code:  editor.field('status_code').val(),
                        });
                    });
                    editor.field('payment_method_id').input().on("change", (e)=>{
                        const method = methods.find( ({id}) => id.toString() === editor.field('payment_method_id').val().toString())
                        const fields = ['provider_reference','provider_reference_confirmation']
                        if(filled(method) && method.code !== '<?php echo e(\App\Models\PaymentManagement\PaymentMethod::CASH); ?>'){
                            editor.show(fields)
                        }else{
                            editor.hide(fields)
                        }
                        //console.log(method)
                    });

                  return   editor.create({
                                title : "<span class='fa fa-question-circle-o m-r-5 fs-20'></span> "+"<?php echo e(__("Confirmation")); ?>",
                                message : "<div class='text-center font-weight-bold fs-18 m-b-5'>"+"<?php echo e(__("Submit this order for ")); ?>"+customer.full_name+" ?</div>",
                                buttons: {
                                    label: "<?php echo e(__('Submit')); ?> <span class='fa fa-send-o m-l-2 fs-13s'></span>",
                                    className : "btn-success fs-13s",
                                    fn : async function (e) {
                                        $DTE_Form_Error.hide();

                                         that.setConfig({
                                            // status_code: this.field('status_code').val(),
                                             note : this.field('note').val()
                                         });

                                         if(uses_manual_payment){
                                             const provider_reference = this.field('provider_reference').val();
                                             const provider_reference_confirmation = this.field('provider_reference_confirmation').val();
                                             const paid_at = this.field('paid_at').val();
                                             const payer_number = this.field('payer_number').val().toString();
                                             const payment_method_id = this.field('payment_method_id').val().toString();
                                             // const remaining_amount = this.field('remaining_amount').get();
                                             const paid_amount = this.field('paid_amount').val();

                                             let method = methods.find( ({id}) => id.toString() === payment_method_id.toString());

                                             console.log(method)

                                             if(filled(method) && method.code !== '<?php echo e(\App\Models\PaymentManagement\PaymentMethod::CASH); ?>'){
                                                 if (provider_reference === ""){
                                                     return this.field('provider_reference')
                                                                .error('This field is required');
                                                 }
                                                 if(provider_reference_confirmation !== provider_reference){
                                                     return this.field('provider_reference')
                                                         .error('The provider_reference must same with confirmation field value');

                                                 }
                                             }

                                             that.setConfig({
                                                 new_payment : {
                                                     provider_reference ,
                                                     payment_method_id ,
                                                     payer_number ,
                                                     paid_at ,
                                                     paid_amount ,
                                                     // remaining_amount ,
                                                 }
                                             });

                                         }


                                        $(".DTE_Form_Error").show();
                                        $(".DTE_Form_Error").html("<div class='loader'></div>");

                                        $(".DTE_Form_Buttons button").attr("disabled","true");
                                        const response = await that.service.sendOrder()
                                                                          .catch (error => {
                                                                              $(".DTE_Form_Buttons button").removeAttr("disabled")
                                                                              $(".DTE_Form_Error").html(error)
                                                                          });

                                       // const response = {};

                                        const success = response?.success ?? false;
                                        const message = response?.message ?? "Internal Server Error";
                                        $(".DTE_Form_Buttons button").removeAttr("disabled");
                                       // $DTE_Form_Error.html('')
                                        if(success){
                                            this.close();
                                        }else{
                                            $(".DTE_Form_Error").html("<div class='fs-12'>"+message+"</div>")
                                        }

                                       // this.submit()

                                    },
                                },
                            } );


                    
                    
                    
                    
                },

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

                addItem(item){
                    const items = this.items;
                    const product = this.findItem(item);
                    if (product){
                        this.updateItem(product,{qty :  ++product.qty})
                        item = product
                    }else{
                        item.qty = 1;
                        items.push(item)
                    }
                    const message = formatNumber(item.qty)+" x "+ item.name+" added to cart.";
                    toast({title : "<span class='fs-13 m-b-1'> " + message.toUpperCase()+"</span>"})
                    this.setItems(items);
                },

                setOrder (o = null){
                    const order = (o) ? o : this.order;
                    if (this.stored_in_cart){
                        return this.$store.cart.setCart(order);
                    }
                    return this.$store.draft.updateOrder(order.ref,order);
                },

                setCustomer (customer){
                    this.customer = customer;
                    this.setOrder();
                },

                setBillingDesk (pos){
                    if (typeof pos !== "object"){
                        pos = this.$store.data_page.billing_desks.find( ({id}) => (id.toString() === pos.toString()))
                    }
                    this.billing_desk = pos;
                    this.setOrder();
                },

                setWarehouse (warehouse){
                    if (typeof warehouse !== "object"){
                        warehouse = this.$store.data_page.warehouses.find( ({id}) => (id.toString() === warehouse.toString()))
                    }
                    this.warehouse = warehouse;
                    this.setOrder();
                },
                setConfig (param = {}){
                    this.config = {...this.config, ...param};
                    this.setOrder()
                },

                setItems (items){
                    if(items) {
                        items.forEach(item => item.amount = item.price * item.qty);
                        this.items = items;
                        this.setOrder()
                    }
                },

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

                    const editor =  DataTableEditor( {
                                        fields: [
                                            {
                                                label: "<?php echo e(__('New Qty')); ?> : ",
                                                name: "qty" ,
                                                type: "text",
                                                def: qty,
                                                attr : {  type : "number" },
                                            },

                                        ],
                                    } );


                    const message = formatNumber(qty)+" x "+item.name.toUpperCase();

                    editor.bubble( td,["qty"], {
                        // title : this.order.ref,
                        message,
                        buttons: {
                            label: '<?php echo e(__("OK")); ?>',
                            className : "btn-success fs-12",
                            fn : function (e) {
                                const new_qty = parseFloat(this.field('qty').get());

                                if(new_qty > 0){
                                    that.updateItem(item,{qty : new_qty})
                                    this.close();
                                }else{
                                    this.field('qty').error("<?php echo e(__('This value is invalid.')); ?>");
                                }
                                // $(".DTE_Form_Error").css("display","none")
                            },
                        },
                    } );

                },

                updateItem (item, data = {}) {
                    let items = [];
                    if (typeof item === 'object' && ('id' in item)){
                        item = item.id;
                    }
                    for (let i = 0; i < this.count; i++) {
                        let cart_item = this.items[i];
                        if (cart_item.id === item) {
                            cart_item = {...cart_item  , ...data};
                        }
                        items.push(cart_item)
                    }

                    // items.forEach( cart_item => {
                    //     if (cart_item.id === item) {
                    //         cart_item = {...cart_item  , ...data};
                    //         // return ;
                    //     }
                    // })

                    this.setItems(items);
                },

                remove () {
                    this.setItems([])
                },

                deleteItem (item){
                    if(item){
                        const items = this.items.filter(({id}) => item.id !== id);
                        this.setItems(items);
                    }
                },

                changeOrderSetting($el,param = {}) {
                    const that = this;

                    const fields = param.fields ?? [];
                    const message = param?.message ?? "";
                    const mode = param?.mode ?? "set-billing-desk";


                    if (fields && $el){
                        const editor = that.editor_order_settings;

                      //  editor.field('qty').s.def = qty
                        //editor.s.ajax = qty
                        //editor.field('qty').set(qty)

                        editor.bubble( $el,fields, {
                            message,
                            buttons: {
                                label: '<?php echo e(__("OK")); ?>',
                                className : "btn-success fs-13",
                                fn : function (e) {
                                    if (mode === "set-billing-desk"){
                                        that.setBillingDesk(this.field('billing_desk_id').get());
                                    }
                                    if (mode === "set-warehouse"){
                                        that.setWarehouse(this.field('warehouse_id').get());
                                    }
                                    this.close();
                                },
                            },
                        } );
                    }
                },
            }));

            Alpine.store('draft',{

                init (){
                },

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

                order_displayed : {},

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

                get offline_orders (){
                    return this.orders.filter( order => order.config.is_offline);
                },
                get draft_orders (){
                    return this.orders.filter( order => order.config.is_draft);
                },

                get sales (){

                    const orders = this.offline_orders;
                    const orders_sync = orders.filter(o => ( (o.sync.active && o.sync.success) && o.response));
                    const orders_not_sync = orders.filter(o => ( (o.sync.active && !o.sync.success) && o.response));
                    const orders_await_sync = orders.filter(o => ( (o.sync.active) && !o.response));

                    return [
                        {
                            label: "Sync.",
                            className: "fs-12",
                            icon: "fa fa-check-circle",
                            color: "text-red",
                            card_style: "border: 2px solid var(--green); background: var(--green); color: var(--white)",
                            count : orders_sync.length,
                            amount : getSum(pluck(orders_sync,"items"),"amount"),
                        },
                        {
                            label: "Not Sync.",
                            className: "fs-12 text-success",
                            icon: "fa fa-ban",
                            color: "text-green",
                            card_style: "border: 2px solid var(--red); background: var(--red); color: var(--white)",
                            count : orders_not_sync.length,
                            amount : getSum(pluck(orders_not_sync,"items"),"amount"),
                        },
                        {
                            label: "Await Sync.",
                            className: "fs-13 text-success",
                            icon: "fa fa-clock-o",
                            card_style: "border: 2px solid var(--gray); background: var(--gray);color: var(--white)",
                            color: "text-muted",
                            count : orders_await_sync.length,
                            amount : getSum(pluck(orders_await_sync,"items"),"amount"),
                        },
                        {
                            label: "Total.",
                            className: "fs-13 text-success",
                            icon: "fa fa-money",
                            card_style: "border: 2px solid var(--orange); background: var(--orange);color: var(--white)",
                            color: "text-muted",
                            count : orders.length,
                            amount : getSum(pluck(orders,"items"),"amount"),
                        },
                    ];
                },

                generateNewReference(){
                        
                        
                        
                        
                        
                        
                    const ref = createRandomString(10,{letters : false});
                    const order = this.findOrder(ref)

                    if (order) return this.generateNewReference() ;
                    return ref;
                },

                findOrder(order){
                    const ref =  (typeof order === "object") ? order.ref : order;
                    return this.orders.find(order => order.ref === ref);
                },
                add(order){
                    // try {
                    const orders = this.orders;
                    const {is_draft , is_offline} = order.config;
                    if( !('ref' in order) || order.ref !== "" ){
                        order.ref = this.generateNewReference();
                    }
                    if( !('date' in order.config) ){
                        order.config.date = moment().format("<?php echo e(__('YYYY-MM-DD HH:mm:ss')); ?>");
                    }

                    order.sync.success = false;
                    order.sync.active = true;
                    orders.push(order);

                    this.setOrders(orders);
                    let count = this.orders.filter(o=>o.config.is_offline).length;
                    let message = formatNumber(count)+" x Offline Order(s)";

                    if(is_draft){
                        count = this.orders.filter(o=>o.config.is_draft).length;
                        message = formatNumber(count)+" x Order(s) in draft";
                    }

                    toast({title : "<span class='fs-13 m-b-1 text-uppercasep'> " + message +" </span>"});
                    // }
                    // catch (error) {
                    //     toast({
                    //         title : "<span class='fs-12 m-b-1 text-uppercasep'> " + error +" </span>",
                    //         timer : 10000 ,
                    //         icon : "error"
                    //     });
                    // }
                },

                remove(order,confirm = true){
                    let orders = [];
                    order = this.findOrder(order);

                    const that = this;

                    if(order) {
                        const {is_draft , is_offline} = order.config
                        let ref =   order.ref;
                        let text =   "Remove this order from Onffline Sales ?"
                        let message = "1 x Order was removed";
                        orders = this.offline_orders;
                        let count = this.offline_orders.length;

                        if(is_draft){
                            orders = this.draft_orders;
                            message = "1 x Order was removed in draft";
                            text =   "Remove this order from Draft ?"
                        }
                        count = orders;

                        const removeProcess = ()=>{
                            orders = orders.filter( (o) => ref !== o.ref);
                            that.setOrders(orders);
                            toast({title : "<span class='fs-13 m-b-1 text-uppercase'> " + message +" </span>"});
                        }

                        if(confirm){
                            return confirmAction({
                                        title : ref,
                                        text,
                                        preConfirm : () => {
                                            removeProcess();
                                        },
                                    });
                        }
                        return removeProcess();

                    }

                },

                setOrders (orders){
                    localStorage.setItem("ORDERS_DRAFT",JSON.stringify(orders))
                    this.orders = orders
                },

                updateOrder (ref, data) {
                    const orders = [];
                    const count = this.count;
                    if(filled(this.orders)){
                        for (let item of this.orders) {
                            if (item.ref === ref){
                                item = {...item , ...data};
                            }
                            orders.push(item)
                        }
                        this.setOrders(orders);
                    }

                },
                reset (){
                    return this.setOrders([]);
                },

            });

            Alpine.data('sales',(param={})=> ({

                async init (){
                    const that = this;

                    if ('storage' in param) that.storage = param.storage;

                    that.$nextTick(async () => {
                        await that.refreshOrders();
                        const $table = $("#"+that.table_id);

                        that.datatable.on("click","tbody tr td .btn-action-click",async (e)=>{
                           // const table  = $table.DataTable(); // <button></button>
                            const $button = $(e.target); // <button></button>
                            const $td = $button.closest("td"); // <td></td>
                            const  index = $td.index();  // l'index de la colonne [1]
                            const order = that.datatable.row($td).data(); // Les données de la ligne

                            if(index === 0){ // column 'id'
                              //  alert(that.table_id)
                                that.displayedOrder(order)
                            }

                            if(index === 3){ // column 'action'
                                that.$store.draft.remove(order);
                                await that.refreshOrders();
                            }
                        })

                        const time = 1000 * 60; // 1min
                        that.timer = setInterval(async () => await that.refreshOrders(), time)

                    })

                   // that.datatable()
                },
                destroy(){
                    clearInterval(this.timer)
                },
                orders : [],
                timer : null,
                storage: 'offline',

                table_id : param?.table_id ?? "table-sales",

                get is_online(){
                    return (this.storage === "online");
                },
                get is_offline(){
                    return (this.storage === "offline");
                },
                get is_draft(){
                    return (this.storage === "draft");
                },

                get table_options(){

                    const that =this;

                    const columns =  [
                        {
                            title : "#<?php echo e(__('ID')); ?>",
                            name : "order_ref",
                            width : "20%",
                            className : "right fs-12",
                            searchable: true,
                            orderable: false,
                            data : "ref_id",
                            render: function (data, type,rowData) {
                                // const order_id = (that.is_online) ? rowData.ref_id : rowData.ref;
                                // rowData = JSON.stringify(rowData)
                                if (type === 'display') {
                                    return `
                                    <span class="text-blue text-underline cursor-pointer btn-action-click">
                                        ${data}
                                    </span>
                                    `;
                                }
                                // console.log(`${rowData}`)
                                // console.log(rowData)
                                return data;
                            }
                        },
                        {
                            title : "<?php echo e(__('Customer')); ?>",
                            // width : "50%",
                            name : "order_customer",
                            className : "left fs-12",
                            searchable: true,
                            orderable: false,
                            data : "customer.full_name",

                        },
                        {
                            title : "<?php echo e(__('Total')); ?>",
                            name : "order_total",
                            width : "30%",
                            className : "right fs-12",
                            searchable: true,
                            orderable: false,
                            data : "total",
                            render: function (data, type) {
                                if (type === 'display') {
                                    return formatNumber(data,"<?php echo e(getSettingsOf("currency")); ?>");
                                }
                                return data;
                            }
                        }
                    ];
                    const options = {
                        serverSide : false,
                        processing : false,
                        lengthChange: false,
                        searching: true,
                        info: false,
                        ordering: true,
                        paging: true,
                        dom : "Bfrtilp",
                        responsive: true,
                        buttons : [
                            { extend: "export" },
                        ],
                    };
                    // ( async ()=> await that.refreshOrders())();
                    if (that.is_online){
                        
                       // options.buttons.unshift({extend: "reload"});
                      //  options.data = that.orders ?? [];
                        columns.push( {
                            title : "<?php echo e(__('Status')); ?>",
                            name : "status",
                            className : "left fs-12",
                            searchable: true,
                            data : "status.name",
                            // render: function (data, type,rowData) {
                            //     if (type === 'display') {
                            //        // convert html string into DOM
                            //
                            //         return (new DOMParser).parseFromString(data, "text/html").body.firstElementChild;
                            //     }
                            //     return data;
                            // }

                        },)
                        columns.push( {
                            title : "<?php echo e(__('Date')); ?>",
                            width : "20%",
                            name : "date",
                            className : "left fs-12",
                            searchable: true,
                            data : "created_at",
                        },)
                    }else{
                        columns[0].data = 'ref';
                        columns[2].data = 'allTotal.total.value';
                        options.data = that.offline_sales;

                        if (that.is_draft){
                            options.data = that.draft_sales;
                        }else{
                            columns.push( {
                                title : "<?php echo e(__('Sync.')); ?>",
                                //width : "20%",
                                name : "sync",
                                className : "left fs-12 text-red",
                                searchable: false,
                                data : "response.message",
                            },)
                        }

                        columns.push( {
                            title : "<?php echo e(__('Action')); ?>",
                            width : "10%",
                            name : "action",
                            className : "center fs-12",
                            searchable: false,
                            data : null,
                            render: function (data, type,e) {
                                if (type === 'display') {
                                    return '<span  class="fs-12 fa fa-trash cursor-pointer btn-action-click text-red"></span>';
                                }
                                return data;
                            }

                        },)
                    }
                    options.columns = columns;
                    return options

                },

                get offline_sales(){
                  return this.$store.draft?.offline_orders ?? []
                },
                get draft_sales(){
                    return this.$store.draft?.draft_orders ?? []
                },

                get statistics(){
                  const count = this.orders.length
                  let sales = getSum(this.orders,"total")

                    if (!this.is_online){
                        sales = pluck(this.orders,"allTotal");
                        sales = pluck(sales,"total");
                        sales = getSum(sales,"value");
                    }
                  let customers_orders = pluck(this.orders,"customer");
                  let customers = []
                  if (customers_orders) {
                      const unique_Id = customers_orders.map((item) => item.id)
                                                .filter((value, index, self) => self.indexOf(value) === index);

                      unique_Id.forEach( id => {
                           const customer = customers_orders.find(c => c.id === id)
                          if (customer) {
                              customers.push(customer)
                          }
                      })
                  }


                    return {
                          sales : {
                              label : "Total",
                              value : formatNumber(arround(sales,2),currency),
                              icon : "fa fa-money",
                              card_style : "background : var(--green); color: var(--white)",
                          } ,
                        order_count : {
                            label : "Orders Count",
                            value : formatNumber(count),
                            icon : "fa fa-luggage-cart",
                            style : "background : var(--yellow); color: #222",
                        },
                        customers : {
                            label : "Customers",
                            value : formatNumber(customers.length),
                            icon : "fa fa-user-circle-o",
                            style : "background : var(--indigo); color: var(--white)",
                        },

                    }
                },

               async refreshOrders(){
                   let orders =  this.offline_sales;
                   const datatable =  this.datatable;
                   if(this.is_online){
                       const body =  {};
                       const response = await request("<?php echo e(route("admin.orders.get-sales")); ?>",{body},false)
                       orders = response?.data ?? [];
                   }
                   else if (this.is_draft){
                       orders = this.draft_sales
                   }
                   this.orders = orders;
                   datatable.clear();
                   datatable.rows.add(this.orders);
                   datatable.draw(false);
                },


               get datatable(){
                    let table_id = this.table_id;
                    return  ($.fn.dataTable.isDataTable('#'+table_id))
                            ? $("#"+table_id).DataTable()
                            : new DataTable("#"+table_id,this.table_options)
                },

                displayedOrder(order){
                    order.reference = order?.ref ?? order.ref_id;
                    order.is_online = this.is_online

                    if (!order.is_online){
                        const allTotal = order.allTotal
                        order.subtotal = allTotal?.sub_total?.value ?? 0;
                        order.discount = allTotal?.discount?.value ?? 0;
                        order.tax      = allTotal?.tax?.value ?? 0;
                        order.shipping = allTotal?.shipping?.value ?? 0;
                        order.total    = allTotal?.total?.value ?? 0;
                    }
                    this.$store.invoice.open(order,order.is_online);
                    showOffcanvas("offcanvas-displayed-invoice",true)
                }
            }))


        })
    </script>
<?php $__env->stopPush(); ?>
<?php /**PATH /home/lekruu/public_html/resources/views/backend/orders/create/script-alpine-js.blade.php ENDPATH**/ ?>