<script type="text/javascript">
    function zamanPlaceBarOrder(orderId, customerName, customerPhone, convertTo, changePriceTo) {
        zamanEposPopupcloser();
        $('#placeOrderTypeBlock').hide();
        clearEposWorkArea();
        clearEposWorkAreaForOrderList();
        $('#categoryBreadcurm').show();
        $('#eposCategoryMenuList').show();
        $('#categoryBreadcurm').show();
        $('.breadcurmb-category').text('<?php echo sprintf($this->lang->line('placing_order_head'), $this->lang->line('bar')) ?>');
        $('.breadcurmb-menu').show().text('');
        var html = `<form id="barInfoCollectForm">
          <div class="neworder-waiting ">
            <div class="neworder-table-number" style="width:50%">
                <div class="form-group">
                    <label><?php echo $this->lang->line('customer_name') ?></label>
                    <input type="text" name="name" id="barCustomerName" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" data-error="#barCustomeNameErrorPlaceHolder" class="form-control text-capitalize" placeholder="<?php echo $this->lang->line('customer_name') ?>" autocomplete="off">
                    <input type="hidden" id="barOrderId">
                    <input type="hidden" id="existingBarCustomerName">
                    <input type="hidden" id="isConvertedToBar">
                    <input type="hidden" id="isConvertedToBarPrice">
                </div>
                <div id="barCustomeNameErrorPlaceHolder"></div>
                <div class="clearfix"></div>
            </div>
            <div class="neworder-table-guest" style="width:50%">
                <div class="form-group">
                    <label><?php echo $this->lang->line('customer_phone') ?></label>
                    <input type="text" id="zamanPrimaryStaticCustomerPhone" name="phone" onfocus="ShowPhonePad()" data-error="#barCustomePhoneErrorPlaceHolder" class="form-control" placeholder="<?php echo $this->lang->line('customer_phone') ?>" autocomplete="off">
                    <input type="hidden" id="existingBarCustomerPhone">
                </div>
                <div id="barCustomePhoneErrorPlaceHolder"></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="initiateBarOrder('barInfoCollectForm')"><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 barStaticPrimaryNumKey">1</div>
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">2</div>
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">3</div>  
            </div>  
            <div class="tab-group keypad">                     
              <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">4</div>
              <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">5</div>
              <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">6</div>                 
           </div>          
            <div class="tab-group keypad">
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">7</div>
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">8</div>
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">9</div>      
            </div> 
            <div class="tab-group keypad">    
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryActionKey">DEL</div>                 
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryNumKey">0</div> 
                <div class="tab-item zaman-epos-nav quantity-digit keypad-key barStaticPrimaryActionKey">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();
        }
        if (orderId > 0) {
            $('#barOrderId').val(orderId);
            $('#barCustomerName').val(customerName);
            $('#existingBarCustomerName').val(customerName);
            $('#zamanPrimaryStaticCustomerPhone').val(customerPhone);
            $('#existingBarCustomerPhone').val(customerPhone);
            $('#isConvertedToBar').val(convertTo);
            $('#isConvertedToBarPrice').val(changePriceTo);
        }
        zamanPrimaryNumpad('zamanPrimaryStaticCustomerPhone', 'barStaticPrimaryNumKey', 'barStaticPrimaryActionKey');
    }
    function initiateBarOrder(formId) {
        $('#' + formId).validate({
            submitHandler: function () {
                var barCustomerName = $('#barCustomerName').val();
                var barCustomerPhone = $('#zamanPrimaryStaticCustomerPhone').val();
                checkAndSubmitBarInfo(barCustomerName, barCustomerPhone);
            },
            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 checkAndSubmitBarInfo(barCustomerName, barCustomerPhone) {
        var customerData = {
            name: barCustomerName,
            phone: barCustomerPhone
        };
        var existingBarCustomerName = $('#existingBarCustomerName').val();
        var existingBarCustomerPhone = $('#existingBarCustomerPhone').val();
        var existingBarOrderId = Number($('#barOrderId').val());
        if (existingBarOrderId > 0) {
            var isConvertedToBar = $('#isConvertedToBar').val();
            var isConvertedToBarPrice = $('#isConvertedToBarPrice').val();
            if (isConvertedToBar === 'yes') {
                eposConvertToBar(Number(existingBarOrderId), isConvertedToBar, isConvertedToBarPrice, customerData);
                window.setTimeout(function () {
                    zamanEposDb.epos_order.get({orderId: Number(existingBarOrderId)}).then(function (anOrder) {
                        if (anOrder.type === 'bar') {
                            eposPostUpdateOnConvertToBar(Number(existingBarOrderId), customerData);
                        }
                    });
                }, 300);
            } else {
                updateBarOrderInfo(Number(existingBarOrderId), existingBarCustomerName, existingBarCustomerPhone, customerData);
            }
        } else {
            zamanEposDb.epos_customer.get({phone: barCustomerPhone}).then(function (aCustomer) {
                if (typeof (aCustomer) !== 'undefined') {
                    saveEposOrder(customerData, 'bar');
                } else {
                    zamanEposDb.epos_customer.add(customerData).then(function (theCustomer) {
                        if (theCustomer > 0) {
                            saveEposOrder(customerData, 'bar');
                        }
                    });
                }
            });
        }
    }
    function  updateBarOrderInfo(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_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 eposConvertToBar(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: 'bar'
                });
            }).then(function () {
                if (isConvertedTo === 'yes' && isConvertedToPrice === 'in') {
                    zamanEposCart.changeToInPrice();
                }
                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 eposPostUpdateOnConvertToBar(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 () {
            displayEposCart();
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                if (Number(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 bar'
                        },
                        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 listBarOrder(all) {
        $('#placeOrderTypeBlock').hide();
        $('.menu-category.menu-button-inner').removeClass('active');
        if (all !== 'yes') {
            $('.footer-order-list-button').removeClass('active');
            $('#list-bar-only').addClass('active');
            $('#isToShowAllOrders').val('no');
            clearEposWorkAreaForOrderList('EposOrderListAreaBar');
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            playBeepSound();
        } else {
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            $('#isToShowAllOrders').val('yes');
        }
        zamanEposDb.epos_order.where({'source': 'epos'}).filter(function (aBarOrder) {
            var userData = zamanEposCart.getUserData();
            return aBarOrder.type === 'bar' && Number(aBarOrder.branch) === Number(userData.branch) && Number(aBarOrder.team) === Number(userData.team);
        }).toArray().then(function (barOrders) {
            var html = ``;
            if (barOrders.length > 0) {
                barOrders.forEach(function (barOrder) {
                    if (Number(barOrder.status) <= 4) {
                        var isPaid = Number(barOrder.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 bar-bg order-process-status-` + barOrder.status + `" onclick="eposLoadOrder(` + barOrder.orderId + `,'no')">
                                    <p class="text-capitalize" style="line-height:0.9;">` + isPaid + `<br/><img class="bar-icon" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC8AAAAvAQMAAABJ6QHvAAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAAA1JREFUeNpjYBgFVAEAAUkAAf+U2WcAAAAASUVORK5CYII=" style="width:30px"><br/>` + barOrder.orderInfo.name + `</p>        
                                </div>
                            </div>
                        </div>`;
                    }
                });
                html += `<div class="clearfix">&nbsp;</div>`;
            }
            $('#EposOrderListAreaBar').html(html).show();
        });
    }
</script>




