<script type="text/javascript">
    function zamanPlaceWaitingOrder(orderId, customerName, customerPhone, convertTo, changePriceTo) {
        $('#placeOrderTypeBlock').hide();
        zamanEposPopupcloser();
        clearEposWorkArea();
        clearEposWorkAreaForOrderList();
        $('#categoryBreadcurm').show();
        $('#eposCategoryMenuList').show();
        $('.breadcurmb-category').text('<?php echo sprintf($this->lang->line('placing_order_head'), $this->lang->line('waiting')) ?>');
        var html = `
                <form id="waitingOrderInfoCollectForm">
                <div class="neworder-waiting ">
                    <div class="neworder-table-number">
                        <div class="form-group">
                            <label><?php echo $this->lang->line('customer_name') ?></label>
                            <input type="hidden" id="waitingOrderId">
                            <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="name" id="waitingCustomerName" data-error="#waitingCustomeNmaeErrorPlaceHolder" class="form-control text-capitalize" placeholder="<?php echo $this->lang->line('customer_name') ?>" autocomplete="off">
                            <input type="hidden" id="existingWaitingCustomerName">
                            <input type="hidden" id="isConvertedToWaiting">
                            <input type="hidden" id="isConvertedToWaitingPrice">
                        </div>
                        <div id="waitingCustomeNmaeErrorPlaceHolder"></div>
                    </div>
                    <div class="neworder-table-guest">
                        <div class="form-group">
                            <label><?php echo $this->lang->line('customer_phone') ?></label>
                            <input type="text" onfocus="ShowPhonePad()" name="phone" id="zamanPrimaryStaticCustomerPhone" data-error="#waitingCustomePhoneErrorPlaceHolder" class="form-control" placeholder="<?php echo $this->lang->line('customer_phone') ?>" autocomplete="off">
                            <input type="hidden" id="existingWaitingCustomerPhone">
                        </div>
                        <div id="waitingCustomePhoneErrorPlaceHolder"></div>
                        <div class="clearfix"></div>
                    </div>
                </div>
                <div class="clearfix"></div>
                <div class="tab-group config-submit" style="padding:0px 10px">
                    <button type="submit" onclick="initiateWaitingOrder('waitingOrderInfoCollectForm')"><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 waitingStaticPrimaryNumKey">1</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">2</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">3</div>                 
                       </div>
                        <div class="tab-group keypad">
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">4</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">5</div>        
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">6</div>         
                        </div>                       
                       <div class="tab-group keypad">
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">7</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">8</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">9</div>                                         
                       </div> 
                        <div class="tab-group keypad">
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryActionKey">DEL</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryNumKey">0</div>
                           <div class="tab-item zaman-epos-nav quantity-digit keypad-key waitingStaticPrimaryActionKey">CLR</div>         
                        </div>              
                    </div>                         
                </div>                                               
            </form>`;
        $('#eposCategoryMenuList').html(html).show();
        var userData = zamanEposCart.getUserData();
        var userApps = userData.userApps;
        var preveleges = userApps.length;
        if (preveleges > 1) {
            playBeepSound();
        }
        if (orderId > 0) {
            $('#waitingOrderId').val(orderId);
            $('#waitingCustomerName').val(customerName);
            $('#existingWaitingCustomerName').val(customerName);
            $('#zamanStaticWaitingCustomerPhone').val(customerPhone);
            $('#existingWaitingCustomerPhone').val(customerPhone);
            $('#isConvertedToWaiting').val(convertTo);
            $('#isConvertedToWaitingPrice').val(changePriceTo);
        }
        zamanPrimaryNumpad('zamanPrimaryStaticCustomerPhone', 'waitingStaticPrimaryNumKey', 'waitingStaticPrimaryActionKey');
    }
    function initiateWaitingOrder(formId) {
        $('#' + formId).validate({
            submitHandler: function () {
                var waitingCustomerName = $('#waitingCustomerName').val();
                var waitingCustomerPhone = $('#zamanPrimaryStaticCustomerPhone').val();
                checkAndSubmitWaitingInfo(waitingCustomerName, waitingCustomerPhone);
            },
            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'},
            errorPlacement: function (error, element) {
                errorPlacement(error, element);
            }
        });
    }
    function checkAndSubmitWaitingInfo(waitingCustomerName, waitingCustomerPhone) {
        var customerData = {
            name: waitingCustomerName,
            phone: waitingCustomerPhone
        };
        var existingBarCustomerName = $('#existingWaitingCustomerName').val();
        var existingBarCustomerPhone = $('#existingWaitingCustomerPhone').val();
        var existingBarOrderId = Number($('#waitingOrderId').val());
        if (Number(existingBarOrderId) > 0) {
            var isConvertedToWaiting = $('#isConvertedToWaiting').val();
            var isConvertedToWaitingPrice = $('#isConvertedToWaitingPrice').val();
            if (isConvertedToWaiting === 'yes') {
                eposConvertToWaiting(Number(existingBarOrderId), isConvertedToWaiting, isConvertedToWaitingPrice, customerData);
                window.setTimeout(function () {
                    zamanEposDb.epos_order.get({orderId: Number(existingBarOrderId)}).then(function (anOrder) {
                        if (anOrder.type === 'waiting') {
                            eposPostUpdateOnConvertToWaiting(Number(existingBarOrderId), customerData);
                        }
                    });
                }, 300);
            } else {
                updateWaitingOrderInfo(Number(existingBarOrderId), existingBarCustomerName, existingBarCustomerPhone, customerData);
            }
        } else {
            saveEposOrder(customerData, 'waiting');
        }
    }
    function  updateWaitingOrderInfo(existingBarOrderId, existingBarCustomerName, existingBarCustomerPhone, customerData) {
        var cart = zamanEposCart.listCart();
        if ((customerData.name).toLowerCase() === existingBarCustomerName.toLowerCase() && customerData.phone === existingBarCustomerPhone) {
            zamanEposDb.epos_order.get({orderId: Number(existingBarOrderId)}).then(function (theOrderNow) {
                manageOrderListDisplay(theOrderNow, true);
            });
        } else {
            zamanEposDb.epos_order.where("orderId").equals(existingBarOrderId).modify({
                orderInfo: customerData
            }).then(function (status) {
                if (status) {
                    if (cart.length > 0) {
                        resentCart(existingBarOrderId, cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                    }
                }
            }).then(function () {
                zamanEposDb.epos_order.get({orderId: Number(existingBarOrderId)}).then(function (theOrderNow) {
                    manageOrderListDisplay(theOrderNow, true);
                });
            });
        }
    }
    function eposConvertToWaiting(orderId, isConvertedTo, isConvertedToPrice, orderInfo) {
        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: 'waiting'
                });
            }).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 eposPostUpdateOnConvertToWaiting(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 waiting'
                        },
                        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 listWaitingOrder(all) {
        $('#placeOrderTypeBlock').hide();
        $('.menu-category.menu-button-inner').removeClass('active');
        if (all !== 'yes') {
            $('.footer-order-list-button').removeClass('active');
            $('#list-waiting-only').addClass('active');
            $('#isToShowAllOrders').val('no');
            clearEposWorkAreaForOrderList('EposOrderListAreaWaiting');
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            playBeepSound();
        } else {
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            $('#isToShowAllOrders').val('yes');
        }

        zamanEposDb.epos_order.where({'source': 'epos'}).filter(function (anWaitingOrder) {
            var userData = zamanEposCart.getUserData();
            return anWaitingOrder.type === 'waiting' && Number(anWaitingOrder.branch) === Number(userData.branch) && Number(anWaitingOrder.team) === Number(userData.team);
        }).toArray().then(function (waitingOrders) {
            var html = ``;
            if (waitingOrders.length > 0) {
                waitingOrders.forEach(function (waitingOrder) {
                    if (Number(waitingOrder.status) <= 4) {
                        var isPaid = Number(waitingOrder.isPaid) === 3 ? '(<?php echo $this->lang->line('paid') ?>)' : '&nbsp;';
                        html += `<div class="pane-content">
                        <div class="zaman-nav-item-pane">
                          <div class="order-item-img-block pull-left waiting-bg order-process-status-` + waitingOrder.status + `" onclick="eposLoadOrder(` + waitingOrder.orderId + `,'no')">
                            <p class="text-capitalize" style="line-height:10px;">` + isPaid + `<br/> <img class="waiting-icon" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAAA1JREFUeNpjYBgF1AQAAVAAATS4OtkAAAAASUVORK5CYII=" style="width:30px"><br/>` + waitingOrder.orderInfo.name + `</p>
                         </div>
                      </div>           
                     </div>`;
                    }
                });
                html += `<div class="clearfix">&nbsp;</div>`;
            }
            $('#EposOrderListAreaWaiting').html(html).show();
        });
    }
</script>



