<?php
if (
    !isset($permissions['finance']['invoices'])
    || isset($permissions['finance']['invoices'])
    && $permissions['finance']['invoices'] == 0
) redirect('admin/dashboard');

?>
<script src="<?php echo site_url(); ?>assets/js/plugin/datatables1_10_7/jquery.dataTables.min.js"></script>
<script src="<?php echo site_url(); ?>assets/js/plugin/datatables/dataTables.colReorder.min.js"></script>
<script src="<?php echo site_url(); ?>assets/js/plugin/datatables/dataTables.colVis.min.js"></script>
<script src="<?php echo site_url(); ?>assets/js/plugin/datatables/dataTables.tableTools.min.js"></script>
<script src="<?php echo site_url(); ?>assets/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
<script src="<?php echo site_url(); ?>assets/js/plugin/datatable-responsive/datatables.responsive.min.js"></script>

<script src="//cdn.datatables.net/buttons/1.6.1/js/dataTables.buttons.min.js" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/buttons/1.6.1/js/buttons.flash.min.js" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/buttons/1.6.1/js/buttons.html5.min.js" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/buttons/1.6.1/js/buttons.print.min.js" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/buttons/1.6.1/js/buttons.colVis.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.lordicon.com/libs/mssddfmo/lord-icon-2.1.0.js"></script>
<div id="main p-0" role="main">
    <!-- <div class="header-bg shadow-sm p-0" style="background: url(https://images.pexels.com/photos/1475033/pexels-photo-1475033.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"> -->
    <!-- <div class="header-bg shadow-lg p-0" style="background: url(https://images.pexels.com/photos/1487834/pexels-photo-1487834.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></div> -->
    <div id="content" style=" padding-top: 0px; ">
        <div class="container">
            <div class="row mt-3 justify-content-center">
                <div class="header_invoice_wrapper shadow">
                    <div class="fs-1 w-25 text-white d-flex align-items-center"><?php echo $this->lang->line('all_customers'); ?> Online</div class="fs-1">
                    <div class="new_invoice_btn">
                        <button type="button" class="shadow-lg add_invoice_button" data-bs-toggle="modal" data-bs-target="#createPaymentModal" title="<?php echo $this->lang->line('new_customer'); ?>">
                            <lord-icon src="https://cdn.lordicon.com/mecwbjnp.json" trigger="loop" delay="1000" colors="primary:#356359,secondary:#00bcd4" style="width:32px;height:32px">
                            </lord-icon>
                            <span class="pt-1 text-dark">
                                <?php echo $this->lang->line('new_customer'); ?>
                            </span>
                        </button>
                        <button type="button" class="shadow-lg excel_exporter cancel_invoice p-2" style="width: 50px;" data-bs-toggle="collapse" href="#date_search" role="button" aria-expanded="false" aria-controls="date_search">
                            <i class="fa fa-search"></i></button>
                        <button type="button" class="shadow-lg excel_exporter" data-bs-toggle="modal" data-bs-target="#ExcelExportModal">
                            <i class="far fa-file-excel "></i>
                            <!-- <lord-icon src="https://cdn.lordicon.com/nocovwne.json" trigger="loop" delay="1000" colors="primary:#356359,secondary:#00bcd4" style="width:32px;height:32px">
                                </lord-icon> -->
                            <!-- <span class="pt-1 text-dark">
                                    Excel
                                </span> -->
                        </button>
                        <button type="button" class="shadow-lg excel_exporter cancel_invoice p-2" style="width: 50px;" data-bs-toggle="modal" id="deleteInvoiceButton" rel-customer="-1" data-bs-target="#DeleteInvoice">
                            <i class="fas fa-file-pdf text-warning"></i>
                        </button>
                        <button type="button" class="shadow-lg excel_exporter cancel_invoice p-2" style="width: 50px;" data-bs-toggle="modal" id="deleteInvoiceButton" rel-customer="-1" data-bs-target="#DeleteInvoice">
                            <i class="fas fa-copy text-primary"></i>
                        </button>
                        <button type="button" class="shadow-lg excel_exporter cancel_invoice p-2" style="width: 50px;" data-bs-toggle="modal" id="deleteInvoiceButton" rel-customer="-1" data-bs-target="#DeleteInvoice">
                            <i class="pt-1 me-1 fas fa-trash-alt text-danger"></i>
                        </button>
                        <button type="button" class="shadow-lg excel_exporter view_invoice p-2" style="width: 50px;" data-bs-toggle="modal" id="viewInvoiceButton" rel-customer="-1" data-bs-target="#DeleteInvoice">
                            <i class="pt-1 me-1 fas fa-eye text-success"></i>
                        </button>
                    </div>
                </div>
                <div class="collapse w-100" id="date_search">
                    <div class="date-searchWrapper">
                        <div class="card p-3 w-25">

                            <form method="POST" action="<?php echo site_url(); ?>admin/customers/customersOnline">
                                <div>
                                    <div class="form-group">
                                        <input type="text" class="form-control datepicker" name="from_date" id="from_date" value="<?php echo date('d/m/Y', strtotime($date_from)); ?>" autocomplete="OFF" placeholder="<?php echo $this->lang->line('from_date'); ?>">
                                    </div>
                                </div>
                                <div>
                                    <div class="form-group">
                                        <input type="text" class="form-control datepicker" name="to_date" id="to_date" value="<?php echo date('d/m/Y', strtotime($date_to)); ?>" autocomplete="OFF" placeholder="<?php echo $this->lang->line('to_date'); ?>">
                                    </div>
                                </div>
                                <div>
                                    <button type="submit" class="btn btn-success">
                                        <?php echo $this->lang->line('search'); ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
            </div>

            <div class="row">
                <hr class="bg-white mt-5" style="border-radius: 30px; padding: 2px;" />
                <div class=" table-responsive card card-body">
                    <table class="table table-sm" id="dt_basic2">
                        <thead>
                            <th>#</th>
                            <th>#</th>
                            <th><?php echo $this->lang->line('name'); ?></th>
                            <th><?php echo $this->lang->line('address'); ?></th>
                            <th><?php echo $this->lang->line('date'); ?></th>
                            <th><?php echo $this->lang->line('admin'); ?></th>
                        </thead>
                        <tbody>
                            <?php foreach ($sessions as $session) { ?>
                                <tr>
                                    <td><?php echo $session->id; ?></td>
                                    <td><?php echo $session->customerId; ?></td>
                                    <td>
                                        <?php if (isset($customers[$session->customerId])) { ?>
                                            <strong><?php echo $customers[$session->customerId]->customerName; ?></strong>
                                        <?php } else { ?>
                                            <strong><?php echo getUserName($session->customerId); ?></strong>
                                        <?php }; ?>
                                    </td>
                                    <td><?php echo $session->ip_address; ?></td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($session->session_date)); ?></td>
                                    <td><?php if ($session->isAdmin == 1) {
                                            echo $this->lang->line('yes');
                                        } else {
                                            echo $this->lang->line('no');
                                        }; ?></td>
                                </tr>
                            <?php }; ?>
                        </tbody>
                        <tfoot>
                            <!-- <tr>
                                        <td colspan="2"></td>
                                        <td><strong><?php echo number_format($balance, 2); ?></strong></td>
                                        <td colspan="3"></td>
                                    </tr> -->
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.5.2/bootbox.min.js" integrity="sha512-RdSPYh1WA6BF0RhpisYJVYkOyTzK4HwofJ3Q7ivt/jkpW6Vc8AurL1R+4AUcvn9IwEKAPm/fk7qFZW3OuiUDeg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/css/bootstrap-datepicker.css">
<script>
    $(document).ready(function() {
        // $('#dt_basic2').DataTable({
        //     "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'dt-buttons col-sm-6 col-xs-12 hidden-xs'l>r>" +
        //         "t" +
        //         "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
        //     "buttons": [],
        //     "processing": false,
        //     "bStateSave": false,
        //     "dom": 'Blfrtip',
        //     "pagingType": "full_numbers",
        //     "lengthMenu": [
        //         [10, 25, 50, -1],
        //         [10, 25, 50, "הכל"]
        //     ],
        //     "pageLength": 20,
        //     "sPaginationType": "full_numbers",
        //     "iDisplayLength": 10,
        //     "sScrollY": 500,
        //     "bScrollCollapse": true,
        //     "oLanguage": {
        //         "sProcessing": "מעבד...",
        //         "sZeroRecords": "לא נמצאו רשומות מתאימות",
        //         "sInfo": "_START_ עד _END_ מתוך _TOTAL_ רשומות",
        //         "sInfoEmpty": "0 עד 0 מתוך 0 רשומות",
        //         "sInfoFiltered": "(מסונן מסך _MAX_  רשומות)",
        //         "sInfoPostFix": "",
        //         "sUrl": "",
        //         "oPaginate": {
        //             "sFirst": "ראשון",
        //             "sPrevious": "קודם",
        //             "sNext": "הבא",
        //             "sLast": "אחרון"
        //         }
        //     },
        //     orderCellsTop: true,
        //     fixedHeader: false,
        //     searching: false
        // });

        $(document).on('click', '#dt_basic2 tbody tr', function() {
            let elem = $(this);
            let rowAttr = elem.attr('rel-customer');
            $('tr').css('background-color', "white");
            elem.css('background-color', "#e3edff")
            $('#deleteInvoiceButton').css('border-color', "#e9200c");
            $('#viewInvoiceButton').css('border-color', "#27b980");

            $('#deleteInvoiceButton').attr('rel-customer', rowAttr);
            $('#viewInvoiceButton').attr('rel-customer', rowAttr);
            $('#send_between').attr('rel-customer', rowAttr);

        });
        $('#savePaymentDetails').on('click', function() {

            var data = $('#payment_data').serializeArray();

            $.post(root + 'admin/invoices/addPayment', data, function(d) {

                if (d.result == true) {
                    alert("<?php echo $this->lang->line('Done'); ?>!");
                    location.reload();
                } else {
                    alert("<?php echo $this->lang->line('Error'); ?>!");
                }

            }, 'json');
        });

    });
