<div style="display: none;">
    <div id="paymentContent">
        <div class="popup-header toolbar-header">
            <div class="popup-title"><?php echo $this->lang->line('order_payment') ?></div>
            <div class="popup-close-btn" onclick="zamanEposPopupcloser()"><span class="icon icon-cancel"></span></div>
        </div>
        <form id="orderPaymentProcessForm">
            <div class="popup-content">
                <div class="tab-group payment-type-list" id="paymentOptionList"></div>
                <div class="pane-payment">
                    <div class="pane-payment-left">
                        <div class="pane-payment-balance">
                            <div class="payment-balance-block"><?php echo $this->lang->line('ref') ?>:<span id="paymentOrderReferenceNumber"></span></div>
                            <div class="payment-balance-block"><?php echo $this->lang->line('total') ?>: <span id="paymentOrderReferenceTotal"></span></div>
                            <div class="payment-balance-block due-block"><span id="paymentStatusText" >Due</span><br/><span id="paymentOrderReferenceTotalDue"></span></div>
                            <div class="payment-balance-block pay-tip">&nbsp;<span id="paymentExtraAsTip" style="display: none;"><?php echo $this->lang->line('pay_as_tip') ?>&nbsp;<input type="checkbox" name="paytip" id="paymnetHasTips"></span></div>
                        </div>
                    </div>
                    <div class="pane-payment-middle">
                        <div class="neworder-table-guest collection-phone ccfee">
                            <div class="form-group">
                                <input type="text" name="amount" id="zamanPrimaryPaymentValue" class="form-control" style="height: 32px;" placeholder="<?php echo $this->lang->line('amount') ?>">
                                <input type="hidden" id="zamanPaymentVoucherCode" name="voucher_code" class="form-control" style="height: 32px; width: 63%;" placeholder="<?php echo $this->lang->line('voucher_code') ?>"><span style="background: #0d7da2;padding: 9px 43px;margin-left: 0px;width: 37%;border-radius: 3px; display: none;" id="voucherActionBtn" onclick="paymentReceiveAmount('4', 'Voucher')"><?php echo $this->lang->line('add') ?></span>
                            </div>
                            <div class="clearfix"></div>
                            <div id="paymentBtnsOnPaymentPage">
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">1</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">2</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">3</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">10</div>

                                </div>
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">4</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">5</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">6</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">20</div>
                                </div>
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">7</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">8</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">9</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">50</div>
                                </div>
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryActionKey">DEL</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">0</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryActionKey">CLR</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentPrimaryNumKey">.</div>
                                </div>
                            </div>
                            <div id="voucherCodeBtnsOnPaymentPage" style="display: none;">
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">1</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">2</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">3</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">10</div>
                                </div>
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">4</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">5</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">6</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">20</div>
                                </div>
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">7</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">8</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">9</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">50</div>
                                </div>
                                <div class="tab-group keypad">
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherActionKey">DEL</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">0</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherActionKey">CLR</div>
                                    <div class="tab-item zaman-epos-nav quantity-digit keypad-key paymentVoucherNumKey">.</div>
                                </div>
                            </div>
                            <div class="tab-group keypad">
                                <div class="tab-item zaman-epos-nav quantity-digit keypad-key" onclick="zamanConfirmPaymentAndClose()"><span class="icon icon-credit-card"></span>&nbsp;<?php echo $this->lang->line('confirm_payment') ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="pane-payment-right" id="receivedPaymentOption"></div>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript">
    function zamanOrderPayAndCloseControllerPopup() {
        var cartArray = zamanEposCart.listCart();
        var currentOrderId = zamanEposCart.getEposCurrentId();
        zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (anOrder) {
            if (typeof (anOrder) !== 'undefined') {
                if (anOrder.type === 'delivery') {
                    if (Number(anOrder.orderInfo.minOrderAmount) > Number(zamanEposCart.cartCalculator().cartSubtotal)) {
                        $('.page-loader').hide();
                        warning('<?php echo $this->lang->line('delivery') . ' ' . $this->lang->line('warning') ?>', '<?php echo $this->lang->line('required_minimum_delivery_amount') ?>' + toCurrency(anOrder.orderInfo.minOrderAmount), '<?php echo $this->lang->line('ok') ?>');
                    } else {
                        if (cartArray.length >= 1) {
                            if (Number(anOrder.isPaid) === 3) {
                                orderPaymentPreProcessor(anOrder);
                            } else {
                                orderPaymentProcessor(anOrder);
                            }
                        } else {
                            warning('<?php echo $this->lang->line('empty_cart') ?>', '<?php echo $this->lang->line('empty_cart_msg') ?>', '<?php echo $this->lang->line('close') ?>');
                        }
                    }
                } else {
                    if (cartArray.length >= 1) {
                        if (Number(anOrder.isPaid) === 3) {
                            orderPaymentPreProcessor(anOrder);
                        } else {
                            orderPaymentProcessor(anOrder);
                        }
                    } else {
                        warning('<?php echo $this->lang->line('empty_cart') ?>', '<?php echo $this->lang->line('empty_cart_msg') ?>', '<?php echo $this->lang->line('close') ?>');
                    }
                }
            } else {
                settleDownNewOrderOption();
            }
        });
    }
    function orderPaymentPreProcessor(anOrder) {
        if (Number(anOrder.status) <= 1) {
            $.confirm({
                title: Number(anOrder.isPaid) === 3 ? '<?php echo $this->lang->line('order_paid') ?>' : '<?php echo $this->lang->line('warning') ?>',
                message: Number(anOrder.isPaid) === 3 ? '<?php echo $this->lang->line('sent_paid_order_msg') ?>' : '<?php echo $this->lang->line('cart_has_unsent_items') . ' ' . $this->lang->line('send_it_now') ?>',
                buttons: {
                    '<span class="icon icon-check">&nbsp;<?php echo $this->lang->line('yes') ?></span>': {
                        'class': 'green',
                        'action': function () {
                            $('.page-loader').show();
                            sendCartForProcessing();
                        }
                    },
                    '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('no') ?></span>': {
                        'class': 'black',
                        'action': function () {
                            playBeepSound();
                            $.confirm.hide();
                        }
                    }
                }
            });
        } else {
            if (anOrder.type === 'table' || anOrder.type === 'bar') {
                $.confirm({
                    title: '<?php echo $this->lang->line('order_paid') ?>',
                    message: '<?php echo $this->lang->line('sent_paid_order_msg_with_option') ?>',
                    buttons: {
                        '<span class="icon icon-print">&nbsp;<?php echo $this->lang->line('print_and_close') ?></span>': {
                            'class': 'green',
                            'action': function () {
                                orderPaymentChangePrintAndStatusFlag(anOrder.orderId, 5, 3);
                            }
                        },
                        '<span class="icon icon-book">&nbsp;<?php echo $this->lang->line('close') ?></span>': {
                            'class': 'black',
                            'action': function () {
                                orderPaymentChangePrintAndStatusFlag(anOrder.orderId, 5, 2);
                            }
                        },
                        '<span class="icon icon-print">&nbsp;<?php echo $this->lang->line('print') ?></span>': {
                            'class': 'green',
                            'action': function () {
                                orderPaymentChangePrintAndStatusFlag(anOrder.orderId, 4, 3);
                            }
                        },
                        '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('cancel') ?></span>': {
                            'class': 'red',
                            'action': function () {
                                playBeepSound();
                                $.confirm.hide();
                            }
                        }
                    }
                });
            } else {
                $.confirm({
                    title: '<?php echo $this->lang->line('print_bill_copy') ?>',
                    message: '<?php echo $this->lang->line('bill_copy_prompt') ?>',
                    buttons: {
                        '<span class="icon icon-check">&nbsp;<?php echo $this->lang->line('yes') ?></span>': {
                            'class': 'green',
                            'action': function () {
                                orderPaymentChangePrintAndStatusFlag(anOrder.orderId, 5, 3);
                            }
                        },
                        '<span class="icon icon-book">&nbsp;<?php echo $this->lang->line('no') ?></span>': {
                            'class': 'black',
                            'action': function () {
                                orderPaymentChangePrintAndStatusFlag(anOrder.orderId, 5, 2);
                            }
                        },
                        '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('cancel') ?></span>': {
                            'class': 'red',
                            'action': function () {
                                playBeepSound();
                                $.confirm.hide();
                            }
                        }

                    }
                });
            }
        }
        playBeepSound();
    }
    function orderPaymentChangePrintAndStatusFlag(id, status, bill) {
        zamanEposDb.epos_order.where("orderId").equals(Number(id)).modify({
            status: status,
            hasBillPrint: bill
        }).then(function (isYes) {
            if (isYes) {
                if (status <= 4) {
                    zamanEposCart.clearOnPayAndCloseForSentInOrder();
                } else {
                    zamanEposCart.clearOnPayAndClose();
                }
            }
        }).then(function () {
            zamanEposDb.epos_order.get({orderId: Number(id)}).then(function (theOrder) {
                $('.page-loader').show();
                remotePayAndClose(theOrder);
            });
        });
    }
    function orderPaymentProcessor(anOrder) {
        $.colorbox({
            inline: true,
            scrolling: false,
            href: "#paymentContent",
            width: '70%',
            height: '490px',
            maxWidth: "100%",
            open: true,
            closeButton: false,
            transition: 'none',
            overlayClose: false,
            onOpen: function () {
                playBeepSound();
                zamanEposCart.clearPayments();
            },
            onLoad: function () {
                var paymentUserData = zamanEposCart.getUserData();
                var cartCalculator = zamanEposCart.cartCalculator();
                zamanEposDb.epos_paymentoption.where({status: '3'}).toArray().then(function (paymentOptions) {
                    var payOptionCounter = 0;
                    var paymentOptionList = '';
                    var receivedPaymentOption = '';
                    paymentOptions.forEach(function (option) {
                        if (option.title === "Voucher") {
                            if (Number(paymentUserData.group) === 5) {
                                payOptionCounter++;
                                paymentOptionList += '<div class="tab-item zaman-epos-nav" onclick="paymentReceiveAmount(\'' + option.id + '\',\'' + option.title + '\')">' + option.title + '</div>';
                                receivedPaymentOption += '<div class="tab-group keypad"><div class="tab-item" onclick="deletePayment(\'' + option.id + '\',\'' + option.title + '\')"><span>' + option.title + '</span>&nbsp;<span class="payment-amount" id="paymentOption-' + option.id + '">' + toCurrency(0) + '</span>&nbsp;<span class="payment-cancel-icon icon icon-cancel-circled"></span></div></div>';
                            }
                        } else {
                            payOptionCounter++;
                            paymentOptionList += '<div class="tab-item zaman-epos-nav" onclick="paymentReceiveAmount(\'' + option.id + '\',\'' + option.title + '\')">' + option.title + '</div>';
                            receivedPaymentOption += '<div class="tab-group keypad"><div class="tab-item" onclick="deletePayment(\'' + option.id + '\',\'' + option.title + '\')"><span>' + option.title + '</span>&nbsp;<span class="payment-amount" id="paymentOption-' + option.id + '">' + toCurrency(0) + '</span>&nbsp;<span class="payment-cancel-icon icon icon-cancel-circled"></span></div></div>';
                        }
                    });
                    $('#paymentOptionList').html(paymentOptionList);
                    receivedPaymentOption += '<div class="tab-group keypad"><div class="tab-item waiting-bg"><span>Total Received</span>&nbsp;<span class="payment-amount" id="paymentTotalReceived">' + toCurrency(0) + '</span><span class="payment-cancel-icon"></span></div></div>';
                    $('#receivedPaymentOption').html(receivedPaymentOption);
                    if (payOptionCounter === 4) {
                        $('.pane-payment .pane-payment-right .tab-item').css({'padding': '21px 0px'});
                    }
                    if (payOptionCounter === 3) {
                        $('.pane-payment .pane-payment-right .tab-item').css({'padding': '30px 0px'});
                    }
                });
                if (Number(anOrder.status) >= 2) {
                    $('#paymentOrderReferenceNumber').text(anOrder.orderId + '/' + anOrder.sid);
                } else {
                    $('#paymentOrderReferenceNumber').text(anOrder.orderId);
                }

                $('#paymentOrderReferenceTotal').text(toCurrency(cartCalculator.Total));
                $('#paymentOrderReferenceTotalDue').text(toCurrency(cartCalculator.Total));
            },
            onComplete: function () {
                window.setTimeout(function () {
                    displayPaymentOption();
                }, 200);
            },
            onClosed: function () {
                zamanEposCart.clearPayments();
                resetForm('orderPaymentProcessForm');
            }
        });
    }
    function paymentReceiveAmount(paymentTypeId, paymentType) {
        var currentOrderId = zamanEposCart.getEposCurrentId();
        var cartCalculator = zamanEposCart.cartCalculator();
        zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (anOrder) {
            if (typeof (anOrder) !== 'undefined') {
                var textBoxPaymentAmount = Number($('#zamanPrimaryPaymentValue').val());
                var receivedAmount = 0;
                var TotalPayments = totalAmountReceived();
                if (Number(textBoxPaymentAmount > 0)) {
                    receivedAmount = Number(textBoxPaymentAmount);
                } else {
                    receivedAmount = TotalPayments > 0 ? toCurrencyNoMoney(cartCalculator.Total) - toCurrencyNoMoney(TotalPayments) : toCurrencyNoMoney(cartCalculator.Total);
                }
                var due = toCurrencyNoMoney(cartCalculator.Total) - toCurrencyNoMoney(TotalPayments);
                if (due <= 0) {
                    warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('nothing_to_pay_more') ?>', '<?php echo $this->lang->line('close') ?>');
                } else {
                    if (paymentType.toLowerCase() === 'voucher') {
                        var voucherCode = Number($('#zamanPaymentVoucherCode').val());
                        var existingVoucherAmount = 0;
                        if (voucherCode > 0 && receivedAmount > 0) {
                            zamanEposDb.epos_voucher.get({code: voucherCode.toString(), status: '3'}).then(function (theVoucher) {
                                if (typeof (theVoucher) !== 'undefined') {
                                    var validityStartDate = new Date(theVoucher.start);
                                    var startY = validityStartDate.getFullYear();
                                    var startM = validityStartDate.getMonth();
                                    var startD = validityStartDate.getDate();
                                    var validityEndDate = new Date(theVoucher.end);
                                    var endY = validityEndDate.getFullYear();
                                    var endM = validityEndDate.getMonth();
                                    var endD = validityEndDate.getDate();
                                    var todayDate = new Date();
                                    var todayY = todayDate.getFullYear();
                                    var todayM = todayDate.getMonth();
                                    var todayD = todayDate.getDate();
                                    if ((todayY >= startY && todayY <= endY) && (todayM >= startM && todayM <= endM) && (todayD >= startD && todayD <= endD)) {
                                        var payments = zamanEposCart.listpayments();
                                        if (payments.length > 0) {
                                            payments.forEach(function (method) {
                                                if (method.type === 'Voucher') {
                                                    existingVoucherAmount += Number(method.amount);
                                                }
                                            });
                                        }
                                        if (Number(theVoucher.balance) > 0) {
                                            var remainingBalance = Number(theVoucher.balance) - Number(existingVoucherAmount);
                                            if (remainingBalance > 0) {
                                                if (receivedAmount > remainingBalance) {
                                                    receivedAmount = remainingBalance;
                                                }
                                                addPaymentFromPaymentPage(paymentTypeId, paymentType, receivedAmount, theVoucher.code);
                                            } else {
                                                warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('voucher_balance_insufficient') ?>', '<?php echo $this->lang->line('close') ?>');
                                            }
                                        } else {
                                            warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('voucher_balance_insufficient') ?>', '<?php echo $this->lang->line('close') ?>');
                                        }
                                    } else {
                                        warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('invalid_voucher_code') ?>', '<?php echo $this->lang->line('close') ?>');
                                    }
                                } else {
                                    warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('invalid_voucher_code') ?>', '<?php echo $this->lang->line('close') ?>');
                                }
                            });
                        } else {
                            $('#paymentBtnsOnPaymentPage').hide();
                            $('#voucherCodeBtnsOnPaymentPage').show();
                            $('#voucherActionBtn').show();
                            $('#zamanPaymentVoucherCode').attr('type', 'text');
                            $('#zamanPrimaryPaymentValue').attr('type', 'hidden');
                            playBeepSound();
                        }
                    } else {
                        addPaymentFromPaymentPage(paymentTypeId, paymentType, receivedAmount, 'no');
                    }
                }
            }
        });
    }
    function addPaymentFromPaymentPage(paymentTypeId, paymentType, receivedAmount, code) {
        zamanEposCart.addPayment(paymentTypeId, paymentType, receivedAmount, code);
        resetForm('orderPaymentProcessForm');
        displayPaymentOption();
        playBeepSound();
    }
    function deletePayment(id, title) {
        var deletedId = zamanEposCart.deletePayment(id, title);
        if (deletedId !== null) {
            $('#paymentOption-' + deletedId).text(toCurrency(0));
        }
        displayPaymentOption();
        playBeepSound();
    }
    function displayPaymentOption() {
        var payments = zamanEposCart.listpayments();
        var TotalPayments = totalAmountReceived();
        if (payments.length > 0) {
            payments.forEach(function (method) {
                $('#paymentOption-' + method.id).text(toCurrency(method.amount));
            });
        }
        $('#paymentTotalReceived').text(toCurrency(TotalPayments));
        var currentOrderId = zamanEposCart.getEposCurrentId();
        var cartCalculator = zamanEposCart.cartCalculator();
        zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (anOrder) {
            if (typeof (anOrder) !== 'undefined') {
                var due = toCurrencyNoMoney(cartCalculator.Total) - toCurrencyNoMoney(TotalPayments);
                if (due < 0) {
                    $('#paymentStatusText').text('<?php echo $this->lang->line('pay_back') ?>');
                    $('#paymentExtraAsTip').show();
                } else {
                    $('#paymentStatusText').text('<?php echo $this->lang->line('due') ?>');
                    $('#paymentExtraAsTip').hide();
                }
                $('#paymentOrderReferenceTotalDue').text(toCurrency(Math.abs(due)));
            }
        });
        $('#paymentBtnsOnPaymentPage').show();
        $('#voucherCodeBtnsOnPaymentPage').hide();
        $('#voucherActionBtn').hide();
        $('#zamanPaymentVoucherCode').attr('type', 'hidden');
        $('#zamanPrimaryPaymentValue').attr('type', 'text');
    }
    function totalAmountReceived() {
        var payments = zamanEposCart.listpayments();
        var TotalPayments = 0;
        if (payments.length > 0) {
            payments.forEach(function (method) {
                $('#paymentOption-' + method.id).text(toCurrency(method.amount));
                TotalPayments += method.amount;
            });
        }
        return TotalPayments;
    }
    function zamanConfirmPaymentAndClose() {
        var currentOrderId = zamanEposCart.getEposCurrentId();
        var cartCalculator = zamanEposCart.cartCalculator();
        zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (anOrder) {
            var due = toCurrencyNoMoney(cartCalculator.Total) - toCurrencyNoMoney(totalAmountReceived());
            if (due > 0) {
                playBeepSound();
                warning('<?php echo $this->lang->line('warning') ?>', '<?php echo $this->lang->line('payment_yet_not_covered') ?>', '<?php echo $this->lang->line('ok') ?>');
            } else {
                playBeepSound();
                paymentPrecheck(anOrder, due);
            }
        });
    }
    function paymentPrecheck(anOrder, due) {
        if (Number(anOrder.status) === 1) {
            paymentForPlacedOrder(anOrder.orderId, due);
        } else {
            if (Number(anOrder.status) >= 2) {
                if (anOrder.type === 'table' || anOrder.type === 'bar') {
                    paymentForReadyOrWaitingPaymentOrder(anOrder, due);
                } else {
                    paymentForProcessingOrder(anOrder.orderId, due);
                }

            }
        }
    }
    function paymentForPlacedOrder(currentOrderId, due) {
        $('.page-loader').show();
        zamanEposDb.epos_order.where("orderId").equals(Number(currentOrderId)).modify({
            payment: zamanEposCart.listpayments(),
            isPaid: 3,
            changeAmount: Number(toCurrencyNoMoney(due)),
            changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2
        }).then(function (status) {
            if (status) {
                paymentDeductFromVoucherOnPayAndClose();
                zamanEposPopupcloser();
            }
        }).then(function () {
            zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (theOrder) {
                var payments = theOrder.payment;
                var hasOnline = 'no';
                payments.forEach(function (method) {
                    if (method.type === 'Online') {
                        hasOnline = 'yes';
                    }
                });
                if (hasOnline === 'no') {
                    zamanEposCart.clearOnPayAndCloseForUnsentOrder();
                    zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (theOrder) {
                        manageOrderListDisplay(theOrder, true);
                        $('.page-loader').hide();
                    });
                } else {
                    paymentOnlineForwardToProcessing(theOrder);
                }
            });
        });
    }
    function paymentForProcessingOrder(currentOrderId, due) {
        $.confirm({
            title: '<?php echo $this->lang->line('print_bill_copy') ?>',
            message: '<?php echo $this->lang->line('bill_copy_prompt') ?>',
            buttons: {
                '<span class="icon icon-check">&nbsp;<?php echo $this->lang->line('yes') ?></span>': {
                    'class': 'green',
                    'action': function () {
                        zamanEposDb.epos_order.where("orderId").equals(Number(currentOrderId)).modify({
                            payment: zamanEposCart.listpayments(),
                            isPaid: 3,
                            status: 5,
                            changeAmount: Number(toCurrencyNoMoney(due)),
                            changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                            hasBillPrint: 3
                        }).then(function (status) {
                            if (status) {
                                paymentDeductFromVoucherOnPayAndClose();
                            }
                        }).then(function () {
                            zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (anOrder) {
                                $('.page-loader').show();
                                remotePayAndClose(anOrder);
                            });
                        });
                    }
                },
                '<span class="icon icon-book">&nbsp;<?php echo $this->lang->line('no') ?></span>': {
                    'class': 'black',
                    'action': function () {
                        zamanEposDb.epos_order.where("orderId").equals(Number(currentOrderId)).modify({
                            payment: zamanEposCart.listpayments(),
                            isPaid: 3,
                            status: 5,
                            changeAmount: Number(toCurrencyNoMoney(due)),
                            changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                            hasBillPrint: 2
                        }).then(function (status) {
                            if (status) {
                                paymentDeductFromVoucherOnPayAndClose();
                            }
                        }).then(function () {
                            zamanEposDb.epos_order.get({orderId: Number(currentOrderId)}).then(function (anOrder) {
                                $('.page-loader').show();
                                remotePayAndClose(anOrder);
                            });
                        });
                    }
                },
                '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('cancel') ?></span>': {
                    'class': 'red',
                    'action': function () {
                        playBeepSound();
                        $.confirm.hide();
                    }
                }
            }
        });
    }
    function paymentForReadyOrWaitingPaymentOrder(anOrder, due) {
        if (Number(anOrder.status) === 2) {
            $.confirm({
                title: '<?php echo $this->lang->line('order_paid') ?>',
                message: '<?php echo $this->lang->line('sent_paid_order_msg_with_option') ?>',
                buttons: {
                    '<span class="icon icon-print">&nbsp;<?php echo $this->lang->line('print_and_close') ?></span>': {
                        'class': 'green',
                        'action': function () {
                            zamanEposDb.epos_order.where("orderId").equals(Number(anOrder.orderId)).modify({
                                payment: zamanEposCart.listpayments(),
                                isPaid: 3,
                                status: 5,
                                changeAmount: Number(toCurrencyNoMoney(due)),
                                changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                                hasBillPrint: 3
                            }).then(function (status) {
                                if (status) {
                                    paymentDeductFromVoucherOnPayAndClose();
                                }
                            }).then(function () {
                                zamanEposDb.epos_order.get({orderId: Number(anOrder.orderId)}).then(function (anOrder) {
                                    $('.page-loader').show();
                                    remotePayAndClose(anOrder);
                                });
                            });
                        }
                    },
                    '<span class="icon icon-book">&nbsp;<?php echo $this->lang->line('close') ?></span>': {
                        'class': 'black',
                        'action': function () {
                            zamanEposDb.epos_order.where("orderId").equals(Number(anOrder.orderId)).modify({
                                payment: zamanEposCart.listpayments(),
                                isPaid: 3,
                                status: 5,
                                changeAmount: Number(toCurrencyNoMoney(due)),
                                changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                                hasBillPrint: 2
                            }).then(function (status) {
                                if (status) {
                                    paymentDeductFromVoucherOnPayAndClose();
                                }
                            }).then(function () {
                                zamanEposDb.epos_order.get({orderId: Number(anOrder.orderId)}).then(function (anOrder) {
                                    $('.page-loader').show();
                                    remotePayAndClose(anOrder);
                                });
                            });
                        }
                    },
                    '<span class="icon icon-print">&nbsp;<?php echo $this->lang->line('print') ?></span>': {
                        'class': 'green',
                        'action': function () {
                            zamanEposDb.epos_order.where("orderId").equals(Number(anOrder.orderId)).modify({
                                payment: zamanEposCart.listpayments(),
                                isPaid: 3,
                                status: 4,
                                changeAmount: Number(toCurrencyNoMoney(due)),
                                changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                                hasBillPrint: 3
                            }).then(function (status) {
                                if (status) {
                                    paymentDeductFromVoucherOnPayAndClose();
                                }
                            }).then(function () {
                                zamanEposDb.epos_order.get({orderId: Number(anOrder.orderId)}).then(function (anOrder) {
                                    $('.page-loader').show();
                                    remotePayAndClose(anOrder);
                                });
                            });
                        }
                    },
                    '<span class="icon icon-cancel red">&nbsp;<?php echo $this->lang->line('cancel') ?></span>': {
                        'class': 'red',
                        'action': function () {
                            playBeepSound();
                            $.confirm.hide();
                        }
                    }
                }
            });
        } else {
            $.confirm({
                title: '<?php echo $this->lang->line('print_bill_copy') ?>',
                message: '<?php echo $this->lang->line('bill_copy_prompt') ?>',
                buttons: {
                    '<span class="icon icon-check">&nbsp;<?php echo $this->lang->line('yes') ?></span>': {
                        'class': 'green',
                        'action': function () {
                            zamanEposDb.epos_order.where("orderId").equals(Number(anOrder.orderId)).modify({
                                payment: zamanEposCart.listpayments(),
                                isPaid: 3,
                                status: 5,
                                changeAmount: Number(toCurrencyNoMoney(due)),
                                changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                                hasBillPrint: 3
                            }).then(function (status) {
                                if (status) {
                                    paymentDeductFromVoucherOnPayAndClose();
                                }
                            }).then(function () {
                                zamanEposDb.epos_order.get({orderId: Number(anOrder.orderId)}).then(function (anOrder) {
                                    $('.page-loader').show();
                                    remotePayAndClose(anOrder);
                                });
                            });
                        }
                    },
                    '<span class="icon icon-book">&nbsp;<?php echo $this->lang->line('no') ?></span>': {
                        'class': 'black',
                        'action': function () {
                            zamanEposDb.epos_order.where("orderId").equals(Number(anOrder.orderId)).modify({
                                payment: zamanEposCart.listpayments(),
                                isPaid: 3,
                                status: 5,
                                changeAmount: Number(toCurrencyNoMoney(due)),
                                changeAsTips: $('#paymnetHasTips').is(":checked") ? 3 : 2,
                                hasBillPrint: 2
                            }).then(function (status) {
                                if (status) {
                                    paymentDeductFromVoucherOnPayAndClose();
                                }
                            }).then(function () {
                                zamanEposDb.epos_order.get({orderId: Number(anOrder.orderId)}).then(function (anOrder) {
                                    $('.page-loader').show();
                                    remotePayAndClose(anOrder);
                                });
                            });
                        }
                    },
                    '<span class="icon icon-cancel">&nbsp;<?php echo $this->lang->line('cancel') ?></span>': {
                        'class': 'red',
                        'action': function () {
                            playBeepSound();
                            $.confirm.hide();
                        }
                    }
                }
            });
        }
    }
    function paymentOnlineForwardToProcessing(theOrder) {
        if (typeof (theOrder) !== 'undefined') {
            var payments = theOrder.payment;
            payments.forEach(function (method) {
                if (method.type === 'Online') {
                    var onlineDetails = theOrder.onlinePaymentDetails;
                    if (jQuery.isEmptyObject(onlineDetails)) {
                        zamanEposDb.epos_order.where("orderId").equals(Number(theOrder.orderId)).modify({
                            isPaid: 2
                        }).then(function (status) {
                            if (status) {
                                zamanEposNavigator('verified', '<?php echo site_url('epos/paymentOnline/') ?>' + theOrder.orderId + '/' + theOrder.sid + '/' + theOrder.status + '/' + toCurrencyNoMoney(method.amount) + '/' + theOrder.hasBillPrint);
                                warning('<?php echo $this->lang->line('redirecting') ?>', '<?php echo $this->lang->line('redirecting_msg') ?>', '<?php echo $this->lang->line('close') ?>');
                            }
                        });
                    }
                }
            });
        }
    }

    function checkIfOnlinePaymentAttached(theOrder) {
        var payments = theOrder.payment;
        var online = false;
        payments.forEach(function (method) {
            if (method.type === 'Online') {
                online = true;
                var onlineDetails = theOrder.onlinePaymentDetails;
                if (!jQuery.isEmptyObject(onlineDetails)) {
                    online = false;
                }
            }
        });
        return online;
    }

    function remotePayAndClose(theOrder) {
        if (Number(theOrder.status) > 1) {
            if (checkInternetConnection()) {
                if (checkIfOnlinePaymentAttached(theOrder)) {
                    zamanEposDb.epos_order.get({orderId: Number(theOrder.orderId)}).then(function (nowTheOrder) {
                        paymentOnlineForwardToProcessing(nowTheOrder);
                    });
                } else {
                    return new Promise(function (resolve, reject) {
                        $.ajax('<?php echo site_url('api/payAndClose') ?>', {
                            type: 'post',
                            dataType: 'json',
                            data: {
                                theOrder: theOrder
                            },
                            error: function (xhr, textStatus) {
                                reject(textStatus);
                            },
                            success: function (data) {
                                resolve(data);
                            }
                        });
                    }).then(function (data) {
                        if (data.status) {
                            zamanEposPopupcloser();
                            if (Number(theOrder.status) >= 5) {
                                zamanEposCart.clearOnPayAndClose();
                                $('#loadedOrderInformation').text('<?php echo $this->lang->line('void_order') ?>');
                                zamanEposDb.epos_order.delete(theOrder.orderId);
                            } else {
                                zamanEposCart.clearOnPayAndCloseForSentInOrder();
                            }
                            if (theOrder.type === 'table') {
                                zamanEposDb.epos_table.where("tableNumber").equals(theOrder.orderInfo.tableNumber).modify({
                                    status: '2'
                                });
                            }
                            var isTrue = Number(theOrder.status) <= 4 ? true : false;
                            manageOrderListDisplay(theOrder, isTrue);
                        }
                    });
                }
            } else {
                zamanEposPopupcloser();
                var isTrue = Number(theOrder.status) <= 4 ? true : false;
                if (!isTrue) {
                    $('#loadedOrderInformation').text('<?php echo $this->lang->line('void_order') ?>');
                }
                manageOrderListDisplay(theOrder, isTrue);
                //alert('offline bill print');
            }
        }
    }
    function paymentDeductFromVoucherOnPayAndClose() {
        var payments = zamanEposCart.listpayments();
        if (payments.length > 0) {
            payments.forEach(function (method) {
                if (method.type === 'Voucher') {
                    var amountToDeduct = method.amount;
                    var fromCode = method.code;
                    var remainingBalance = 0;
                    zamanEposDb.epos_voucher.get({code: fromCode}).then(function (theVoucher) {
                        remainingBalance = Number(theVoucher.balance);
                    }).then(function () {
                        zamanEposDb.epos_voucher.where("code").equals(fromCode).modify({
                            balance: remainingBalance - amountToDeduct
                        });
                    });
                }
            });
        }
    }
</script>