<script type="text/javascript">
    function zamanPlaceTableOrder(orderId, exitingTable, existingGuest, 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('table')) ?>');
        $('.breadcurmb-menu').show().text('');
        var html = `<form id="tableOrderInfoCollectForm">
                    <div class="neworder-table">
                        <div class="neworder-table-number">
                            <div class="form-group">
                                <label><?php echo $this->lang->line('table_number') ?></label>
                                <input type="text" name="tableNumber" data-error="#tableNumberErrorPlaceHolder" id="zamanPrimaryTableNumber" class="form-control" placeholder="<?php echo $this->lang->line('table_number') ?>">
                                <input type="hidden" id="existingTableNumber">
                                <input type="hidden" id="existingTableOrderId">
                                <input type="hidden" id="isConvertedToTable">
                                <input type="hidden" id="isConvertedToTablePrice">
                            </div>
                            <div id="tableNumberErrorPlaceHolder"></div>
                            <div class="clearfix"></div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">1</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">2</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">3</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">-S1</div>        
                            </div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">4</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">5</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">6</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">-S2</div>         
                            </div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">7</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">8</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">9</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">-S3</div>        
                            </div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryActionKey">DEL</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">0</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryActionKey">CLR</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tablePrimaryNumKey">-S4</div>           
                            </div>
                        </div>
                        <div class="neworder-table-guest">
                            <div class="form-group">
                                <label><?php echo $this->lang->line('guest_quantity') ?></label>
                                <input type="text" name="guestQty" data-error="#tableGuestQtyErrorPlaceHolder" id="zamanSecondaryTableNumber" class="form-control" placeholder="<?php echo $this->lang->line('guest_quantity') ?>">
                            </div>
                            <div id="tableGuestQtyErrorPlaceHolder"></div>
                            <div class="clearfix"></div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">1</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">2</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">3</div>
                            </div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">4</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">5</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">6</div>
                            </div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">7</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">8</div>
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">9</div>
                            </div>
                            <div class="tab-group keypad">
                               <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryActionKey">DEL</div>
                               <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryNumKey">0</div>
                               <div class="tab-item zaman-epos-nav quantity-digit keypad-key tableSecondaryActionKey">CLR</div>
                            </div>
                        </div>
                    </div>
                    <div class="clearfix"></div>
                    <div class="tab-group config-submit" style="padding:0px 10px">
                        <button type="submit" onclick="initiateTableOrder('tableOrderInfoCollectForm')"><span class="icon icon-folder"></span>&nbsp;<?php echo $this->lang->line('go') ?></button>
                    </div>
                </form> `;
        $('#eposCategoryMenuList').html(html);
        var userData = zamanEposCart.getUserData();
        var userApps = userData.userApps;
        var preveleges = userApps.length;
        if (preveleges > 1) {
            playBeepSound();
        }
        if (exitingTable > 0) {
            $('#zamanPrimaryTableNumber').val(exitingTable);
            $('#eposTableOrderInfoCollector .popup-title').text('<?php echo $this->lang->line('update_customer_table') ?>');
        } else {
            $('#eposTableOrderInfoCollector .popup-title').text('<?php echo $this->lang->line('customer_table_information') ?>');
        }
        if (existingGuest > 0) {
            $('#zamanSecondaryTableNumber').val(existingGuest);
        }
        $('#existingTableNumber').val(exitingTable);
        $('#existingTableOrderId').val(orderId);
        $('#isConvertedToTable').val(convertTo);
        $('#isConvertedToTablePrice').val(changePriceTo);
        zamanPrimaryNumpad('zamanPrimaryTableNumber', 'tablePrimaryNumKey', 'tablePrimaryActionKey');
        zamanSecondaryNumpad('zamanSecondaryTableNumber', 'tableSecondaryNumKey', 'tableSecondaryActionKey');
    }
    function initiateTableOrder(formId) {
        $('#' + formId).validate({
            submitHandler: function () {
                var tableNumber = $('#zamanPrimaryTableNumber').val();
                var guestQty = $('#zamanSecondaryTableNumber').val();
                checkAndSubmitTableInfo(tableNumber, guestQty);
            },
            errorClass: "has-error",
            highlight: function (e) {
                $(e).closest('.form-group').addClass('has-error');
            },
            unhighlight: function (e) {
                $(e).closest('.form-group').removeClass('has-error');
            },
            rules: {
                tableNumber: {required: true},
                guestQty: {required: true}
            },
            messages: {
                tableNumber: 'Table Number is required',
                guestQty: 'Guest Quantity is a required field'
            },
            errorPlacement: function (error, element) {
                errorPlacement(error, element);
            }
        });
    }
    function checkAndSubmitTableInfo(tableNumber, guestQty) {
        zamanEposDb.transaction('rw', [zamanEposDb.epos_branch,zamanEposDb.epos_table, zamanEposDb.epos_order, zamanEposDb.epos_discountplan, zamanEposDb.epos_discountmulti, zamanEposDb.epos_discountitem, zamanEposDb.epos_menucategory, zamanEposDb.epos_menu, zamanEposDb.epos_menuselection], function () {
            var tableInfo = {
                'tableNumber': tableNumber,
                'guestQty': guestQty,
                'status': '3'
            };
            var existingTableNumber = Number($('#existingTableNumber').val());
            var existingTableOrderId = Number($('#existingTableOrderId').val());
            if (existingTableOrderId > 0 && existingTableNumber > 0) {
                vacantTableAndUpdateOrder(existingTableOrderId, existingTableNumber, tableInfo);
            } else {
                zamanEposDb.epos_table.get({tableNumber: tableNumber}, function (existingTable) {
                    if (typeof (existingTable) === 'undefined') {
                        zamanEposDb.epos_table.add(tableInfo).then(function (lid) {
                            if (lid > 0) {
                                var isConvertedToTable = $('#isConvertedToTable').val();
                                var isConvertedToTablerPrice = $('#isConvertedToTablePrice').val();
                                if (isConvertedToTable === 'yes') {
                                    eposConvertToTable(existingTableOrderId, isConvertedToTable, isConvertedToTablerPrice, tableInfo);
                                    window.setTimeout(function () {
                                        zamanEposDb.epos_order.get({orderId: Number(existingTableOrderId)}).then(function (anOrder) {
                                            if (anOrder.type === 'table') {
                                                eposPostUpdateOnConvertToTable(Number(existingTableOrderId), tableInfo);
                                            }
                                        });
                                    }, 300);
                                } else {
                                    saveEposOrder(tableInfo, 'table');
                                }
                            } else {
                                warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('data_saving_failed') ?>', '<?php echo $this->lang->line('close') ?>');
                            }
                        });
                    } else {
                        if (existingTable.status === '3') {
                            $.confirm({
                                title: '<?php echo $this->lang->line('warning') ?>',
                                message: '<?php echo $this->lang->line('table_number_msg') ?>' + tableNumber + '<?php echo ' ' . $this->lang->line('not_vacant') . ' ' . $this->lang->line('make_table_vacant') ?>',
                                buttons: {
                                    '<span class="icon icon-check">&nbsp;<?php echo $this->lang->line('yes') ?></span>': {
                                        'class': 'positive',
                                        'action': function () {
                                            jsutVacantTableAndPlaceNew('', tableNumber, '', '', '');
                                        }
                                    },
                                    '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('no') ?></span>': {
                                        'class': 'negative',
                                        'action': function () {}
                                    }
                                }
                            });
                        } else {
                            tableInfo.lid = existingTable.lid;
                            zamanEposDb.epos_table.put(tableInfo).then(function (lid) {
                                if (lid > 0) {
                                    var isConvertedToTable = $('#isConvertedToTable').val();
                                    var isConvertedToTablerPrice = $('#isConvertedToTablePrice').val();
                                    if (isConvertedToTable === 'yes') {
                                        eposConvertToTable(existingTableOrderId, isConvertedToTable, isConvertedToTablerPrice, tableInfo);
                                        window.setTimeout(function () {
                                            zamanEposDb.epos_order.get({orderId: Number(existingTableOrderId)}).then(function (anOrder) {
                                                if (anOrder.type === 'table') {
                                                    eposPostUpdateOnConvertToTable(Number(existingTableOrderId), tableInfo);
                                                }
                                            });
                                        }, 300);
                                    } else {
                                        saveEposOrder(tableInfo, 'table');
                                    }
                                } else {
                                    warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('data_saving_failed') ?>', '<?php echo $this->lang->line('close') ?>');
                                }
                            });
                        }
                    }
                });
            }
        });
    }

    function jsutVacantTableAndPlaceNew(orderId, exitingTable, existingGuest, convertTo, changePriceTo) {
        zamanEposDb.epos_table.where("tableNumber").equals(exitingTable).modify({
            status: '2'
        }).then(function (status) {
            if (status) {
                zamanPlaceTableOrder(orderId, exitingTable, existingGuest, convertTo, changePriceTo);
            }
        });
    }
    function vacantTableAndUpdateOrder(existingTableOrderId, existingTableNumber, newTableInfo) {
        var cart = zamanEposCart.listCart();
        zamanEposDb.epos_table.get({tableNumber: (newTableInfo.tableNumber).toString()}, function (existingTable) {
            if (typeof (existingTable) === 'undefined') {
                zamanEposDb.epos_table.add(newTableInfo).then(function (lid) {
                    if (lid > 0) {
                        zamanEposDb.epos_table.where("tableNumber").equals(existingTableNumber.toString()).modify({
                            status: '2'
                        }).then(function () {
                            newTableInfo.lid = lid;
                            newTableInfo.switchFrom = existingTableNumber;
                            zamanEposDb.epos_order.where("orderId").equals(existingTableOrderId).modify({
                                orderInfo: newTableInfo
                            }).then(function (status) {
                                if (status) {
                                    eposLoadOrder(existingTableOrderId, 'yes');
                                }
                            }).then(function () {
                                if (cart.length > 0) {
                                    resentCart(existingTableOrderId, cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                                }
                            });
                        });
                    }
                });
            } else {
                if (existingTable.tableNumber === existingTableNumber.toString()) {
                    newTableInfo.lid = existingTable.lid;
                    zamanEposDb.epos_table.put(newTableInfo).then(function (lid) {
                        if (lid > 0) {
                            zamanEposDb.epos_order.where("orderId").equals(existingTableOrderId).modify({
                                orderInfo: newTableInfo
                            }).then(function () {
                                zamanEposDb.epos_table.where("tableNumber").equals(existingTableNumber.toString()).modify({
                                    status: '2'
                                });
                            }).then(function () {
                                eposLoadOrder(existingTableOrderId, 'yes');
                            }).then(function () {
                                if (cart.length > 0) {
                                    resentCart(existingTableOrderId, cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                                }
                            });
                        } else {
                            warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('data_saving_failed') ?>', '<?php echo $this->lang->line('close') ?>');
                        }
                    });
                } else {
                    if (existingTable.status === '2') {
                        newTableInfo.lid = existingTable.lid;
                        zamanEposDb.epos_table.put(newTableInfo).then(function (lid) {
                            if (lid > 0) {
                                newTableInfo.switchFrom = existingTableNumber;
                                zamanEposDb.epos_order.where("orderId").equals(existingTableOrderId).modify({
                                    orderInfo: newTableInfo
                                }).then(function () {
                                    zamanEposDb.epos_table.where("tableNumber").equals(existingTableNumber.toString()).modify({
                                        status: '2'
                                    });
                                }).then(function () {
                                    eposLoadOrder(existingTableOrderId, 'yes');
                                }).then(function () {
                                    if (cart.length > 0) {
                                        resentCart(existingTableOrderId, cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                                    }
                                });
                            } else {
                                warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('data_saving_failed') ?>', '<?php echo $this->lang->line('close') ?>');
                            }
                        });
                    } else {
                        $.confirm({
                            title: '<?php echo $this->lang->line('warning') ?>',
                            message: '<?php echo $this->lang->line('table_number_msg') ?>' + newTableInfo.tableNumber + '<?php echo ' ' . $this->lang->line('not_vacant') . ' ' . $this->lang->line('make_table_vacant') ?>',
                            buttons: {
                                '<span class="icon icon-check">&nbsp;<?php echo $this->lang->line('yes') ?></span>': {
                                    'class': 'positive',
                                    'action': function () {
                                        jsutVacantTableAndPlaceNew(existingTableOrderId, newTableInfo.tableNumber, newTableInfo.guestQty, '', '');
                                    }
                                },
                                '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('no') ?></span>': {
                                    'class': 'negative',
                                    'action': function () {}
                                }
                            }
                        });
                    }
                }
            }
        });
    }
    function eposConvertToTable(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: 'table'
                });
            }).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 eposPostUpdateOnConvertToTable(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 (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 table'
                        },
                        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 listTableOrder(all) {
        $('#placeOrderTypeBlock').hide();
        $('.menu-category.menu-button-inner').removeClass('active');
        if (all !== 'yes') {
            $('.footer-order-list-button').removeClass('active');
            $('#list-table-only').addClass('active');
            $('#isToShowAllOrders').val('no');
            clearEposWorkAreaForOrderList('EposOrderListAreaTable');
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            playBeepSound();
        } else {
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            $('#isToShowAllOrders').val('yes');
        }
        zamanEposDb.epos_order.where({'source': 'epos'}).filter(function (aTableOrder) {
            var userData = zamanEposCart.getUserData();
            return aTableOrder.type === 'table' && Number(aTableOrder.branch) === Number(userData.branch) && Number(aTableOrder.team) === Number(userData.team);
        }).toArray().then(function (tableOrders) {
            var html = ``;
            if (tableOrders.length > 0) {
                tableOrders.forEach(function (tableOrder) {
                    if (Number(tableOrder.status) <= 4) {
                        var isPaid = Number(tableOrder.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 table-bg order-process-status-` + tableOrder.status + `" onclick="eposLoadOrder(` + tableOrder.orderId + `,'no')">
                                    <p style="padding-top:2px; line-height:10px;">` + tableOrder.orderInfo.tableNumber + `<br/>` + isPaid + `<br/><img class="table-icon" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAAA1JREFUeNpjYBgF1AQAAVAAATS4OtkAAAAASUVORK5CYII=" style="width:25px"><br/>` + tableOrder.orderInfo.guestQty + `</p>   
                                </div>
                            </div>
                        </div>`;
                    }
                });
                html += `<div class="clearfix">&nbsp;</div>`;
            }
            $('#EposOrderListAreaTable').html(html).show();
        });
    }
</script>






