<?php $this->load->view('settings/partials/header') ?>
<div class="window-content" id="WindowContent">
    <div class="page-loader" style="display: none;"></div>
    <div style="width: 100%;">
        <?php
        $orderStatus = array('2' => 'Pending', '3' => 'Accepted', '4' => 'Rejected');
        $orderStatusColor = array('2' => '#f900ff', '3' => '#009e12', '4' => '#ff0000')
        ?>
        <table class="text-center report-table" id="printReportEntire">
            <thead class="table-bg">
                <tr class="no-print">
                    <?php if (count($branches) > 1 && $this->session->userdata('group') <= 3): ?>
                        <th colspan="2">
                            <select class="form-control" id="reportBranch">
                                <?php foreach ($branches as $aBranch): ?>
                                    <option value="<?php echo $aBranch->id ?>" <?php trim($filterData[6] && $filterData[6] === $aBranch->id) ? print 'selected="selected"' : '' ?>><?php echo $aBranch->title . ' - ' . $this->config->item('general_name') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </th>
                    <?php else: ?>
                        <th colspan="2">&nbsp;</th>
                    <?php endif ?>
                    <th colspan="1">
                        <select id='reportOrderType' class="form-control">
                            <option value="">Select type</option>
                            <option value='collection' <?php isset($filterData) && $filterData[4] == 'collection' ? print'selected="selected"' : '' ?>><?php echo $this->lang->line('collection') ?></option>
                            <option value='delivery' <?php isset($filterData) && $filterData[4] == 'delivery' ? print'selected="selected"' : '' ?>><?php echo $this->lang->line('delivery') ?></option>
                        </select>
                    </th>
                    <th colspan="2"><input type="text" id="reportDateFrom" class="form-control" placeholder="<?php echo $this->lang->line('date_from') ?>" value="<?php !empty($filterData) && ($filterData[0]) ? print $filterData[0] : '' ?>"></th>
                    <th colspan="1"><input type="text" id="reportDateTo" class="form-control" placeholder="<?php echo $this->lang->line('date_to') ?>" value="<?php !empty($filterData) && ($filterData[1]) ? print $filterData[1] : '' ?>"></th>
                    <th colspan="1"><input type="text" id='reportReference' class="form-control" placeholder="<?php echo $this->lang->line('ref') ?>" value="<?php !empty($filterData) && ($filterData[2]) ? print $filterData[2] : '' ?>"></th>
                    <th colspan="2"><button type="submit" class="btn btn-primary btn-large" style="width: 100%" onclick="filterOnlineReport()"><i class="icon icon-search text-center" ></i>&nbsp;<?php echo sprintf($this->lang->line('dash_report'), $this->lang->line('filter')) ?></button></th>
                </tr>
                <tr>
                    <th><?php echo $this->lang->line('id') ?></th>
                    <th><?php echo $this->lang->line('customer') ?></th>
                    <th><?php echo $this->lang->line('type') ?></th>
                    <th><?php echo $this->lang->line('date') ?></th>
                    <th>Service Charge</th>
                    <th><?php echo $this->lang->line('total') ?></th>
                    <th><?php echo $this->lang->line('payment') ?></th>
                    <th style="width: 120px"><?php echo $this->lang->line('status') ?></th>
                    <th class="no-print" style="width: 120px"><?php echo $this->lang->line('action') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php $aggregateGrandTotal = 0; ?>
                <?php $aggregateServiceChargeTotal = 0; ?>
                <?php if (!empty($orderList)): ?>
                    <?php foreach ($orderList as $anOrder): ?>
                        <tr>
                            <td><?php echo $anOrder->sid . '/' . $anOrder->orderId ?></td>
                            <td>
                            <?php if(!empty($anOrder->orderInfo) && !empty(unserialize($anOrder->orderInfo))):?>
                                <?php $customerInfo = unserialize($anOrder->orderInfo) ?>
                                <?php echo $anOrder->type === 'table' ? 'Table-' . $customerInfo['tableNumber'] : ucfirst($customerInfo['name']) ?>
                            <?php endif;?>
                            </td>
                            <td><?php echo ucfirst($anOrder->type) ?></td>

                            <td><?php echo date('d/m/Y', strtotime($anOrder->closingData)) ?></td>
                            <td>
                                <?php
                                $aggregateServiceChargeTotal += to_currency_no_money($anOrder->serviceCharge);
                                echo to_currency($anOrder->serviceCharge);
                                ?>
                            </td>   
                            <td>
                                <?php
                                $aggregateGrandTotal += to_currency_no_money($anOrder->grandTotal);
                                echo to_currency($anOrder->grandTotal);
                                ?>
                            </td>
                            <td>
                                <?php $shouldDelete = true; ?>
                                <?php if ($anOrder->isPaid === '3'): ?>
                                    <span><?php echo $this->lang->line('paid') ?></span>
                                    <?php if ($anOrder->status_online === '4'): ?>
                                        <?php $payment = (unserialize($anOrder->payment)); ?>
                                        <?php if ($payment[0]['type'] === 'Online'): ?>
                                            <?php $shouldDelete = false; ?>
                                            <?php $onlinePaymentDetails = unserialize($anOrder->onlinePaymentDetails); ?>
                                            <span class="icon icon-level-up" onclick="refundOnlinePayment('<?php echo $onlinePaymentDetails['reference_id'] ?>', '<?php echo $anOrder->sid ?>')"></span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span><?php echo $this->lang->line('unpaid') ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <select class="form-control" style="height: 25px; width:120px; color: <?php echo $orderStatusColor[$anOrder->status_online] ?>" onchange="changeOnlineOrderStatus(this.value, '<?php echo $anOrder->sid ?>')">
                                    <option value="2" <?php $anOrder->status_online == '2' ? print'selected="selected"' : '' ?> style="color:<?php echo $orderStatusColor['2'] ?>">Pending</option>
                                    <option value="3" <?php $anOrder->status_online == '3' ? print'selected="selected"' : '' ?> style="color:<?php echo $orderStatusColor['3'] ?>">Confirmed</option>
                                    <option value="4" <?php $anOrder->status_online == '4' ? print'selected="selected"' : '' ?> style="color:<?php echo $orderStatusColor['4'] ?>">Rejected</option>
                                </select>
                            </td>
                            <td class="no-print" style="width: 120px;">
                                <i class="icon icon-eye" style="color: #078042;font-size: 20px" onclick="zamanOrderDetailPopupController('<?php echo $anOrder->sid ?>')"></i>
                                <?php if ($anOrder->status_online == '3'): ?>
                                    &nbsp;&nbsp;&nbsp;&nbsp;<i class="icon icon-print" style="color: #078042; font-size: 20px;" onclick="printBill('<?php echo $anOrder->sid ?>')"></i>
                                <?php endif; ?>
                                <?php if ($this->session->userdata('group') <= 5 && $shouldDelete && $anOrder->status_online > 2): ?>
                                    &nbsp;&nbsp;&nbsp;&nbsp;<i class="icon icon-trash" style="color: #078042;font-size: 20px;" onclick="deleteOrder('<?php echo $anOrder->sid ?>')"></i>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9"><?php echo sprintf($this->lang->line('not_found'), $this->lang->line('order')) ?></td>
                    </tr>
                <?php endif; ?>
                <tr class="table-bg">
                    <th>&nbsp;</th>
                    <th>&nbsp;</th>
                    <th>&nbsp;</th>
                    <th><strong><?php echo $this->lang->line('all_total') ?></strong></th>
                    <th><strong>Service Charge<br/><span><?php echo to_currency($aggregateServiceChargeTotal); ?></span></strong></th>
                    <th><strong><?php echo $this->lang->line('grand_total') ?><br/><span><?php echo to_currency($aggregateGrandTotal); ?></span></strong></th>
                    <th>&nbsp;</th>
                    <th>&nbsp;</th>
                    <th>&nbsp;</th>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<?php $this->load->view('order') ?>
