<?php $this->load->view('settings/partials/header') ?>
<div class="window-content">
    <div class="page-loader" style="display: none;"></div>
    <div class="pane-group">
        <?php $this->load->view('settings/partials/sidebar') ?>
        <div class="pane content-configuration">
            <?php if ($this->session->userdata('group') <= 5): ?>
                <div class="caption" onclick="zamanEposBlockHideAndShow('expenseFormBlock')">
                    <div class="caption-inner" style="padding: 9px;">Add new income</div>
                </div>
            <?php else: ?>
                <div class="caption">
                    <div class="caption-inner" style="padding: 9px;"><?php echo $this->lang->line('expense') ?></div>
                </div>
            <?php endif; ?>
            <div class="block-inner" id="expenseFormBlock" style="display: none;">
                <?php echo form_open('report/saveIncome/', array('id' => 'incomeForm')); ?>
                <div class="form-group">
                    <label>Source</label>
                    <select name="ledger" class="form-control" data-error="#ledgerError">
                        <option value="0"><?php echo $this->lang->line('select') ?></option>
                        <?php if (!empty($ledgers)): ?>
                            <?php foreach ($ledgers as $aLedger): ?>
                                <option value="<?php echo $aLedger->id ?>"><?php echo $aLedger->title ?></option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div id="ledgerError"></div>
                <div class="form-group">
                    <label>Income</label>
                    <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage', 'setting-pagination-keyboard')" name="expenseAmount" placeholder="Income amount" class="form-control">
                </div>
                <div class="tab-group config-submit">
                    <button type="submit" onclick="saveExpense('incomeForm')"><span class="icon icon-folder"></span>&nbsp;<?php echo $this->lang->line('save') ?></button>
                </div>
                <?php echo form_close() ?>
            </div>
            <table class="text-center report-table">
                <tr class="table-bg">
                    <th colspan="7">Income List</th>
                </tr>
                <tr>
                    <th colspan="1"><input type="text" id="reportDateFrom" class="form-control" placeholder="Date Form" value="<?php echo $filterData[0] ?>"></th>
                    <th colspan="1"><input type="text" id="reportDateTo" class="form-control" placeholder="Date To" value="<?php echo $filterData[0] ?>"></th>
                    <th colspan="2"><button type="submit" class="btn btn-primary btn-large" style="width: 100%" onclick="filterExpenseReport()"><i class="icon icon-search text-center" ></i>&nbsp;Filter Income Report</button></th>
                </tr>
                <tr class="table-bg">
                    <th>Source Income</th>
                    <th>Income</th>
                    <th><?php echo $this->lang->line('date') . '  ' . $this->lang->line('time') ?></th>
                    <?php if ($this->session->userdata('group') <= 3): ?>
                        <th><?php echo $this->lang->line('delete') ?></th>
                    <?php endif; ?>
                </tr>
                <?php $totalexpenseAmount = 0; ?>
                <?php if (!empty($expenseList)): ?>
                    <?php foreach ($expenseList as $anExpense): ?>
                        <tr>
                            <td><?php echo get_title('incomeledger', array('id' => $anExpense->ledger)) ?></td>
                            <td>
                                <?php
                                $totalexpenseAmount += $anExpense->expenseAmount;
                                echo to_currency($anExpense->expenseAmount);
                                ?>
                            </td>

                            <td><?php echo date('d-m-Y h:i', strtotime($anExpense->created_at)) ?></td>
                            <?php if ($this->session->userdata('group') <= 3): ?>
                                <td onclick="deleteExpense('<?php echo $anExpense->id ?>')"><span class="icon icon-trash"></span></td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                    <tr class="table-bg">
                        <th><?php echo $this->lang->line('total') ?></th>
                        <th><?php echo to_currency($totalexpenseAmount) ?></th>
                        <th>&nbsp;</th>
                        <th>&nbsp;</th>
                    </tr>
                <?php else: ?>
                    <tr>
                        <td colspan="4">No income</td>
                    </tr>
                <?php endif; ?>
            </table>
        </div>
        <div class="pane-one-fourth content-configuration">
            <?php if ($this->session->userdata('group') <= 5): ?>
                <div class="caption" onclick="zamanEposBlockHideAndShow('expenseLedgerFormBlock')">
                    <div class="caption-inner" style="padding: 9px">Add new source</div>
                </div>
            <?php else: ?>
                <div class="caption">
                    <div class="caption-inner" style="padding: 9px"><?php echo $this->lang->line('ledger') ?></div>
                </div>
            <?php endif; ?>
            <div class="block-inner" id="expenseLedgerFormBlock" style="display: none;">
                <?php echo form_open('report/saveIncomeLedger/', array('id' => 'expenseLedgerForm')); ?>
                <div class="form-group">
                    <label><?php echo $this->lang->line('title') ?></label>
                    <input type="text" name="title" onfocus="setTargetKeyboard('keyboard-fixed-orderpage', 'setting-pagination-keyboard')" id="ledgerTitle" class="form-control">
                </div>
                <div class="tab-group config-submit">
                    <button type="submit" onclick="saveLedger('expenseLedgerForm')"><span class="icon icon-folder"></span>&nbsp;<?php echo $this->lang->line('save') ?></button>
                </div>
                <?php echo form_close() ?>
            </div>
            <table class="text-center report-table">
                <tr class="table-bg">
                    <th class="text-left">Source</th>
                    <th>Income</th>
                </tr>
                <?php if (!empty($ledgers)): ?>
                    <?php
                    $aggregatedLedgerTotalExpense = 0;
                    $aggregatedLedgerTotalVat = 0;
                    ?>
                    <?php foreach ($ledgers as $aListItem): ?>
                        <?php $ledgerTotalExpense = getIncomeColumnSum($aListItem->id, 'expenseAmount') ?>
                        <tr>
                            <td class="text-left"><?php echo $aListItem->title ?></td>
                            <td>
                                <?php
                                if ($ledgerTotalExpense->expenseAmount) {
                                    $aggregatedLedgerTotalExpense += $ledgerTotalExpense->expenseAmount;
                                    echo to_currency($ledgerTotalExpense->expenseAmount);
                                } else {
                                    echo to_currency(0);
                                }
                                ?>
                            </td>

                        </tr>
                    <?php endforeach; ?>
                    <tr class="table-bg">
                        <th class="text-left">Total:</th>
                        <th><?php echo to_currency($aggregatedLedgerTotalExpense) ?></th>
                    </tr>
                <?php endif; ?>
            </table>
        </div>
    </div>
