$(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', '.add_invoice_button', function() {
        $('.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', '#invoice_date', function(event) {
    //     if (!isValidDate($(this).val())) {
    //         $(this).val("");
    //     }
    // });
    $(document).on('click', '.next-stage', function(event) {
        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 date = $("#invoice_date").val();
            let comment = $("#custComment").val();
            let credit = $("#customer_credit").val();
            let customer = $('#invoice_for').find('option:selected').text();
            let elem = $(this);
            elem.parent().parent().parent().find('page').show();
            $("#customer").html("לקוח: " + customer);
            $("#cust_comment").val(comment);
            $("#invoice_date1").val(date);
            $("#credit1").val(credit);
            let parentModal = parentPageOne.parent().parent().parent().parent().parent();
            parentModal.addClass('modal-lg');
            elem.parent().parent().hide();
        }
    });
    $('#DeleteInvoice').on('hidden.bs.modal', function(e) {
        let elem = $(this);
        elem.find('.first-stage').show();
        elem.find('.modal-dialog').removeClass('modal-lg');
        elem.find('page').hide();
    });
    $('#myModal').on('hidden.bs.modal', function(e) {
        let elem = $(this);
        elem.find('.first-stage').show();
        elem.find('.modal-dialog').removeClass('modal-lg');
        elem.find('page').hide();
    });
    $('.reverse-stage').on('click', 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().find('.first-stage').show();
        elem.parent().parent().parent().parent().parent().hide();
    });
    $('#invoice_table').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
    });
    $("#firstPayDate").datepicker({
        dateFormat: 'dd/mm/yy',
        defaultDate: "now",
        changeMonth: true,
        numberOfMonths: 2,
        isRTL: true,
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        onClose: function(selectedDate) {
            $("#firstPayToDate").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#firstPayToDate").datepicker({
        dateFormat: 'dd/mm/yy',
        defaultDate: "now",
        changeMonth: true,
        numberOfMonths: 2,
        isRTL: true,
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        onClose: function(selectedDate) {
            $("#firstPayDate").datepicker("option", "maxDate", selectedDate);
        }
    });
    $(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');
        }
    });
    $(document).on('click', '.cancel_invoice', function() {

        $('#deleteInvoiceForm').css('display', '');
        $('.next-stage').css('display', 'block');
        $('#DeleteInvoice > .modal-dialog').removeClass('modal-xl');
        $('#DeleteInvoice .first-stage').removeClass('col-md-4 col-sm-4 col-xs-4');

        $('.executeInvoiceDelete').css('display', 'block');

        let elem = $(this);
        let data = {};
        if (elem.attr("rel-invoice") === "-1") {
            bootbox.alert("Please Select an invoice from the table below to continue");
            $('#DeleteInvoice').modal('hide');
        } else {
            data = {
                id: elem.attr("rel-invoice"),
            }

            $.post(root + 'admin/invoices/getInvoiceData', data, function(d) {
                if (d.result == true) {
                    $('#DeleteInvoice .invoice_id_value').text(`${d.data.invoice_info.invoice_id}`);
                    $('#fill_invoice_code').val(`${d.data.invoice_info.invoice_id}`);
                    $('#fill_customer_credit').val(`${d.data.invoice_info.customerCredit}`);
                    $('#fill_credit1').val(`${d.data.invoice_info.customerCredit}`);
                    $('.invoiceCodeLabel').text(`${d.data.invoice_info.invoice_id}`);
                    $('#fill_invoice_date').val(`${d.data.invoice_info.invoice_date}`);
                    $('#fill_boss_Comment').val(`${d.data.invoice_info.bossComment}`);
                    $('#fill_customer').val(`${d.data.invoice_info.customerName}`);
                    $('#fill_warehouse').val(`${d.data.invoice_info.warehouseName}`);
                    $('#fill_customer2').text(`${d.data.invoice_info.customerName}`);
                    $('.fill_cust_comment').val(`${d.data.invoice_info.custComment}`);
                    $('#fill_comment1').val(`${d.data.invoice_info.comment1}`);
                    $('#fill_comment2').val(`${d.data.invoice_info.comment2}`);
                    $('#fill_invoice_date1').val(`${d.data.invoice_info.invoice_date}`);
                    $('.executeInvoiceDelete').attr('rel-invoice', d.data.invoice_info.invoice_id);

                    let productsRows = ``;
                    let items = d.data.items;

                    for (let i = 0; i < items.length; i++) {
                        productsRows += `
                            <tr class="items">
                                <td colspan="3" style="width: 40%;">
                                    <input type="text" value="${items[i].product_code}" class="item_code form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].item_title}" class="item_product form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].unit}" class="item_unit form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].item_price}" class="item_price form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].full_price}" class="full_price form-control text-center" readonly="readonly" style="width: 100%;"/>
                                </td>
                            </tr>`
                    }

                    $('#fill_items').html(productsRows);
                    calcTotal();
                }
            }, 'json');
        }
    });
    $(document).on('click', '.view_invoice', function() {

        $('#deleteInvoiceForm').css('display', 'flex');
        $('.next-stage').css('display', 'none');
        $('.reverse-stage').css('display', 'none');
        $('#DeleteInvoice > .modal-dialog').addClass('modal-xl');
        $('#DeleteInvoice page').show();
        $('#DeleteInvoice .first-stage').addClass('col-md-4 col-sm-4 col-xs-4');
        $('.executeInvoiceDelete').css('display', 'none');


        let elem = $(this);
        let data = {};
        if (elem.attr("rel-invoice") === "-1") {
            bootbox.alert("Please Select an invoice from the table below to continue");
            $('#DeleteInvoice').modal('hide');
        } else {
            data = {
                id: elem.attr("rel-invoice"),
            }

            $.post(root + 'admin/invoices/getInvoiceData', data, function(d) {
                if (d.result == true) {
                    let data = d.data.invoice_info;
                    $('#DeleteInvoice .invoice_id_value').text(`${data.invoice_id}`);
                    $('#fill_invoice_code').val(`${data.invoice_id}`);
                    $('#fill_customer_credit').val(`${data.customerCredit}`);
                    $('#fill_credit1').val(`${data.customerCredit}`);
                    $('.invoiceCodeLabel').text(`${data.invoice_id}`);
                    $('#fill_invoice_date').val(`${data.invoice_date}`);
                    $('#fill_boss_Comment').val(`${data.bossComment}`);
                    $('#fill_customer').val(`${data.customerName}`);
                    $('#fill_warehouse').val(`${data.warehouseName}`);
                    $('#fill_customer2').text(`${data.customerName}`);
                    $('.fill_cust_comment').val(`${data.custComment}`);
                    $('#fill_comment1').val(`${data.comment1}`);
                    $('#fill_comment2').val(`${data.comment2}`);
                    $('#fill_invoice_date1').val(`${data.invoice_date}`);
                    $('.executeInvoiceDelete').attr('rel-invoice', data.invoice_id);

                    let productsRows = ``;
                    let items = d.data.items;

                    for (let i = 0; i < items.length; i++) {
                        productsRows += `
                            <tr class="items">
                                <td colspan="3" style="width: 40%;">
                                    <input type="text" value="${items[i].product_code}" class="item_code form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].item_title}" class="item_product form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].unit}" class="item_unit form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].item_price}" class="item_price form-control text-center" readonly/>
                                </td>
                                <td>
                                    <input type="text" value="${items[i].full_price}" class="full_price form-control text-center" readonly="readonly" style="width: 100%;"/>
                                </td>
                            </tr>`
                    }

                    $('#fill_items').html(productsRows);
                    calcTotal();
                }
            }, 'json');
        }
    });
    $('.executeInvoiceDelete').on('click', function() {
        let text = "Are you sure you want to delete this invoice";
        let elem = $(this);
        var dialog = bootbox.dialog({
            title: 'Invoice Cancelation',
            message: "<p>Are you sure you want to delete this invoice ?</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() {
                        var data = {};
                        data.invoice_id = elem.attr('rel-invoice');
                        data.deleteComment = $('#fill_comment2').val();
                        $.post(root + 'admin/invoices/deleteInvoiceOnly', data, function(d) {
                            if (d.result == true) {
                                bootbox.alert("Invoice Deleted successfully");
                                setTimeout(() => location.reload(), 500);
                            } else {
                                bootbox.alert("An Error Occurred");
                            }
                        }, 'json');
                        console.log('Custom OK clicked');
                    }
                }
            }
        });
    });
    $('.datepicker').datepicker({
        dateFormat: "dd/mm/yy",
        isRTL: true,
        prevText: '<i class="fa fa-chevron-trash"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
    });
    $('#add_item').on('click', function() {
        if (itemAddition < 19) {
            var $table = $('#invoice_table');
            let newRow = `
                            <tr class="items">
                                <td colspan="3" style="width: 60%;"> <select style="width:400px;" name="items[product_id][]" class="select2Custom"></select>
                                <input type="hidden" name="items[code][]">
                                </td>
                                <td> <input type="text" value="" name="items[description][]" class="item_desc form-control" readonly="readonly"/></td>
                                <td> <input type="text" value="" name="items[unit][]" class="item_unit form-control" /></td>
                                <td> <input type="text" value="" name="items[price][]" class="item_price form-control" /></td>
                                <td> <input type="text" value="" name="items[full_price][]" class="full_price form-control" readonly="readonly" /></td>
                                <td>
                                    <div href="#0" class="remove_this_item btn btn-sm bg-danger text-white"><i class="fa fa-times"></i></div>
                                </td>
                            </tr>`;
            $(newRow).insertBefore('#btns_group');
            $('.select2Custom').select2({
                placeholder: 'חפש פריטים',
                selectOnClose: false,
                tags: true,
                ajax: {
                    dataType: "json",
                    url: root + 'admin/invoices/getItems',
                    processResults: function(data) {
                        return {
                            results: data.results
                        }
                    }
                },
                "language": {
                    "noResults": function() {
                        return "חפדש פריטים";
                    }
                },
                theme: "bootstrap-5"
            });
            calcTotal();
            itemAddition++;
        } else {
            alert("Only 20 are allowed");
        }
    });
    $('#add_payment_line').on('click', function() {
        var $table = $('#payment_table');
        var new_line = $table.find('tr.payments').first().clone();
        new_line.find("input.total_payment").val("");
        new_line.append('<a href="#0" class="remove_this_payment btn bg-danger btn-xs text-white"><i class="fa fa-times"></i></a>');
        new_line.insertBefore('#btns_group_payments');
    });
    $(document).on('click', '.remove_this_item', function() {
        $(this).parent().parent().remove();
        calcTotal();
        itemAddition--;
    });
    $('#save_invoice').on('click', function() {
        let checkArray = [];
        let checkFlag = false;
        let inputArray = $("#invoice_table .items input");
        // inputArray.push($('#page_one select'));

        $.each(inputArray, function(index, el) {
            if (el.value == "" || el.value == 0 || el.value == -1) {
                checkArray.push(false);
                el.style.border = '2px solid red';
            } else {
                el.style.border = '2px solid green';
                checkArray.push(el.value);
            }
        });

        $.each($('#invoice_table .items .select2Custom'), 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 = "1px solid red";
                el.parentElement.style.backgroundColor = "#df6d6d";
            } else {
                el.parentElement.style.backgroundColor = "#6ddf9d";
                // el.parentElement.style.border = "2px solid green";
                checkArray.push(el.value);
            }
        });

        if ($.inArray(false, checkArray) !== -1) {
            console.log('you forget an input');
        } else {
            $('#createInvoiceForm').submit();
        }
    });
    $('#invoice_for').on('change', function() {
        var data = {};
        data.customerId = $(this).val();
        $.post(root + 'admin/invoices/getCustomerDetailsforInvoice', data, function(d) {
            if (d.result == true) {
                $('#customer_credit').val(d.credits);
            } else {
                $('#customer_credit').val("");
            }

        }, 'json');
    });
    $(document).on('change', '.item_price', function() {
        calcTotal();
    });
    $(document).on('change', '.item_unit', function() {
        calcTotal();
    });
    $(document).on('change', '.select2Custom', function() {
        var elem = $(this);
        var data = {};
        data.id = $(this).val();
        data.text = $(this).find('option:selected').text();

        elem.parent().find('input[type="hidden"]').val(data.text);

        $.post(root + 'admin/invoices/getItemPrice', data, function(d) {
            console.log(d);
            if (d.id !== undefined) {
                elem.find('option:selected').val(d.id);
            }
            if (d.price) {
                elem.parent().parent().find('.item_price').val(d.price);
                calcTotal();
            }
            if (d.name) {
                elem.parent().parent().find('.item_desc').val(d.name);
                calcTotal();
            }
        }, 'json');
    });

    function calcTotal() {
        var full_total = 0;
        $(".item_price").each(function(index) {
            var elem = $(this);
            var price = Number(elem.val());
            var unit = Number(elem.parent().parent().find('.item_unit').val());
            var priceF = price * unit;
            elem.parent().parent().find('.full_price').val(priceF);
            full_total = full_total + priceF;
        });
        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));
    }
    $('.excel_exporter').on('click', () => {
        $('#selectCustomer').select2({
            placeholder: '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 "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 "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 "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', '#invoice_table tbody tr', function() {
        let elem = $(this);
        let rowAttr = elem.attr('rel-invoice');
        $('tr').css('background-color', "white");
        elem.css('background-color', "#e3edff")
        $('#deleteInvoiceButton').css('border-color', "#e9200c");
        $('#viewInvoiceButton').css('border-color', "#27b980");

        $('#deleteInvoiceButton').attr('rel-invoice', rowAttr);
        $('#viewInvoiceButton').attr('rel-invoice', rowAttr);
    });

});;