<?php $this->load->view('settings/partials/footer') ?>
<script type="text/javascript">
    $('document').ready(function () {
        if ($('#reportDateFrom').val() === 'verified') {
            $('#reportDateFrom').val('');
        }
        $('#reportDateFrom').datetimepicker({
            timepicker: false,
            format: 'd-m-Y',
            maxDate: '<?php echo date('d/m/Y', strtotime('today')) ?>',
            formatDate: 'Y/m/d'
        });
        $('#reportDateTo').datetimepicker({
            timepicker: false,
            format: 'd-m-Y',
            maxDate: '<?php echo date('d/m/Y', strtotime('today')) ?>',
            formatDate: 'Y/m/d'
        });
    });
    function filterOnlineReport() {
        if (!$('.page-loader').is(":visible")) {
            var reportDateFrom = $.trim($('#reportDateFrom').val()) ? $('#reportDateFrom').val() : 0;
            var reportDateTo = $.trim($('#reportDateTo').val()) ? $('#reportDateTo').val() : 0;
            var reportReference = $.trim($('#reportReference').val()) ? $('#reportReference').val() : 0;
            var reportOrderSource = 'online';
            var reportOrderType = $.trim($('#reportOrderType').val()) ? $('#reportOrderType').val() : 0;
            ;
            var reportOrderPayment = 0;
            var reportBranch = $.trim($('#reportBranch').val()) ? $('#reportBranch').val() : 0;
            var splited = [];
            if (reportReference !== 0) {
                splited = reportReference.split('/');
                reportReference = splited[0] + '-' + splited[1];
            }
            zamanEposNavigator('onlineReportIndex', '<?php echo site_url('report/online/') ?>' + reportDateFrom + '/' + reportDateTo + '/' + reportReference + '/' + reportOrderSource + '/' + reportOrderType + '/' + reportOrderPayment + '/' + reportBranch, 'onlineReportIndex');
        }
    }
    function printBill(id) {
        if (!$('.page-loader').is(":visible")) {
            var DetailedorderId = $('#detailedOrderId').val();
            var sid = Number(id) > 0 ? Number(id) : Number(DetailedorderId);
            $.ajax({
                url: '<?php echo site_url('api/printer') ?>',
                data: {
                    sid: sid,
                    type: 4
                },
                type: 'POST',
                dataType: 'json',
                beforeSend: function () {
                    $('.page-loader').show();
                },
                success: function (response) {
                    $('.page-loader').hide();
                    if (response.status) {
                        zamanEposPopupcloser();
                    } else {
                        warning('<?php echo $this->lang->line('error') ?>', '<?php echo $this->lang->line('data_saving_failed') ?>', '<?php echo $this->lang->line('close') ?>');
                    }
                }
            });
        }
    }
    function deleteOrder(id) {
        if (!$('.page-loader').is(":visible")) {
            var DetailedorderId = $('#detailedOrderId').val();
            var sid = Number(id) > 0 ? Number(id) : Number(DetailedorderId);
            if (checkInternetConnection()) {
                $.confirm({
                    title: '<?php echo $this->lang->line('warning') ?>',
                    message: '<?php echo $this->lang->line('delete_order_msg') ?>',
                    buttons: {
                        '<?php echo $this->lang->line('yes') ?>': {
                            'class': 'primary',
                            'action': function () {
                                $.ajax({
                                    url: '<?php echo site_url('report/deleteOrder/') ?>' + sid,
                                    type: 'Get',
                                    dataType: 'json',
                                    beforeSend: function () {
                                        $('.page-loader').show();
                                    },
                                    success: function (response) {
                                        zamanEposPopupcloser();
                                        $('.page-loader').hide();
                                        if (response.status) {
                                            zamanEposNavigator('onlineReportIndex', '<?php echo $refresh ?>', 'onlineReportIndex');
                                        } else {
                                            warning('<?php echo $this->lang->line('error') ?>', 'Deleting order failed! Please try again', '<?php echo $this->lang->line('close') ?>');
                                        }
                                    }
                                });
                            }
                        },
                        '<?php echo $this->lang->line('no') ?>': {
                            'class': 'positive',
                            'action': function () {}
                        }
                    }
                });

            } else {
                warning('<?php echo $this->lang->line('lost_connection') ?>', '<?php echo $this->lang->line('lost_connection_message') ?>', '<?php echo $this->lang->line('close') ?>');
            }
        }
    }
    function refundOnlinePayment(charge, sid) {
        $.confirm({
            title: 'Refund Warning',
            message: 'Are you sure that you want to refund the amount',
            buttons: {
                'Yes': {
                    'class': 'primary',
                    'action': function () {
                        $.ajax({
                            url: '<?php echo site_url('report/refund') ?>',
                            type: 'POST',
                            dataType: 'json',
                            data: {'charge': charge, 'sid': sid},
                            beforeSend: function () {
                                $('.page-loader').show();
                            },
                            success: function (response) {
                                $('.page-loader').hide();
                                if (response.status) {
                                    zamanEposNavigator('onlineReportIndex', '<?php echo $refresh ?>', 'onlineReportIndex');
                                } else {
                                    warning('<?php echo $this->lang->line('error') ?>', response.message, '<?php echo $this->lang->line('close') ?>')
                                }
                            }
                        });
                    }
                },
                'No': {
                    'class': 'positive',
                    'action': function () {}
                }
            }
        });
    }
    function changeOnlineOrderStatus(action, sid) {
        if (Number(action) >= 3 && Number(action) <= 4) {
            var data = {};
            var url = '';
            if (Number(action) === 3) {
                data.sid = sid;
                data.extraTime = 0;
                url = '<?php echo site_url('api/acceptOnlineOrder') ?>';
            }
            if (Number(action) === 4) {
                data.sid = sid;
                data.rejectMsg = '';
                url = '<?php echo site_url('api/rejectOnlineOrder') ?>';
            }
            $.ajax({
                url: url,
                data: data,
                type: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response.status) {
                        zamanEposNavigator('onlineReportIndex', '<?php echo $refresh ?>', 'onlineReportIndex');
                    } else {
                        warning('<?php echo $this->lang->line('error') ?>', 'There some internal problem', '<?php echo $this->lang->line('close') ?>');
                    }
                }
            });
        } else {
            warning('Warning', 'You can not make order pending', 'Close')
        }
    }
</script>