</div>
<?php $this->load->view('settings/partials/footer') ?>
<script type="text/javascript">
    $(document).ready(function () {
        $('input[type=radio][name=withdrawnFromTill]').change(function () {
            if (this.value == 'no') {
                $('#withdrawnTypeBlock').show();
            } else {
                $('#withdrawnTypeBlock').hide();
            }
        });
        $('#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 saveExpense(formId) {
        if (!$('.page-loader').is(":visible")) {
            $('#' + formId).validate({
                submitHandler: function () {
                    var myform = document.getElementById(formId);
                    var formdata = new FormData(myform);
                    $.ajax({
                        url: $('#' + formId).attr('action'),
                        data: formdata,
                        cache: false,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        dataType: 'json',
                        success: function (response) {
                            if (response.status) {
                                zamanEposNavigator('income', '<?php echo site_url('report/income') ?>', 'income');
                            } else {
                                warning('Error', response.message, 'Close');
                            }
                        }
                    });
                },
                errorClass: "has-error",
                highlight: function (e) {
                    $(e).closest('.form-group').addClass('has-error');
                },
                unhighlight: function (e) {
                    $(e).closest('.form-group').removeClass('has-error');
                },
                rules: {
                    ledger: {
                        required: true
                    },
                    expenseAmount: {number: true, required: true},
                    expenseVat: {number: true},
                    withdrawnFromTill: {required: true},
                    withdrawnType: {required: '#withdrawnFromTillNo:checked'}
                },
                messages: {
                    ledger: "<?php echo $this->lang->line('select_ledger') ?>",
                    expenseAmount: "<?php echo $this->lang->line('expense_total_in_amount_only') ?>",
                    expenseVat: "<?php echo $this->lang->line('insert_vat_on_expense') ?>",
                    withdrawnFromTill: "<?php echo $this->lang->line('mention_spent_from_cash') ?>",
                    withdrawnType: '<?php echo $this->lang->line('how_did_pay') ?>'
                },
                errorPlacement: function (error, element) {
                    errorPlacement(error, element);
                }
            });
        }
    }
    function saveLedger(formId) {
        $('#' + formId).validate({
            submitHandler: function () {
                var myform = document.getElementById(formId);
                var formdata = new FormData(myform);
                $.ajax({
                    url: $('#' + formId).attr('action'),
                    data: formdata,
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    dataType: 'json',
                    success: function (response) {
                        if (response.status) {
                            zamanEposNavigator('income', '<?php echo site_url('report/income') ?>', 'income');
                        } else {
                            warning('Error', response.message, 'Close');
                        }
                    }
                });
            },
            errorClass: "has-error",
            highlight: function (e) {
                $(e).closest('.form-group').addClass('has-error');
            },
            unhighlight: function (e) {
                $(e).closest('.form-group').removeClass('has-error');
            },
            rules: {
                title: {
                    required: true,
                    remote: {
                        url: "<?php echo site_url('report/checkIncomeledger') ?>",
                        type: "post",
                        data: {
                            value: function () {
                                return $("#ledgerTitle").val();
                            },
                            column: 'title'
                        }
                    }
                }
            },
            messages: {
                title: '<?php echo sprintf($this->lang->line('item_required'), $this->lang->line('ledger')) ?>'
            },
            errorPlacement: function (error, element) {
                errorPlacement(error, element);
            }
        });
    }
    function filterExpenseReport() {
        var reportDateFrom = $.trim($('#reportDateFrom').val()) ? $('#reportDateFrom').val() : 0;
        var reportDateTo = $.trim($('#reportDateTo').val()) ? $('#reportDateTo').val() : 0;
        zamanEposNavigator('income', '<?php echo site_url('report/income/') ?>' + reportDateFrom + '/' + reportDateTo, 'income');
    }
    function deleteExpense(id) {
        $.ajax({
            url: '<?php echo site_url('report/deleteIncome/') ?>' + id,
            type: 'GET',
            dataType: 'json',
            beforeSend: function (xhr) {
                $('.page-loader').show();
            },
            success: function (response) {
                $('.page-loader').hide();
                if (response.status) {
                    filterExpenseReport();
                } else {
                    warning('<?php echo $this->lang->line('error') ?>', response.message, '<?php echo $this->lang->line('close') ?>');
                }
            }
        });
    }
</script>