<script type="text/javascript">
    function zamanPlaceCollectionOrder(orderId, customerName, customerPhone, collectionTime, convertTo, changePriceTo) {
        $('#placeOrderTypeBlock').hide();
        zamanEposPopupcloser();
        clearEposWorkArea();
        clearEposWorkAreaForOrderList();
        $('#categoryBreadcurm').show();
        $('#eposCategoryMenuList').show();
        $('#categoryBreadcurm').show();
        $('.breadcurmb-category').text('<?php echo sprintf($this->lang->line('placing_order_head'), $this->lang->line('collection')) ?>');
        $('.breadcurmb-menu').show().text('');
        var html = `
         <form id="collectionOrderInfoCollectForm">
            <div class="neworder-waiting ">
                <div class="neworder-table-number collection-customer" style="width:40%">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('name') ?></label>
                        <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="name" id="collectionCustomerName" data-error="#collectionCustomeNameErrorPlaceHolder" class="form-control text-capitalize" placeholder="<?php echo $this->lang->line('name') ?>" autocomplete="off">
                        <input type="hidden" id="collectionOrderId">
                        <input type="hidden" id="existingCollectionCustomerName">
                        <input type="hidden" id="isConvertedToCollection">
                        <input type="hidden" id="isConvertedToCollectionPrice">
                    </div>
                    <div id="collectionCustomeNameErrorPlaceHolder"></div>
                    <div class="clearfix"></div>
                </div>          
                <div class="neworder-table-guest collection-phone" style="width:35%">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('phone') ?></label>
                        <input type="text" onfocus="ShowPhonePad()" name="phone" id="collectionCustomerPhone" data-error="#collectionCustomePhoneErrorPlaceHolder" class="form-control" placeholder="<?php echo $this->lang->line('phone') ?>">
                        <input type="hidden" id="existingCollectionCustomerPhone">
                    </div>
                 <div id="collectionCustomePhoneErrorPlaceHolder"></div>
                </div>         
                <div class="neworder-table-guest collection-time" style="width:25%">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('time') ?></label>
                        <input type="text" name="delivery_time" id="collectionDeliveryTime" class="form-control" placeholder="<?php echo $this->lang->line('time') ?>">
                        <input type="hidden" id="existingCollectionDeliveryTime">
                    </div>
                </div>            
            </div>
            <div class="clearfix"></div>
            <div class="clearfix"></div>
             <div class="tab-group config-submit" style="padding:0px 10px">
                <button type="submit" onclick="initiateCollectionOrder('collectionOrderInfoCollectForm')"><span class="icon icon-folder"></span>&nbsp;<?php echo $this->lang->line('go') ?></button>
            </div>
            <div style="padding:3px 10px; display:none;" class="commonPhonePadForCustomer">
                <div style="border-radius:3px;"> 
                    <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key" style="background:none;padding:0px;"><?php echo $this->lang->line('phone_pad') ?></div>            
                    </div>
                   <div class="tab-group keypad">                     
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">1</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">2</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">3</div>  
                   </div>
                    <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">4</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">5</div> 
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">6</div>
                    </div>            
                   <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">7</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">8</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">9</div>                      
                   </div> 
                    <div class="tab-group keypad">
                        <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryActionKey">DEL</div>                        
                        <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryNumKey">0</div>
                        <div class="tab-item zaman-epos-nav quantity-digit keypad-key collectionStaticPrimaryActionKey">CLR</div>        
                    </div>         
                </div>                         
            </div>                                   
        </form>`;
        $('#eposCategoryMenuList').html(html);
        var userData = zamanEposCart.getUserData();
        var userApps = userData.userApps;
        var preveleges = userApps.length;
        if (preveleges > 1) {
            playBeepSound();
        }
        $('#collectionDeliveryTime').datetimepicker({
            datepicker: false,
            format: 'g:i A',
            formatTime: 'g:i A',
            MinTime: '5:00 PM',
            MaxTime: '11:59 PM',
            step: 30
        });
        if (orderId > 0) {
            $('#collectionOrderId').val(orderId);
            $('#collectionCustomerName').val(customerName);
            $('#existingCollectionCustomerName').val(customerName);
            $('#collectionCustomerPhone').val(customerPhone);
            $('#existingCollectionCustomerPhone').val(customerPhone);
            $('#collectionDeliveryTime').val(collectionTime);
            $('#existingCollectionDeliveryTime').val(collectionTime);
            $('#isConvertedToCollection').val(convertTo);
            $('#isConvertedToCollectionPrice').val(changePriceTo);
        } else {
            $('#collectionCustomerName').val(customerName);
            $('#collectionCustomerPhone').val(customerPhone);
            if (!$.trim($('#collectionDeliveryTime').val())) {
                zamanEposDb.epos_configuration.get('default_time_collection').then(function (collectionTime) {
                    var collectionTimeObj = new Date();
                    collectionTimeObj.setMinutes(collectionTimeObj.getMinutes() + Number(collectionTime.value));
                    var result = collectionTimeObj.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
                    //$('#collectionDeliveryTime').val(result);
                    $('#collectionDeliveryTime').val('');
                });
            } else {
                $('#collectionDeliveryTime').val(collectionTime);
            }
        }
        zamanPrimaryNumpad('collectionCustomerPhone', 'collectionStaticPrimaryNumKey', 'collectionStaticPrimaryActionKey');
    }
    function initiateCollectionOrder(formId) {
        $('#' + formId).validate({
            submitHandler: function () {
                var collectionCustomerName = $('#collectionCustomerName').val();
                var collectionCustomerPhone = $('#collectionCustomerPhone').val();
                var collectionDeliveryTime = $('#collectionDeliveryTime').val();
                checkAndSubmitCollectionInfo(collectionCustomerName, collectionCustomerPhone, collectionDeliveryTime);
            },
            errorClass: "has-error",
            highlight: function (e) {
                $(e).closest('.form-group').addClass('has-error');
                $.colorbox.resize();
            },
            unhighlight: function (e) {
                $(e).closest('.form-group').removeClass('has-error');
                $.colorbox.resize();
            },
            rules: {
                name: {required: true},
                phone: {number: true}
            },
            messages: {name: 'Customer name is required', phone: 'Customer phone is required'},
            errorPlacement: function (error, element) {
                errorPlacement(error, element);
            }
        });
    }
    function checkAndSubmitCollectionInfo(barCustomerName, barCustomerPhone, collectionTime) {
        var customerData = {
            name: barCustomerName,
            phone: barCustomerPhone,
            collectionTime: collectionTime
        };
        var existingBarCustomerName = $('#existingCollectionCustomerName').val();
        var existingBarCustomerPhone = $('#existingCollectionCustomerPhone').val();
        var existingCollectionDeliveryTime = $('#existingCollectionDeliveryTime').val();
        var existingBarOrderId = Number($('#collectionOrderId').val());
        if (existingBarOrderId > 0) {
            var isConvertedToCollection = $('#isConvertedToCollection').val();
            var isConvertedToCollectionPrice = $('#isConvertedToCollectionPrice').val();
            if (isConvertedToCollection === 'yes') {
                eposConvertToCollection(Number(existingBarOrderId), isConvertedToCollection, isConvertedToCollectionPrice, customerData);
                window.setTimeout(function () {
                    zamanEposDb.epos_order.get({orderId: Number(existingBarOrderId)}).then(function (anOrder) {
                        if (anOrder.type === 'collection') {
                            eposPostUpdateOnConvertToCollection(Number(existingBarOrderId), customerData);
                        }
                    });
                }, 300);
            } else {
                updateCollectionOrderInfo(Number(existingBarOrderId), existingBarCustomerName, existingBarCustomerPhone, existingCollectionDeliveryTime, customerData);
            }
        } else {
            zamanEposDb.epos_customer.get({phone: barCustomerPhone}).then(function (aCustomer) {
                if (typeof (aCustomer) !== 'undefined') {
                    saveEposOrder(customerData, 'collection');
                } else {
                    if ($.trim(customerData.phone)) {
                        zamanEposDb.epos_customer.add(customerData).then(function (theCustomer) {
                            if (theCustomer > 0) {
                                saveEposOrder(customerData, 'collection');
                            }
                        });
                    } else {
                        saveEposOrder(customerData, 'collection');
                    }
                }
            });
        }
    }
    function  updateCollectionOrderInfo(existingBarOrderId, existingBarCustomerName, existingBarCustomerPhone, existingCollectionDeliveryTime, customerData) {
        var cart = zamanEposCart.listCart();
        if ((customerData.name).toLowerCase() === existingBarCustomerName.toLowerCase() && customerData.phone === existingBarCustomerPhone && customerData.collectionTime === existingCollectionDeliveryTime) {
            zamanEposDb.epos_order.get({orderId: Number(existingBarOrderId)}).then(function (theOrderNow) {
                manageOrderListDisplay(theOrderNow, true);
            });
        } else {
            zamanEposDb.epos_customer.get({phone: existingBarCustomerPhone}).then(function (aCustomer) {
                if (typeof (aCustomer) !== 'undefined') {
                    zamanEposDb.epos_order.where("orderId").equals(existingBarOrderId).modify({
                        orderInfo: customerData
                    }).then(function () {
                        eposLoadOrder(existingBarOrderId, 'yes');
                    }).then(function () {
                        if (cart.length > 0) {
                            resentCart(existingBarOrderId, cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                        }
                    });
                } else {
                    zamanEposDb.epos_order.where("orderId").equals(existingBarOrderId).modify({
                        orderInfo: customerData
                    }).then(function () {
                        eposLoadOrder(existingBarOrderId, 'yes');
                    }).then(function () {
                        if (cart.length > 0) {
                            resentCart(existingBarOrderId, cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                        }
                    });
                }
            });
        }
    }

    function eposConvertToCollection(orderId, isConvertedTo, isConvertedToPrice, orderInfo) {
        console.log(isConvertedTo, isConvertedToPrice);
        zamanEposDb.transaction('rw', [zamanEposDb.epos_branch,zamanEposDb.epos_order, zamanEposDb.epos_discountplan, zamanEposDb.epos_discountmulti, zamanEposDb.epos_discountitem, zamanEposDb.epos_table, zamanEposDb.epos_menucategory, zamanEposDb.epos_menu, zamanEposDb.epos_menuselection], function () {
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                if (theOrder.type === 'table') {
                    zamanEposDb.epos_table.where("tableNumber").equals(theOrder.orderInfo.tableNumber).modify({
                        status: '2'
                    });
                }
            }).then(function () {
                zamanEposDb.epos_order.where("orderId").equals(orderId).modify({
                    type: 'collection'
                });
            }).then(function () {
                if (isConvertedTo === 'yes' && isConvertedToPrice === 'out') {
                    zamanEposCart.changeToOutPrice();
                }
                zamanEposCart.resetOnConvert();
                zamanEposCart.setOnConvert();
            }).then(function () {
                var cartCalculator = zamanEposCart.cartCalculator();
                zamanEposDb.epos_order.where("orderId").equals(orderId).modify({
                    orderInfo: orderInfo,
                    cart: zamanEposCart.listCart(),
                    subTotal: cartCalculator.cartSubtotal,
                    tax: cartCalculator.cartTaxTotal,
                    serviceCharge: cartCalculator.serviceCharge,
                    deliveryCharge: cartCalculator.deliveryCharge,
                    ccFee: cartCalculator.cartccFee,
                    discount: cartCalculator.specialDiscount,
                    promo: cartCalculator.cartPromoDiscountAmount,
                    multiDiscount: cartCalculator.cartMultiDiscountAmount,
                    grandTotal: cartCalculator.Total
                });
            });
        }).then(function () {
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                manageOrderListDisplay(theOrder, true);
            });
        });
    }
    function eposPostUpdateOnConvertToCollection(orderId, orderInfo) {
        var cartCalculator = zamanEposCart.cartCalculator();
        zamanEposDb.epos_order.where("orderId").equals(orderId).modify({
            orderInfo: orderInfo,
            cart: zamanEposCart.listCart(),
            subTotal: cartCalculator.cartSubtotal,
            tax: cartCalculator.cartTaxTotal,
            serviceCharge: cartCalculator.serviceCharge,
            deliveryCharge: cartCalculator.deliveryCharge,
            ccFee: cartCalculator.cartccFee,
            discount: cartCalculator.specialDiscount,
            promo: cartCalculator.cartPromoDiscountAmount,
            multiDiscount: cartCalculator.cartMultiDiscountAmount,
            grandTotal: cartCalculator.Total
        }).then(function () {
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                if (theOrder.status >= 2 && checkInternetConnection()) {
                    $.ajax('<?php echo site_url('api/epos_order') ?>', {
                        type: 'post',
                        dataType: 'json',
                        data: {
                            theOrder: theOrder,
                            type: '2',
                            sent: '2',
                            additionals: 'Ref ' + theOrder.sid + '/' + theOrder.orderId + ' is now collection'
                        },
                        success: function (data) {
                            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                                if (data.status) {
                                    manageOrderListDisplay(theOrder, true);
                                } else {
                                    manageOrderListDisplay(theOrder, true);
                                }
                            });
                        }
                    });
                } else {
                    zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                        manageOrderListDisplay(theOrder, true);
                    });
                }
            });
        });
    }
    function listCollectionOrder(all) {
        $('#placeOrderTypeBlock').hide();
        $('.menu-category.menu-button-inner').removeClass('active');
        if (all !== 'yes') {
            $('.footer-order-list-button').removeClass('active');
            $('#list-collection-only').addClass('active');
            $('#isToShowAllOrders').val('no');
            clearEposWorkAreaForOrderList('EposOrderListAreaCollection');
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            playBeepSound();
        } else {
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            $('#isToShowAllOrders').val('yes');
        }
        zamanEposDb.epos_order.where({'source': 'epos'}).filter(function (aCollectionOrder) {
            var userData = zamanEposCart.getUserData();
            return aCollectionOrder.type === 'collection' && Number(aCollectionOrder.branch) === Number(userData.branch) && Number(aCollectionOrder.team) === Number(userData.team);
        }).toArray().then(function (collectionOrders) {
            var html = ``;
            if (collectionOrders.length > 0) {
                collectionOrders.forEach(function (collectionOrder) {
                    if (Number(collectionOrder.status) <= 4) {
                        var isPaid = Number(collectionOrder.isPaid) === 3 ? '(<?php echo $this->lang->line('paid') ?>)' : '&nbsp;';
                        var collectionTime = $.trim(collectionOrder.orderInfo.collectionTime) ? collectionOrder.orderInfo.collectionTime : '&nbsp;';
                        html += `<div class="pane-content">
                        <div class="zaman-nav-item-pane">
                            <div class="order-item-img-block pull-left collection-bg order-process-status-` + collectionOrder.status + `" onclick="eposLoadOrder(` + collectionOrder.orderId + `,'no')">
                                <p class="text-capitalize" style="line-height:0.9;">` + isPaid + `<br/><img class="collection-icon" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAAA1JREFUeNpjYBgF1AQAAVAAATS4OtkAAAAASUVORK5CYII=" style="width:30px;"><br/>` + collectionOrder.orderInfo.name + `<br/>` + collectionTime + `</p>
                            </div>
                        </div>
                    </div>`;
                    }
                });
                html += `<div class="clearfix">&nbsp;</div>`;
            }
            $('#EposOrderListAreaCollection').html(html).show();
        });
    }
</script>