</script>
<script type="text/javascript">
    <?php
    $url = '';
    if ($this->session->userdata('site_lang') == 'hebrew') {
        $url = '//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Hebrew.json';
    } else if ($this->session->userdata('site_lang') == 'arabic') {
        $url = '//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Arabic.json';
    } else if ($this->session->userdata('site_lang') == 'english') {
        $url = '//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/English.json';
    } else {
        $url = '//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Hebrew.json';
    }
    ?>
    $(document).ready(function() {
        $('.datepicker').datepicker({
            dateFormat: "dd/mm/yy",
            isRTL: true,
            prevText: '<i class="fa fa-chevron-trash"></i>',
            nextText: '<i class="fa fa-chevron-right"></i>',
        });

        var qData = JSON.parse(localStorage.getItem("DataTables_dt_basic2_/admin/customers/categories"));

        $('#dt_basic2 thead tr').clone(true).appendTo('#dt_basic2 thead');
        $('#dt_basic2 thead tr:eq(1) th').each(function(i) {

            if (i == 3) {
                var title = $(this).text();
                $(this).html(' <select name="filter_request_status" id="filter_request_status" class="form-control"><option value=""></option><?php foreach ($categories as $cat) { ?> <option value="<?php echo $cat->category_name; ?>"> <?php echo $cat->category_name; ?> </option> <?php }; ?></select>');
                if (qData != null) {
                    var data = qData.columns[3].search.search;
                } else {
                    var data = "";
                }

                var x = data;
                var y = x.replace("$", "");
                var z = y.replace("^", "");

                $("#filter_request_status option[value='" + z + "']").prop("selected", true);
                $('#filter_request_status').on('change', function() {
                    var val = $(this).val();
                    oTbl1.column(3)
                        .search(val ? '^' + $(this).val() + '$' : val, true, false)
                        .draw();
                });

            }

        });

        var oTbl1 = $('#dt_basic2').DataTable({
            "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'dt-buttons col-sm-6 col-xs-12 hidden-xs'l>r>" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
            "buttons": ['excelHtml5'],
            "processing": false,
            "bStateSave": false,
            "dom": 'Blfrtip',
            "order": [
                [0, "asc"]
            ],
            "pagingType": "full_numbers",
            "lengthMenu": [
                [10, 25, 50, -1],
                [10, 25, 50, "<?php echo $this->lang->line('Everything'); ?>"]
            ],
            "pageLength": 10,
            "sPaginationType": "full_numbers",
            "iDisplayLength": 10,
            "language": {
                "url": "<?php echo $url; ?>"
            },
            orderCellsTop: true,
            fixedHeader: true
        });
        oTbl1.buttons().container().appendTo('.dataTables_filter');
        $('input[aria-controls="dt_basic2"]').attr('placeholder', '<?php echo $this->lang->line('search1'); ?>...');
        $('#dt_basic2_info').css('float', 'left').parent().css('float', 'left');
        $('.dataTables_paginate ').parent().css('float', 'right');
        $('.dataTables_paginate ').css('text-align', 'right');
        var row_input = '<tr><td></td>';
        row_input += '<td><input type="text" name="category_name" class="category_name form-control" value="" autocomplete="OFF" /></td>';
        row_input += '<td><input type="text" name="description" class="description form-control" value="" autocomplete="OFF" /></td>';
        row_input += '<td><a href="#0" class="add_new btn btn-success btn-circle"><i class="fa fa-check"></i></a></td></tr>';
        $(document).on('click', '.add_new', function() {
            var elem = $(this).parent().parent();
            var data = {};
            data.text = elem.find('.category_name').val();
            data.desc = elem.find('.description').val();
            $.post(root + 'admin/customers/addCategory', data, function(d) {
                if (d.result == true) {
                    elem.remove();
                    var edit_btn = '<a href="#0" class="edit_this btn btn-warning btn-circle" rel="' + d.id + '"><i class="fa fa-edit"></i></a>';
                    var del_btn = '<a href="#0" class="delete_this btn btn-danger btn-circle" rel="' + d.id + '"><i class="fa fa-trash-o"></i></a>';
                    var n_row_input = '<tr><td>' + d.id + '</td>';
                    n_row_input += '<td><input type="text" name="category_name" class="category_name form-control" value="' + data.text + '" autocomplete="OFF" /></td>';
                    n_row_input += '<td><input type="text" name="description" class="description form-control" value="' + data.desc + '" autocomplete="OFF" /></td>';
                    n_row_input += '<td>' + edit_btn + del_btn + '</td></tr>';
                    $('#dt_basic2 tbody').append(n_row_input);
                    var e = getResult(type = 'success');
                } else {
                    var e = getResult(type = 'failed');
                }
                $('#dt_basic2 tbody').append(row_input);
            }, 'json');
        });
        $(document).on('click', '.edit_this', function() {
            var elem = $(this).parent().parent();
            var data = {};
            data.cat = $(this).attr("rel");
            data.text = elem.find('.category_name').val();
            data.desc = elem.find('.description').val();
            $.post(root + 'admin/customers/editCategory', data, function(d) {
                if (d.result == true) {
                    var e = getResult(type = 'success');
                } else {
                    var e = getResult(type = 'failed');
                }
            }, 'json');
        });
        $(document).on('click', '.delete_this', function() {
            var elem = $(this).parent().parent();
            var data = {};
            data.cat = $(this).attr("rel");
            $.post(root + 'admin/customers/deleteCategory', data, function(d) {
                if (d.result == true) {
                    elem.remove();
                    var e = getResult(type = 'success');
                } else {
                    var e = getResult(type = 'failed');
                }
            }, 'json');
        });
        $(document).on('change', '.customer_category', function() {
            var data = {};
            data.cat = $(this).val();
            data.customerId = $(this).attr("rel");
            $.post(root + 'admin/customers/updateCustomerCategory', data, function(d) {
                if (d.result == true) {
                    var e = getResult(type = 'success');
                } else {
                    var e = getResult(type = 'failed');
                }
            }, 'json');
        });
    });
</script>


<style>
    .date-searchWrapper {
        display: flex;
        justify-content: flex-end;
        width: 100%;
    }
</style>