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

?>
<script src="https://cdn.lordicon.com/libs/mssddfmo/lord-icon-2.1.0.js"></script>
<div id="main p-0" role="main" class="check_page">
    <!-- <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('bank_checks'); ?></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="#myModal" title="<?php echo $this->lang->line('new_order'); ?>">
                            <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_payment'); ?>
                            </span>
                        </button>
                        <button type="button" class=" filed_effect 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 p-2" style="width: 50px;" id="" rel-check="-1" data-bs-target="">
                            <i class="fas fa-file-pdf text-warning"></i>
                        </button>
                        <button type="button" class=" shadow-lg excel_exporter check_back p-2" style="width: 50px;">
                            <i class="pt-1 me-1 fas fa-undo text-danger"></i>
                        </button>
                    </div>
                </div>
                <div class="collapse w-100" id="date_search" style="margin-left: 120px;">
                    <div class>
                        <div class="card p-3 w-25" style="border-radius: 0 0 20px 20px; float: left;">
                            <div>
                                <div>
                                    <select class="exit_check" name="supplier_id" id="supplier_id">
                                        <?php foreach ($supplires as  $supplier) { ?>
                                            <option value="<?php echo $supplier->supplier_id; ?>"><?php echo $supplier->name; ?></option>
                                        <?php  } ?>
                                    </select>
                                </div>
                            </div>
                            <div>
                                <button type="button" class="btn btn-success p-2 mt-1 confirmCheckButton">
                                    <?php echo $this->lang->line('change'); ?>
                                </button>
                            </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><?php echo $this->lang->line('date'); ?></th>
                                <th><?php echo $this->lang->line('customer'); ?></th>
                                <th><?php echo $this->lang->line('date'); ?></th>
                                <th><?php echo $this->lang->line('bank_visa'); ?></th>
                                <th><?php echo $this->lang->line('Branch_digits'); ?></th>
                                <th><?php echo $this->lang->line('account'); ?></th>
                                <th><?php echo $this->lang->line('bank_check_number'); ?></th>
                                <th><?php echo $this->lang->line('sum'); ?></th>
                                <th><?php echo $this->lang->line('status'); ?></th>
                                <th><?php echo $this->lang->line('supplier'); ?></th>
                            </thead>
                            <tbody>
                                <?php foreach ($checks as $check) { ?>

                                    <tr rel-check="<?php echo $check->item_id; ?>" <?php if ($check->check_return == 1) { ?> class="table-danger" <?php } ?>>
                                        <td>
                                            <div class="form-check">
                                                <?php if ($check->check_return == 1) { ?>

                                                <?php } else if ($check->check_used == 0) { ?>
                                                    <input class="form-check-input payment_check" type="checkbox" value="" id="payment_Check" rel-return="-1" rel-action="-1">
                                                <?php } else if ($check->check_used == 1) { ?>
                                                    <input class="form-check-input payment_check" type="checkbox" value="" id="payment_Check" rel-return="-1" rel-action="1">
                                                <?php } ?>
                                            </div>
                                        </td>
                                        <td><?php echo date('d/m/Y', strtotime($check->payment_date)); ?></td>
                                        <td><?php echo getCustomerName($check->customerId); ?> </td>
                                        <td><?php echo date('d/m/Y', strtotime($check->check_date)); ?></td>
                                        <td><?//php echo getBankName($check->bank_visa); ?> </td>
                                        <td><?//php echo getBranchName($check->branch_digits, $check->bank_visa); ?> </td>
                                        <td><?php echo $check->account_card; ?> </td>
                                        <td><?php echo $check->check_number; ?></td>
                                        <td><?php echo $check->total; ?></td>
                                        <td>
                                            <?php if ($check->check_return == 1) { ?>
                                                <span class="badge bg-danger"><?php echo $this->lang->line('back'); ?> </span>

                                            <?php } else if ($check->check_used == 1) { ?>
                                                <span class="badge bg-primary"> <?php echo $this->lang->line('used'); ?> </span>
                                            <?php } else { ?>
                                                <span class="badge bg-success"> <?php echo $this->lang->line('free'); ?> </span>
                                            <?php  } ?>
                                        </td>
                                        <td>
                                            <?php if ($check->check_used == 1) { ?>
                                                <?php echo getSupplierName($check->check_used_for); ?>
                                            <?php   } ?>
                                        </td>
                                    </tr>
                                <?php }; ?>
                            </tbody>
                            <tfoot>
                            </tfoot>
                        </table>
                    </div>
                </div>
                <div class="modal" id="myModal" role="dialog">
                    <div class="modal-dialog modal-dialog-centered ">
                        <div class="modal-content position-relative">
                            <div class="close_modal" id="close_modal">
                                <i class="fas fa-times-circle text-danger"></i>
                            </div>
                            <div class="modal-body" style="background-color: #f5f5f5;">
                                <div id="content">
                                    <form action="no-action" method="POST" class="smart-form" id="payment_data">
                                        <div class="first-stage position-relative" id="page_one">
                                            <div class="form-header">
                                                <div class="invoice-head">
                                                    <label for=""><?php echo $this->lang->line('Production_receipt'); ?></label>
                                                    <input class="form-control" value="<?//php echo getNewPaymentNo(); ?>" name="payment_code">
                                                </div>
                                                <div class="invoice-head">
                                                    <label for=""><?php echo $this->lang->line('date'); ?></label>
                                                    <input type="text" value="<?php $now = date('Y-m-d');
                                                                                echo date("d/m/Y", strtotime($now)); ?>" name="payment_date" id="payment_date" class=" datepicker form-control p-0 py-2" />
                                                </div>
                                            </div>
                                            <div class="">
                                                <div class="form-full">
                                                    <label for=""><?php echo $this->lang->line('supplier'); ?></label>
                                                    <div class="selectorHolder">
                                                        <select class="select2" id="payment_for" name="payment_for">
                                                                <option value=""><?php echo $this->lang->line('select2'); ?></option>
                                                                <?php foreach ($supplires as  $supplier) { ?>
                                                                    <option value="<?php echo $supplier->supplier_id; ?>"><?php echo $supplier->name; ?></option>
                                                                <?php  } ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="form-full">
                                                    <div class="invoice-custom_75 d-flex" style="width: 80%;">
                                                        <label for="" class="" style="width: 20.3%;">
                                                            <div style="max-width: 20px;">
                                                                <?php echo $this->lang->line('manger_note'); ?>
                                                            </div>
                                                        </label>
                                                        <input id="fill_boss_Comment1" class="form-control w-75" name="boss_Comment">
                                                    </div>
                                                    <div class="invoice-custom_25 d-flex" style="width: 30%">
                                                        <label class="w-50"><?php echo $this->lang->line('customer_balance'); ?></label>
                                                        <input id="customer_credit" type="text" class="form-control w-50 p-1 text-center" value="" name="customer_credit" style="font-size:8px; color: tomato !important; font-weight: bold !important;" />
                                                    </div>
                                                </div>
                                                <div class="form-full">
                                                    <label for=""><?php echo $this->lang->line('details'); ?></label>
                                                    <input class="form-control fill_cust_comment" name="custComment" id="custComment">
                                                </div>
                                                <div class="form-full" style="margin-top: 50px;">
                                                    <label for=""><?php echo $this->lang->line('notes'); ?></label>
                                                    <textarea class="form-control" style="width: 85%; height: 150px;" placeholder="<?php echo $this->lang->line('Enter_your_comment'); ?>" id="comment1" name="comment1"></textarea>
                                                </div>
                                            </div>
                                            <div class="row w-100 d-flex justify-content-end m-0">
                                                <button type="button" class="btn btn-success rounded float-left p-1 next-stage" style="width: 100px;">
                                                    <?php echo $this->lang->line('confirm'); ?> </button>
                                            </div>
                                        </div>
                                        <page size="A4" style="display: none;">
                                            <div class="second_stage_header row align-items-start">
                                                <div class="right-section w-50">
                                                    <div class="w-50 m-2">
                                                        <label for="" class="me-1"><?php echo $this->lang->line('Production_receipt'); ?>: </label>
                                                        <label for="" class="fw-bold"><?//php echo getNewPaymentNo()  ?></label>
                                                    </div>
                                                    <div class="w-50 m-2">
                                                        <label for="" class="me-1" name="customer" id="customer"><?php echo $this->lang->line('customer'); ?>: </label>
                                                        <label for=""></label>
                                                    </div>
                                                    <div class="form-full w-50 m-2">
                                                        <label for="" class="me-1"><?php echo $this->lang->line('details'); ?>: </label>
                                                        <input class="form-control" name="cust_comment" id="cust_comment">
                                                    </div>
                                                </div>
                                                <div class="left-section w-50">
                                                    <div class="invoice-head w-50 m-2">
                                                        <label for="" class="me-1"><?php echo $this->lang->line('date'); ?>: </label>
                                                        <input class="form-control" value="" name="payment_date1" id="payment_date1">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row container-sm mx-auto p-0">
                                                <div class="col col-lg-12 col-md-12 col-sm-12" id="payment_details">
                                                    <table class="table" id="payment_table">
                                                        <thead>
                                                            <tr class="items">
                                                                <th style="width: 5px;"><?php echo $this->lang->line('actions'); ?></th>
                                                                <th><?php echo $this->lang->line('payment_method'); ?></th>
                                                                <th><?php echo $this->lang->line('cashbox'); ?></th>
                                                                <th><?php echo $this->lang->line('sum'); ?></th>
                                                                <th class="check_items shared_items"><?php echo $this->lang->line('bank_visa'); ?></th>
                                                                <th class="check_items shared_items"><?php echo $this->lang->line('Branch_digits'); ?></th>
                                                                <th class="check_items shared_items"><?php echo $this->lang->line('invoice_validity'); ?></th>
                                                                <th class="check_items"><?php echo $this->lang->line('bank_check_number'); ?></th>
                                                                <th class="check_items shared_items"><?php echo $this->lang->line('date'); ?></th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr id="btns_group">
                                                                <td colspan="7" style="text-align:center;">
                                                                    <a href="#0" class="btn btn-success btn-circle p-1" id="add_item">
                                                                        <i class="fa fa-plus"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>

                                                <div class="final_info">
                                                    <div class="form-full">
                                                        <textarea class="form-control w-75" style="height: 100px" placeholder="הערות" id="floatingTextarea" name="comment2"></textarea>
                                                    </div>
                                                    <div class="final_number">
                                                        <div class="form-full mt-1" style="margin: 0px;">
                                                            <label class="w-50 fw-bold" for="" style="font-size: 11px; font-weight: bold !important;"><?php echo $this->lang->line('total_before_vat'); ?></label>
                                                            <input type="text" value="0" name="total_before_vat" class="fill_total_before_vat form-control w-50 text-center p-0" readonly />
                                                        </div>
                                                        <div class="form-full mt-1" style="margin: 0px;">
                                                            <label class="w-50 fw-bold" for="" style="font-size: 11px; font-weight: bold !important;"><?php echo $this->lang->line('vat_17'); ?></label>
                                                            <input type="text" value="0" name="vat" class="form-control w-50 fill_vat text-center p-0" readonly />
                                                        </div>
                                                        <div class="form-full mt-1" style="margin: 0px;">
                                                            <label class="w-50 fw-bold" for="" style="font-size: 11px; font-weight: bold !important;"><?php echo $this->lang->line('total_shekel'); ?></label>
                                                            <input type="text" value="0" name="total" class="fill_total form-control w-50 text-center p-0" readonly />
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="col col-lg-12 col-lg-12 col-sm-12">
                                                    <div class="row justify-content-between">
                                                        <div class="col-lg-3 d-flex align-items-center">
                                                            <div class="invoice-custom_25 d-flex">
                                                                <label class="w-50"><?php echo $this->lang->line('customer_balance'); ?></label>
                                                                <input type="text" class="form-control w-50 p-1 text-center" value="" name="credit1" id="credit1">
                                                            </div>
                                                        </div>
                                                        <div class="align-items-center col-lg-5 d-flex justify-content-end">
                                                            <button type="button" class="reverse-stage btn btn-primary p-1"><i class="fas fa-angle-right me-1"></i><?php echo $this->lang->line('back'); ?></button>
                                                            <a href="#0" class="btn btn-danger" id="close_invoiceForm" style=" margin: 0 10px !important;padding: 4px 20px !important;">
                                                                <?php echo $this->lang->line('close'); ?>
                                                            </a>
                                                            <button type="button" class="btn btn-success" id="savePaymentDetails" style="float:left; margin: 0 10px !important;padding: 4px 20px !important;"><?php echo $this->lang->line('save'); ?></button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </page>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/js/bootstrap-datepicker.min.js"></script>
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/css/bootstrap-datepicker.css">
<script>
    <?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() {
        let itemAddition = 0;
        var total_before_vat = 0;
        var vat = 0;
        var total = 0;

        function isValidDate(s) {
            // Assumes s is "mm/dd/yyyy"
            if (!/^\d\d\/\d\d\/\d\d\d\d$/.test(s)) {
                return false;
            }
            const parts = s.split('/').map((p) => parseInt(p, 10));
            parts[0] -= 1;
            const d = new Date(parts[2], parts[0], parts[1]);
            return d.getMonth() === parts[0] && d.getDate() === parts[1] && d.getFullYear() === parts[2];
        }
        $(document).on('click', '.check_page .add_invoice_button', function() {
            let counter = 0;
            $(".payment_check").each(function() {
                var elem = $(this);
                let action = elem.attr("rel-action");
                console.log(action);
                if (elem.prop('checked') == true) {
                    if (action == -1) {
                        counter++;
                    } else {
                        elem.prop('checked', false);
                    }
                }
            });
            if (counter == 0) {
                $('#myModal').modal('hide');
                bootbox.alert("<?php echo $this->lang->line('select_check'); ?>");
            } else {
                // $('#myModal').modal('show');
                $('.next-stage').css('display', 'block');

                if ($('#myModal > .modal-dialog').hasClass('modal-lg')) {
                    $('#myModal > .modal-dialog').removeClass('modal-lg');
                }
                if ($('#DeleteInvoice > .modal-dialog').hasClass('modal-lg')) {
                    $('#myModal > .modal-dialog').removeClass('modal-lg');
                }
            }
        });
        $(document).on('change', ' .check_page #order_date', function(event) {
            if (!isValidDate($(this).val())) {
                $(this).val("");
            }
        });
        $(document).on('click', '.check_page #to_invoice', function(event) {
            $(".unitOut").each(function(index) {
                var elem = $(this);
                var unitLeft = Number(elem.val());
                var productId = Number(elem.parent().parent().find('.item_code').attr('rel-product'));
                var order_id = Number($('#out_order_id').text())
                $('#secret_order_id').val(order_id);
                activities.push({
                    productId,
                    unitLeft,
                    order_id
                });
            });
            var total_items = $('#total_items').val();
            if (total_items > 0) {
                $('#out_page_one').show();
                $('#check_items').hide();
            } else {
                $(".unitOut").each(function(index) {
                    var elem = $(this);
                    elem.css({
                        "color": "red",
                        "border": "2px solid red "
                    });;
                });
            }

        });
        $('#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, "<?php echo $this->lang->line('Everything'); ?>"]
            ],
            "pageLength": 20,
            "sPaginationType": "full_numbers",
            "iDisplayLength": 10,
            "sScrollY": 500,
            "bScrollCollapse": true,
            "searchCols": [
                null,
                {
                    "search": "My filter"
                },
                null,
                {
                    "search": "^[0-9]",
                    "regex": true
                }
            ],
            "language": {
                "url": "<?php echo $url; ?>"
            },

            orderCellsTop: true,
            fixedHeader: false,
            searching: false
        });

        $(document).on('change', '.check_page .payment_check', function() {
            let counter = 0;
            $(".payment_check").each(function() {
                var elem = $(this);
                if (elem.prop('checked') == true) {
                    counter++;
                }
            });
            console.log(counter);
            if (counter < 2) {
                $(".filed_effect").attr("disabled", "disabled");
            }
        });
        $(document).on('click', '.check_page .check_back', function() {
            let data = [];
            let check_id = 0;
            let counter = 0;
            $(".payment_check").each(function() {

                var elem = $(this);
                var back = elem.attr("rel-return");
                if (elem.prop('checked') == true) {
                    if (back == -1) {
                        check_id = elem.parent().parent().parent().attr('rel-check');
                        data.push(check_id);
                        counter++;
                    }
                }
            });
            if (counter >= 1) {
                let text = "<?php echo $this->lang->line('sure_delete_order'); ?>";
                var dialog = bootbox.dialog({
                    title: 'Order Cancelation',
                    message: "<p><?php echo $this->lang->line('sure_close_order'); ?> ?</p>",
                    size: 'small',
                    buttons: {
                        cancel: {
                            label: "No",
                            className: 'btn-primary',
                            callback: function() {
                                console.log('Custom cancel clicked');
                            }
                        },
                        ok: {
                            label: "Yes",
                            className: 'btn-danger',
                            callback: function() {
                                $.post(root + 'admin/checks/checkReturn', {
                                    checkArray: data
                                }, function(d) {

                                    if (d.result == true) {
                                        bootbox.alert("<?php echo $this->lang->line('Order_Deleted_successfully'); ?>");
                                        setTimeout(() => location.reload(), 500);
                                    } else {
                                        bootbox.alert("<?php echo $this->lang->line('An_error_occurred'); ?>");
                                    }
                                }, 'json');
                                console.log('Custom OK clicked');
                            }
                        }
                    }
                });
            } else {
                bootbox.alert("<?php echo $this->lang->line('select_order_to_continue'); ?>");
            }

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

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

            $.post(root + 'admin/invoices/addSupplierPayment', 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');
        });
        $(document).on('click', '.check_page .confirmOrderButton', function() {
            let data = [];
            let order_id = 0;
            let counter = 0;
            let elemnt = $(this);
            let status = $('#supplier_check_id').val();
            $(".payment_check").each(function() {
                var elem = $(this);
                if (elem.prop('checked') == true) {
                    order_id = elem.parent().parent().parent().attr('rel-check');
                    data.push({
                        order_id,
                        status,
                    });
                    counter++;
                }

            });
            if (counter >= 1) {
                var elem = $(this);
                $.post(root + 'admin/orders/confirmOrder', {
                    orderData: data
                }, function(d) {
                    if (d.result == true) {
                        bootbox.alert("<?php echo $this->lang->line('Order_Confirmed_successfully'); ?>");
                        setTimeout(() => location.reload(), 500);
                    } else {
                        bootbox.alert("<?php echo $this->lang->line('An_error_occurred'); ?>");
                    }


                }, 'json');
            } else {

                bootbox.alert("<?php echo $this->lang->line('select_order_to_continue'); ?>");
            }
        });

        $('.datepicker').datepicker({
            dateFormat: "dd/mm/yy",
            isRTL: true,
            prevText: '<i class="fa fa-chevron-left"></i>',
            nextText: '<i class="fa fa-chevron-right"></i>',
        });

        $('.excel_exporter').on('click', () => {
            $('#selectCustomer').select2({
                placeholder: '<?php echo $this->lang->line('Search_Customers'); ?>',
                selectOnClose: false,
                tags: true,
                dropdownParent: $('#ExcelExportModal'),
                ajax: {
                    dataType: "json",
                    url: root + 'admin/invoices/getCustomersAjax',
                    processResults: function(data) {
                        return {
                            results: data.results
                        }
                    }
                },
                "language": {
                    "noResults": function() {
                        return "<?php echo $this->lang->line('Search_Customers'); ?>";
                    }
                },
                theme: "bootstrap-5"
            });

            $('#selectInvoiceFrom').select2({
                placeholder: 'From Invoice',
                selectOnClose: false,
                tags: true,
                dropdownParent: $('#ExcelExportModal'),
                ajax: {
                    dataType: "json",
                    url: root + 'admin/invoices/getInvoicesAjax',
                    processResults: function(data) {
                        return {
                            results: data.results
                        }
                    }
                },
                "language": {
                    "noResults": function() {
                        return "<?php echo $this->lang->line('Search_Customers'); ?>";
                    }
                },
                theme: "bootstrap-5"
            });

            $('#selectInvoiceTo').select2({
                placeholder: 'To Invoice',
                selectOnClose: false,
                tags: true,
                dropdownParent: $('#ExcelExportModal'),
                ajax: {
                    dataType: "json",
                    url: root + 'admin/invoices/getInvoicesAjax',
                    processResults: function(data) {
                        return {
                            results: data.results
                        }
                    }
                },
                "language": {
                    "noResults": function() {
                        return "<?php echo $this->lang->line('Search_Customers'); ?>";
                    }
                },
                theme: "bootstrap-5"
            });

            // ability_ExcelExportTypes();
            // $('#selectCustomer').prop("disabled", false);
            // $('.ExcelFilteration input[rel-exportby="customer"]').prop('checked', true);
        });
        $(document).on('change', '.ExcelFilteration input[type="checkbox"]', function() {
            var elem = $(this);
            var checkbox = elem.attr("rel-exportby");
            if (checkbox != 'customer') {
                if ($('#exportByCustomer').prop('checked') == true) {
                    if (checkbox == 'invoice') {
                        $('#exportByDate').prop('checked', false);
                    }
                    if (checkbox == 'date') {
                        $('#exportByInvoice').prop('checked', false);
                    }
                } else {
                    if (checkbox == 'invoice') {
                        $('#exportByDate').prop('checked', false);
                    }
                    if (checkbox == 'date') {
                        $('#exportByInvoice').prop('checked', false);
                    }
                }
            }
        });
        $('#buildExcel').on('click', function() {
            let ajaxData = {};
            if ($('#exportByCustomer').prop("checked")) {
                ajaxData.customerId = $('#selectCustomer').val();
            }
            if ($('#exportByInvoice').prop("checked")) {
                ajaxData.invoiceFrom = $('#selectInvoiceFrom').val();
                ajaxData.invoiceTo = $('#selectInvoiceTo').val();
            }
            if ($('#exportByDate').prop("checked")) {
                ajaxData.invoiceDateFrom = $('#invoiceDateFrom').val();
                ajaxData.invoiceDateTo = $('#invoiceDateTo').val();
            }

            console.log(ajaxData);
            $.post(root + 'admin/ajax/invoiceExcelReport', ajaxData, function(response) {
                window.location.assign(root + 'assets/' + response);
            }, "json");
        });
        // $(document).on('click', '#dt_basic2 tbody tr', function() {
        //     let elem = $(this);
        //     let rowAttr = elem.attr('rel-check');
        //     console.log(rowAttr);
        //     $('tr').css('background-color', "white");
        //     elem.css('background-color', "#e3edff")
        //     $('#deleteInvoiceButton').css('border-color', "#e9200c");
        //     $('#viewInvoiceButton').css('border-color', "#27b980");

        //     $('#viewInvoiceButton').attr('rel-check', rowAttr);
        //     $('#out_order').attr('rel-check', rowAttr);
        //     $('#updateOrderButton').attr('rel-check', rowAttr);
        // });
        $(document).on('change', '.check_page .bank_visa', function(event) {
            let data = {};
            let elem = $(this);
            var row = elem.parent().parent();
            let id = elem.val();
            data.id = id;
            row.find(".hidden_bank").val(id);
            row.find(".Branch_digits").val("");

            $.post(root + 'admin/invoices/getbankDetails', data, function(d) {
                if (d.result == true) {
                    elem.val(d.name);
                    // console.log(row.find(".hidden_bank").val());
                } else {
                    elem.val("");
                }

            }, 'json');


        });
        $(document).on('change', '.check_page  .Branch_digits', function(event) {
            let data = {};
            let elem = $(this);
            var row = elem.parent().parent();
            let id = elem.val();
            let bank_id = row.find(".hidden_bank").val();
            data.id = id;
            data.bank_id = bank_id;
            row.find(".hidden_branch").val(id);
            $.post(root + 'admin/invoices/getbranchDetails', data, function(d) {
                if (d.result == true) {
                    elem.val(d.name);
                    console.log(row.find(".hidden_branch").val());
                } else {
                    elem.val("");
                }

            }, 'json');


        });
        $(document).on('change', '.check_page #payment_for', function() {
            var data = {};
            data.supplier_id = $(this).val();
            $.post(root + 'admin/invoices/getSupplierDetailsforInvoice', data, function(d) {
                if (d.result == true) {
                    $('#customer_credit').val(d.credit);
                } else {
                    $('#customer_credit').val("");
                }

            }, 'json');
        });
        $(document).on('click', '.check_page #add_item', function() {
            var $table = $('#payment_table');
            var last = $('tr.items:last');
            var sum = 0;
            var bank_visa = "";
            var brach_digits = 0;
            var invoice_validity = 0;
            var check_number = 0;
            var check_date = "";
            var bank_visa_code = 0;
            var brach_digits_code = 0;
            var approve_number = 0;
            var method = last.find(".payment_method").val();
            if (method == 3) {
                sum = last.find(".payment_sum").val();
            } else if (method == 1) {
                sum = last.find(".payment_sum").val();
                bank_visa = last.find(".bank_visa").val();
                brach_digits = last.find(".Branch_digits").val();
                bank_visa_code = last.find(".hidden_bank").val();
                // console.log(bank_visa_code);
                brach_digits_code = last.find(".hidden_branch").val();
                // console.log(brach_digits_code);
                invoice_validity = last.find(".invoice_validity").val();
                check_date = last.find(".check_date").val();
                // check_date = new Date(check_date);
                approve_number = last.find(".reference_id_num").val();

            } else if (method == 5) {
                sum = last.find(".payment_sum").val();
                bank_visa = last.find(".bank_visa").val();
                brach_digits = last.find(".Branch_digits").val();
                brach_digits_code = last.find(".hidden_branch").val();
                bank_visa_code = last.find(".hidden_bank").val();
                // console.log(bank_visa_code);
                // console.log(brach_digits_code);
                invoice_validity = last.find(".invoice_validity").val();
                check_date = last.find(".check_date").val();
                check_date = new Date(check_date);
                check_number = last.find(".check_number").val();
                check_number = Number(check_number);
            } else {
                sum = last.find(".payment_sum").val();
                bank_visa = last.find(".bank_visa").val();
                brach_digits = last.find(".Branch_digits").val();
                bank_visa_code = last.find(".hidden_bank").val();
                // console.log(bank_visa_code);
                brach_digits_code = last.find(".hidden_branch").val();
                // console.log(brach_digits_code);
                invoice_validity = last.find(".invoice_validity").val();
                check_date = last.find(".check_date").val();
                check_date = new Date(check_date);
                approve_number = last.find(".reference_id_num").val();
            }

            let newRow = `
                    <tr class="items">
                 <td style="width: 5px;">
                     <div href="#0" class="remove_this_item btn btn-sm bg-danger text-white p-1">
                         <i class="fa fa-times"></i>
                     </div>
                 </td>
                 <td>
                     <select style="width:100px;" name="items[payment_method][]" class="payment_method">
                         <option value="0"><?php echo $this->lang->line('select2'); ?></option>
                         <?php foreach ($payment_types as $payment_type) { ?>
                             <option value="<?php echo $payment_type->type_id; ?>"><?php echo $payment_type->name; ?></option>
                         <?php }; ?>
                     </select>
                 </td>
                 <td>
                     <select style="width:100px;" name="items[cashbox][]" class="cash_box">
                         <option value="0"><?php echo $this->lang->line('select2'); ?></option>
                         <?php foreach ($payment_boxes as $payment_box) { ?>
                             <option value="<?php echo $payment_box->box_id; ?>"><?php echo $payment_box->name; ?></option>
                         <?php }; ?>
                     </select>
                 </td>
                 <td>
                     <input type="text" value="" name="items[sum][]" class="payment_sum form-control text-center" />
                 </td>
                 <td class="check_items shared_items">
                     <input type="text" value="" name="items[bank_visa][]" class="bank_visa form-control text-center" />
                     <input type="hidden" value="" name="items[hidden_bank][]" class="hidden_bank form-control text-center"/>
                 </td>
                 <td class="check_items shared_items">
                     <input type="text" value="" name="items[Branch_digits][]" class="Branch_digits form-control text-center" style="width: 100%;" />
                     <input type="hidden" value="" name="items[hidden_branch][]" class="hidden_branch form-control text-center"/>
                 </td>
                 <td class="check_items shared_items">
                     <input type="text" value="" name="items[invoice_validity][]" class="invoice_validity form-control text-center" style="width: 100%;" />
                 </td>
                 <td class="bank_items">
                     <input type="text" value="" name="items[reference_id_num][]" class="reference_id_num form-control text-center" style="width: 100%;" />
                 </td>
                 <td class="check_items">
                     <input type="text" value="" name="items[check_number][]" class="check_number form-control text-center" style="width: 100%;" />
                 </td>
                 <td class="check_items shared_items">
                     <input type="text" value="" name="items[check_date][]" class="datepicker check_date  form-control text-center "  style="width: 100%;" />
                 </td>
                      </tr>`;

            $(newRow).insertBefore('#btns_group');
            var new_row = $('tr.items:last');

            if (method == 3) {
                new_row.find(".cash_box").val('4');
                new_row.find(".payment_method").val('3');
                new_row.find(".payment_sum").val(sum);
            } else if (method == 0) {
                new_row.find(".cash_box").val('0');
                new_row.find(".payment_method").val('0');
                new_row.find('.bank_items').hide();
                $('#payment_table thead').find('.bank_items').hide();
            } else if (method == 1) {
                new_row.find(".cash_box").val('1');
                new_row.find(".payment_method").val('1');
                new_row.find(".check_items").hide();
                new_row.find('.bank_items').show();
                new_row.find(".shared_items").show();
                $('#payment_table thead').find('.check_items').hide();
                $('#payment_table thead').find('.bank_items').show();
                $('#payment_table thead').find('.shared_items').show();
                new_row.find(".payment_sum").val(sum);
                new_row.find(".bank_visa").val(bank_visa);
                new_row.find(".Branch_digits").val(brach_digits);
                new_row.find(".hidden_branch").val(brach_digits_code);
                new_row.find(".hidden_bank").val(bank_visa_code);
                new_row.find(".hidden_branch").val(brach_digits_code);
                new_row.find(".invoice_validity").val(invoice_validity);
                //new_row.find(".check_date").val(check_date);
                new_row.find(".reference_id_num").val(approve_number);
            } else if (method == 5) {
                new_row.find(".cash_box").val('16');
                new_row.find(".payment_method").val('5');
                new_row.find(".cash_box").val('16');
                new_row.find(".check_items").show();
                new_row.find('.bank_items').hide();
                new_row.find(".shared_items").show();
                $('#payment_table thead').find('.bank_items').hide();
                $('#payment_table thead').find('.check_items').show();
                $('#payment_table thead').find('.shared_items').show();
                new_row.find(".payment_sum").val(sum);
                new_row.find(".bank_visa").val(bank_visa);
                new_row.find(".Branch_digits").val(brach_digits);
                new_row.find(".hidden_bank").val(bank_visa_code);
                new_row.find(".hidden_branch").val(brach_digits_code);
                new_row.find(".invoice_validity").val(invoice_validity);
                //new_row.find(".check_date").val(check_date);
                new_row.find(".check_number").val(check_number + 1);

                let newDate = last.find(".check_date").datepicker({
                    dateFormat: "dd/mm/yy",
                });

                let newRow_dateInput = new_row.find(".check_date");
                newRow_dateInput.datepicker({
                    dateFormat: "dd/mm/yy",
                    isRTL: true,
                    prevText: '<i class="fa fa-chevron-trash"></i>',
                    nextText: '<i class="fa fa-chevron-right"></i>',
                });

                newDate = last.find(".check_date").datepicker('getDate');
                console.log(newDate);
                newRow_dateInput.val(newDate);
                newRow_dateInput.datepicker('setDate', "+1m");
            } else {
                new_row.find(".check_items").hide();
                new_row.find(".cash_box").val('1');
                new_row.find(".payment_method").val('1');
                new_row.find(".check_items").hide();
                new_row.find('.bank_items').show();
                new_row.find(".shared_items").show();
                $('#payment_table thead').find('.check_items').hide();
                $('#payment_table thead').find('.bank_items').show();
                $('#payment_table thead').find('.shared_items').show();
                new_row.find(".payment_sum").val(sum);
                new_row.find(".bank_visa").val(bank_visa);
                new_row.find(".Branch_digits").val(brach_digits);
                new_row.find(".hidden_branch").val(brach_digits_code);
                new_row.find(".hidden_bank").val(bank_visa_code);
                new_row.find(".hidden_branch").val(brach_digits_code);
                new_row.find(".invoice_validity").val(invoice_validity);
                //new_row.find(".check_date").val(check_date);
                new_row.find(".reference_id_num").val(approve_number);
            }

            $('.datepicker').datepicker({
                dateFormat: "dd/mm/yy",
                isRTL: true,
                prevText: '<i class="fa fa-chevron-trash"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>',
            });
            calcTotal();
        });

        $(document).on('change', '.check_page .payment_method', function(event) {
            var elem = $(this);
            var row = elem.parent().parent();
            let method = elem.val();
            row.find(".check_items").hide();
            row.find('.bank_items').hide();
            row.find(".shared_items").hide();
            // $('#payment_table thead').find('.bank_items').hide();
            // $('#payment_table thead').find('.check_items').hide();
            // $('#payment_table thead').find('.shared_items').hide();
            if (method == 3) {
                // $("#cash_box option[value='Gateway 2']").prop('selected', true);
                row.find(".cash_box").val('4');
                row.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().addClass('modal-xl');
            } else if (method == 0) {
                row.find(".cash_box").val('0');
                row.find('.bank_items').hide();
                $('#payment_table thead').find('.bank_items').hide();
                row.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().addClass('modal-xl');
            } else if (method == 1) {
                row.find(".cash_box").val('1');
                row.find(".check_items").hide();
                row.find('.bank_items').show();
                row.find(".shared_items").show();
                $('#payment_table thead').find('.check_items').hide();
                $('#payment_table thead').find('.bank_items').show();
                $('#payment_table thead').find('.shared_items').show();
                row.find("input").val("");
                row.find(".check_date").val(moment().format('MMM D, YYYY'));
                row.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().addClass('modal-xl');
            } else if (method == 5) {
                row.find(".cash_box").val('16');
                row.find(".check_items").show();
                row.find('.bank_items').hide();
                row.find(".shared_items").show();
                $('#payment_table thead').find('.bank_items').hide();
                $('#payment_table thead').find('.check_items').show();
                $('#payment_table thead').find('.shared_items').show();
                row.find("input").val("");
                row.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().addClass('modal-xl');
            } else {
                row.find(".cash_box").val('1');
                row.find(".check_items").hide();
                row.find('.bank_items').show();
                row.find(".shared_items").show();
                $('#payment_table thead').find('.check_items').hide();
                $('#payment_table thead').find('.bank_items').show();
                $('#payment_table thead').find('.shared_items').show();
                row.find("input").val("");
                row.find(".check_date").val(moment().format('MMM D, YYYY'));
                row.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().addClass('modal-xl');
            }

        });
        $(document).on('change', ' .check_page  .payment_sum', function(event) {
            calcTotal();
        });
        $(document).on('click', '.check_page .next-stage', function(event) {
            console.log("test");
            let checkArray = [];
            let elem = $(this);
            let isDeleteModal = elem.attr('rel-delete') === "true" ? true : false;
            let parentPageOne = elem.parent().parent();
            let inputArray = parentPageOne.find('input');
            $.each(inputArray, function(index, el) {
                if (el.value == "" || el.value == 0 || el.value == -1) {
                    checkArray.push(false);
                    // el.style.border = '2px solid red';
                    el.classList.add('is-invalid');
                } else {
                    el.classList.add('is-valid');
                    // el.style.border = '2px solid green';
                    checkArray.push(el.value);
                }
            });
            if (!isDeleteModal) {
                $.each($('#invoice_for'), function(index, el) {
                    if (el.value == 0 ||
                        el.value == "" ||
                        el.value == undefined ||
                        el.value == null ||
                        el.value < 0) {
                        checkArray.push(false);
                        el.parentElement.style.border = "2px solid red";
                        el.parentElement.style.borderRadius = "5px";
                    } else {
                        el.parentElement.style.border = "2px solid green";
                        el.parentElement.style.borderRadius = "5px";
                        checkArray.push(el.value);
                    }
                });
            }
            if ($.inArray(false, checkArray) !== -1) {
                console.log('you forgot an input');
            } else {
                let data = [];
                let check_id = 0;
                let counter = 0;
                $(".payment_check").each(function() {
                    var elem = $(this);
                    if (elem.prop('checked') == true) {
                        check_id = elem.parent().parent().parent().attr('rel-check');
                        data.push(check_id);
                        counter++;
                    }
                });
                console.log(counter);
                if (counter >= 1) {
                    console.log("test2");
                    $.post(root + 'admin/checks/getItems', {
                        checkArray: data
                    }, function(d) {
                        if (d.result == true) {
                            console.log(d.data);
                            let value = d.data;
                            $(value).each(function(index, value) {
                                var $row = '<tr class="items">';
                                $row += '<input type="hidden" class="form-control" name="items[customer_payment_id][]" value="' + value.item_id + ' " >';
                                $row += ' <td style="width: 5px;"><div href="#0" class="remove_this_item btn btn-sm bg-danger text-white p-1"><i class="fa fa-times"></i></div></td>';
                                $row += '<td style="  text-align: center;"><input class="form-control payment_method_name" name="items[payment_method_name][]" value="' + value.paymentTypeName + ' " >';
                                $row += '<input type="hidden" class="form-control payment_method" name="items[payment_method][]" value="' + value.payment_type + ' " ></td>';
                                $row += '<td style="  text-align: center;"><input class="form-control cashbox_name" name="items[cashbox_name][]" value="' + value.paymetnBoxName + ' " >';
                                $row += '<input type="hidden" class="form-control cashbox" name="items[cashbox][]" value="' + value.payment_box + ' " ></td>';
                                $row += '<td><input type="text" value="' + value.total + ' " name="items[sum][]" class="payment_sum form-control text-center" /></td>';
                                $row += '<td class="check_items shared_items"><input type="text" value="' + value.bankName + '" name="items[bank_visa][]" class="bank_visa form-control text-center" />';
                                $row += '<input type="hidden" value=" ' + value.bank_visa + '" name="items[hidden_bank][]" class="hidden_bank form-control text-center" /></td>';
                                $row += '<td class="check_items shared_items"><input type="text" value="' + value.branchName + '" name="items[Branch_digits][]" class="Branch_digits form-control text-center" />';
                                $row += '<input type="hidden" value=" ' + value.branch_digits + '" name="items[hidden_branch][]" class="hidden_bank form-control text-center" /></td>';
                                $row += '<td class="check_items shared_items"><input type="text" value="' + value.account_card + '" name="items[invoice_validity][]" class="invoice_validity form-control text-center" style="width: 100%;" /></td>'
                                $row += '<td class="check_items"><input type="text" value="' + value.check_number + '" name="items[check_number][]" class="check_number form-control text-center" style="width: 100%;" />'
                                $row += '<input type="hidden" value="" name="items[reference_id_num][]" class="reference_id_num form-control text-center" style="width: 100%;" /></td>'
                                $row += '<td class="check_items shared_items"><input type="text" value="' + value.check_date + '" name="items[check_date][]" class=" datepicker check_date form-control text-center style="width: 100%;" /></td>';
                                $row += '</tr>';
                                // $('#payment_table tbody').append($row);
                                $('#payment_table tbody tr:last').before($row);

                            });

                        }
                    }, 'json');
                    console.log('Custom OK clicked');

                    let date = $("#payment_date").val();
                    let comment = $("#custComment").val();
                    let credit = $("#customer_credit").val();
                    let customer = $('#payment_for').find('option:selected').text();
                    let elem = $(this);
                    elem.parent().parent().parent().find('page').show();
                    $("#customer").html("<?php echo $this->lang->line('customer'); ?>: " + customer);
                    $("#cust_comment").val(comment);
                    $("#payment_date1").val(date);
                    $("#credit1").val(credit);
                    let parentModal = parentPageOne.parent().parent().parent().parent().parent();
                    parentModal.addClass('modal-xl');
                    elem.parent().parent().hide();
                    calcTotal();

                } else {
                    bootbox.alert("<?php echo $this->lang->line('select_order_to_continue'); ?>");
                }
            }


        });
        $(document).on('click', '.check_page .reverse-stage', function() {
            let elem = $(this);
            let isDeleteModal = elem.attr('rel-delete') === "true" ? true : false;

            if (isDeleteModal) {
                $('#DeleteInvoice .modal-dialog').removeClass('modal-lg');
            } else {
                $('#myModal .modal-dialog').removeClass('modal-lg');
            }
            elem.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().removeClass('modal-xl');
            elem.parent().parent().parent().parent().parent().parent().find('.first-stage').show();
            elem.parent().parent().parent().parent().parent().hide();
        });
        $(document).on('click', '.check_page .remove_this_item', function() {
            $(this).parent().parent().remove();
            calcTotal();
        });

        $(document).on('click', '#close_invoiceForm, #close_modal, #close_DeleteModal, #close_ExportModal', function() {
            let elem = $(this);
            let isDeleteModal = elem.attr('rel-delete') === "true" ? true : false;

            let isExportModal = elem.attr('rel-export') === "true" ? true : false;

            if (isExportModal) {
                $('#ExcelExportModal').modal('hide');
            }

            if (isDeleteModal) {
                $('#DeleteInvoice').modal('hide');
                $('#DeleteInvoice').find('modal-dialog').removeClass('modal-lg');
            } else {
                $('#myModal').modal('hide');
                $('#DeleteInvoice').find('modal-dialog').removeClass('modal-lg');
            }
        });

        function calcTotal() {
            var full_total = 0;
            $(".payment_sum ").each(function(index) {
                var elem = $(this);
                var sum = Number(elem.val());

                full_total += sum;
            });
            var before_vat = full_total / 1.17;
            var vat = full_total - before_vat;
            $('.fill_total_before_vat').val(before_vat.toFixed(2));
            $('.fill_vat').val(vat.toFixed(2));
            $('.fill_total').val(full_total.toFixed(2));
        }

    });
</script>

<style>
    .status-style {
        padding: 5px 13px;
        border-radius: 20px;
        color: white;
        font-weight: bold;
    }
</style>