<?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;"><?php echo $this->lang->line('add_new_expense') ?></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/saveExpense/', array('id' => 'expenseForm')); ?>
                <div class="form-group">
                    <label><?php echo $this->lang->line('ledger') ?></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><?php echo $this->lang->line('expense_amount') ?></label>
                    <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage', 'setting-pagination-keyboard')" name="expenseAmount" placeholder="<?php echo $this->lang->line('expense_amount') ?>" class="form-control">
                </div>
                <div class="form-group">
                    <label><?php echo $this->lang->line('vat_on_expense') ?></label>
                    <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage', 'setting-pagination-keyboard')" name="expenseVat" placeholder="<?php echo $this->lang->line('vat_on_expense') ?>" class="form-control">
                </div>
                <div class="form-group">
                    <label><?php echo $this->lang->line('withdrawn_from_till') ?></label>&nbsp;&nbsp;
                    <label><input data-error="#withdrawnFromTillError" type="radio" value="yes" id="withdrawnFromTillYes" name="withdrawnFromTill">&nbsp;<?php echo $this->lang->line('yes') ?></label>
                    &nbsp;&nbsp;<label><input data-error="#withdrawnFromTillError" type="radio" id="withdrawnFromTillNo" value="no" name="withdrawnFromTill">&nbsp;<?php echo $this->lang->line('no') ?></label>
                </div>
                <div id="withdrawnFromTillError"></div>
                <div class="form-group" id="withdrawnTypeBlock" style="display: none;">
                    <label>Alternative Source</label>&nbsp;&nbsp;
                    <label><input data-error="#withdrawnType " type="radio" value="Cash" name="withdrawnType">Cash</label>
                    <label><input data-error="#withdrawnType " type="radio" value="EFT" name="withdrawnType">EFT</label>
                    <label><input data-error="#withdrawnType " type="radio" value="Cheque" name="withdrawnType">Cheque</label>
                    <label><input data-error="#withdrawnType " type="radio" value="Voucher" name="withdrawnType">Voucher</label>
                </div>
                <div id="withdrawnTypeError"></div>
                <div class="tab-group config-submit">
                    <button type="submit" onclick="saveExpense('expenseForm')"><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"><?php echo $this->lang->line('expense') . ' ' . $this->lang->line('list') ?></th>
                </tr>
                <tr>
                    <th colspan="2"><input type="text" id="reportDateFrom" class="form-control" placeholder="Date Form" value="<?php echo $filterData[0]?>"></th>
                    <th colspan="2"><input type="text" id="reportDateTo" class="form-control" placeholder="Date To" value="<?php echo $filterData[0]?>"></th>
                    <th colspan="3"><button type="submit" class="btn btn-primary btn-large" style="width: 100%" onclick="filterExpenseReport()"><i class="icon icon-search text-center" ></i>&nbsp;<?php echo $this->lang->line('filter') . ' ' . sprintf($this->lang->line('dash_report'), $this->lang->line('expense')) ?></button></th>
                </tr>
                <tr class="table-bg">
                    <th><?php echo $this->lang->line('ledger') ?></th>
                    <th><?php echo $this->lang->line('expense_amount') ?></th>
                    <th><?php echo $this->lang->line('vat') ?></th>
                    <th><?php echo $this->lang->line('withdrawn_from_till') ?></th>
                    <th><?php echo $this->lang->line('ledger_type') ?></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;
                $totalExpenseVat = 0;
                $cashTotal = 0;
                $EFTTotal = 0;
                $chequeTotal = 0;
                $voucherTotal = 0;
                $cashTakenFromTill = 0;
                ?>
                <?php if (!empty($expenseList)): ?>

                    <?php foreach ($expenseList as $anExpense): ?>
                        <?php
                        if ($anExpense->withdrawnType === 'Cash') {
                            $cashTotal += $anExpense->expenseAmount;
                        }
                        if ($anExpense->withdrawnType === 'EFT') {
                            $EFTTotal += $anExpense->expenseAmount;
                        }
                        if ($anExpense->withdrawnType === 'Cheque') {
                            $chequeTotal += $anExpense->expenseAmount;
                        }
                        if ($anExpense->withdrawnType === 'Voucher') {
                            $voucherTotal += $anExpense->expenseAmount;
                        }
                        if ($anExpense->withdrawnFromTill === 'yes' && $anExpense->withdrawnType === 'Cash') {
                            $cashTakenFromTill += $anExpense->expenseAmount;
                        }
                        ?>
                        <tr>
                            <td><?php echo get_title('expenseledger', array('id' => $anExpense->ledger)) ?></td>
                            <td>
                                <?php
                                $totalexpenseAmount += $anExpense->expenseAmount;
                                echo to_currency($anExpense->expenseAmount);
                                ?>
                            </td>
                            <td>
                                <?php
                                $totalExpenseVat += $anExpense->expenseVat;
                                echo to_currency($anExpense->expenseVat);
                                ?>
                            </td>
                            <td><?php echo $anExpense->withdrawnFromTill ?></td>
                            <td><?php echo $anExpense->withdrawnType ?></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><?php echo to_currency($totalExpenseVat) ?></th>
                        <th>&nbsp;</th>
                        <th>&nbsp;</th>
                        <th>&nbsp;</th>
                        <th>&nbsp;</th>
                    </tr>
                <?php else: ?>
                    <tr>
                        <td colspan="7"><?php echo sprintf($this->lang->line('not_found'), $this->lang->line('expense')) ?></td>
                    </tr>
                <?php endif; ?>
                <tr>
                    <td colspan="7">
                        <table class="report-table">
                            <tr>
                                <td style="width: 25%;border: none;">&nbsp;</td>
                                <td style="width: 50%; border: none;">
                                    <table class="report-table  text-center">
                                        <caption><?php echo sprintf($this->lang->line('dash_summary'), $this->lang->line('expense')) ?></caption>
                                        <tr class="table-bg">
                                            <th><?php echo $this->lang->line('total') . ' ' . $this->lang->line('expense') ?></th>
                                            <th><?php echo to_currency($totalexpenseAmount) ?></th>
                                        </tr>
                                        <tr>
                                            <td><?php echo $this->lang->line('cash') ?></td>
                                            <td><?php echo to_currency($cashTotal) ?></td>
                                        </tr>
                                        <tr>
                                            <td><?php echo $this->lang->line('eft') ?></td>
                                            <td><?php echo to_currency($EFTTotal) ?></td>
                                        </tr>
                                        <tr>
                                            <td><?php echo $this->lang->line('cheque') ?></td>
                                            <td><?php echo to_currency($chequeTotal) ?></td>
                                        </tr>
                                        <tr>
                                            <td><?php echo $this->lang->line('voucher') ?></td>
                                            <td><?php echo to_currency($voucherTotal) ?></td>
                                        </tr>
                                        <tr>
                                            <td><?php echo $this->lang->line('vat_on_expense') ?></td>
                                            <td><?php echo to_currency($totalExpenseVat) ?></td>
                                        </tr>
                                        <tr class="table-bg">
                                            <th><?php echo $this->lang->line('cash_taken_from_till') ?></th>
                                            <th><?php echo to_currency($cashTakenFromTill) ?></th>
                                        </tr>
                                    </table>
                                </td>
                                <td style="width: 25%;border: none;">&nbsp;</td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </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"><?php echo $this->lang->line('add_new_ledger') ?></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/saveExpenseLedger/', 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"><?php echo $this->lang->line('ledger') ?></th>
                    <th><?php echo $this->lang->line('amount') ?></th>
                    <th><?php echo $this->lang->line('vat') ?></th>
                </tr>
                <?php if (!empty($ledgers)): ?>
                    <?php
                    $aggregatedLedgerTotalExpense = 0;
                    $aggregatedLedgerTotalVat = 0;
                    ?>
                    <?php foreach ($ledgers as $aListItem): ?>
                        <?php $ledgerTotalExpense = getExpenseColumnSum($aListItem->id, 'expenseAmount') ?>
                        <?php $ledgerTotalVat = getExpenseColumnSum($aListItem->id, 'expenseVat'); ?>
                        <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>
                            <td>
                                <?php
                                if ($ledgerTotalVat->expenseVat) {
                                    $aggregatedLedgerTotalVat += $ledgerTotalVat->expenseVat;
                                    echo to_currency($ledgerTotalVat->expenseVat);
                                } 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>
                        <th><?php echo to_currency($aggregatedLedgerTotalVat) ?></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('expense', '<?php echo site_url('report/expense') ?>', 'expense');
                            } 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('expense', '<?php echo site_url('report/expense') ?>','expense');
                        } 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/checkledger') ?>",
                        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('expense', '<?php echo site_url('report/expense/') ?>' + reportDateFrom + '/' + reportDateTo, 'expense');
    }
    function deleteExpense(id) {
        $.ajax({
            url: '<?php echo site_url('report/deleteExpense/') ?>' + 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>