$(".floats").on("keypress", function (event) {
    if (event.which != 46 && (event.which < 47 || event.which > 59)) {
        event.preventDefault();
        if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
            event.preventDefault();
        }
    }
});

$(".nummbers").keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        e.preventDefault();
    }
});

$('body').on('click', '.buttons-excel', function () {

    $(".changeenddate").hide();
    $(".changeenddatee").show();
    location.reload();
});

$('body').on('click', '.carformajax', function () {
    if ($("#carformajax").valid() === true && $('#supplier').val() > 0) {
        $('.carformajax').prop("disabled", true);
        $('.carformajax').css("background", "red");
        $("#carformajax").submit();
    } else {
        if ($('#supplier').val() <= 0) {
            alert('يجب اختيار العميل اولا');
        }
        $('.carformajax').prop("disabled", false);
    }
});

$('form#carformajax').submit(function (e) {
    e.preventDefault();
    var action = $('#carformajax').attr('action');
    var dosave = $('#carformajax').attr('data-dosave');
    var formData = new FormData(this);
    $.ajax({
        url: action + dosave,
        type: 'POST',
        dataType: 'json',
        data: formData,
        success: function (data) {
            if (data > 0) {
                window.location = action + '?do=show';
            } else {

                window.location = action;
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });

});


selectRefresh2();
function selectRefresh2() {
    $('select.selectnew').select2({
        width: '100%'
    });
}

fetch_data();
function fetch_data(start_date = '', end_date = '', del = '', data1 = '', data2 = '', data3 = '') {
    var linkcon = $("#getajaxdata").attr('data-controll');
    var table = $('#getajaxdata');
    var dataTable = $('#getajaxdata').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu": [[50, 100, 200, 300, 400, 500, -1], [50, 100, 200, 300, 400, 500, "All"]],
        "language": {
            "emptyTable": "لا يوجد بيانات متاحه",
            "infoEmpty": "لا يوجد بيانات متاحه",
            "infoFiltered": "(filtered1 from _MAX_ total records)",
            "lengthMenu": "العدد _MENU_",
            "search": "بحث:",
            "zeroRecords": "No matching records found",
            "paginate": {
                "previous": "السابق",
                "next": "التالى",
                "last": "الاخير",
                "first": "الاول"
            }
        },
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'copyHtml5',
                exportOptions: {
                    columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
                }
            },
            {
                extend: 'csvHtml5',
                exportOptions: {
                    columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
                }
            },
            {
                extend: 'print',
                exportOptions: {
                    columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
                }
            },
            {
                extend: 'excelHtml5',
                exportOptions: {
                    columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
                }
            },
            {
                extend: 'pdfHtml5',
                exportOptions: {
                    columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
                }
            },
            'colvis'
        ],
        "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
        "order": [[0, "desc"]],
        "displayLength": 50,
        "columnDefs": [
            { "className": "dt-center", "targets": "_all" }
        ],
        "ajax": {
            url: linkcon,
            type: "POST",
            data: {
                start_date: start_date,
                end_date: end_date,
                del: del,
                data1: data1
            }
        }
    });

}

$('body').on('change', '.searchdata', function () {
    var start_date = $('#start_date').val();
    var end_date = $('#end_date').val();
    var del = $("#del").attr("checked") ? 1 : '';
    var data1 = $("select[name=data1]").val();
    $('#getajaxdata').DataTable().destroy();
    fetch_data(start_date, end_date, del, data1);

});


getselectjoin();

function getselectjoin() {
    $(".getselectjoin").select2({
        allowClear: true,
        // minimumInputLength: 1,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: 'importContractControllerAjax.php?do=getselectjoin',
            dataType: 'json',
            type: "POST",
            data: function (term) {
                var itr = $(this).attr('data-itr');
                var parentcol = $(this).attr('data-parent');
                var parentid = $('#' + parentcol + itr).val();
                var placeholder = $('#' + parentcol + itr).attr('data-placeholder');
                if (parentcol != '' && parentid == '') {
                    alert(' يجب اختيار  ' + placeholder + ' اولآ');
                    return false;
                }
                return {
                    searchTerms: term,
                    tablesearch: $(this).attr("data-search"),
                    table: $(this).attr('data-table'),
                    join: $(this).attr('data-join'),
                    filter: $(this).attr('data-filter'),
                    parentid: parentid,
                    parentcol: parentcol,
                };
            },
            results: function (data) {
                return { results: data };
            }
        },
        formatResult: function (data) {
            return '<span>' + data.text + '</span >';

        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = { id: item[0], text: item[1] };
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    });
}

$('body').on('click', '.removeteble', function () {
    var id = $(this).attr('data-id');
    var table = $(this).attr('data-table');
    if (confirm('هل انت متاكد من الحذف ؟')) {
        var thisis = $(this);
        $.post('importContractControllerAjax.php?do=removeteble', { id: id, table: table }, function (data) {
            if (data == 1) {
                thisis.parent().parent().remove();
            } else {
                alert('حدث خطأ أثناء التنفيذ');
            }
        });
    } else {
        alert('لماذا ضغطت إلغاء؟ يجب أن تكون قد أكدت');
    }
});

$('body').on('click', '.removecontroller', function () {
    var id = $(this).attr('data-id');
    var controll = $(this).attr('data-controll');
    if (confirm('هل انت متاكد من الحذف ؟')) {
        var thisis = $(this);
        $.post(controll + '.php?do=removecontroller', { id: id }, function (data) {
            if (data == 1) {
                thisis.parent().parent().remove();
            } else {
                alert('حدث خطأ أثناء التنفيذ');
            }
        });
    } else {
        alert('لماذا ضغطت إلغاء؟ يجب أن تكون قد أكدت');
    }
});


$(".getselect").select2({
    allowClear: true,
    placeholder: "اختر ",
    // minimumInputLength: 1,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: 'importContractControllerAjax.php?do=getselect',
        dataType: 'json',
        type: "POST",
        data: function (term) {
            var itr = $(this).attr('data-itr');
            var parentcol = $(this).attr('data-parent');
            var parentid = $('#' + parentcol + itr).val();
            var placeholder = $('#' + parentcol + itr).attr('data-placeholder');
            if (parentcol != '' && parentid == '') {
                alert(' يجب اختيار  ' + placeholder + ' اولآ');
                return false;
            }
            return {
                searchTerms: term,
                tablesearch: $(this).attr("data-search"),
                table: $(this).attr('data-table'),
                del: $(this).attr('data-del'),
                filter: $(this).attr('data-filter'),
                parentcol: parentcol,
                parentid: parentid,
            };
        },
        results: function (data) {
            return { results: data };
        }
    },
    formatResult: function (data) {
        return '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        var data = { id: item[0], text: item[1] };
        callback(data);
    },
    //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});

$('body').on('click', '.delRow', function () {
    var itr = $(this).attr('data-itr');
    var table = $(this).attr('data-container');
    var thisis = $(this);
    if (confirm('هل انت متاكد من الحذف ؟')) {
        $(this).parent().parent().remove();
    } else {
        alert('لماذا ضغطت إلغاء؟ يجب أن تكون قد أكدت');
    }
});

$(".getselectparent").select2({
    allowClear: true,
    // minimumInputLength: 1,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: 'importContractControllerAjax.php?do=getselectparent',
        dataType: 'json',
        type: "POST",
        data: function (term) {
            var itr = $(this).attr('data-itr');
            var parentcol = $(this).attr('data-parent');
            var parentid = $('#' + parentcol + itr).val();
            var placeholder = $('#' + parentcol + itr).attr('data-placeholder');
            if (parentcol != '' && parentid == '') {
                alert(' يجب اختيار  ' + placeholder + ' اولآ');
                return false;
            }

            return {
                searchTerms: term,
                tablesearch: $(this).attr("data-search"),
                table: $(this).attr('data-table'),
                filter: $(this).attr('data-filter'),
                parentid: parentid,
                parentcol: parentcol,
            };
        },
        results: function (data) {
            return { results: data };
        }
    },
    formatResult: function (data) {
        return '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        var data = { id: item[0], text: item[1] };
        callback(data);
    },
    //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});

function deldata() {
    var deldata = Number($('.deldata').val());
    if (deldata > 1) {
        $('input').attr('readonly', 'readonly');
        $('textarea').attr('readonly', 'readonly');
        $("select").attr("disabled", "disabled");

    }
}

function selectedit2() {
    $(".selectedit").each(function () {
        var ids = Number($(this).attr('data-id'));
        var texts = $(this).attr('data-text');
        var table = $(this).attr('data-table');
        $("#" + table).select2("data", { id: ids, text: texts });
    });

}

$('body').on('click', '.restall', function () {
    $('#getdata').html('');
    $("#restall").val(1);
    var cd = (new Date()).toISOString().split('T')[0];
    $("#start_date").val(cd);
    $("#end_date").val(cd);
    $("#clientid").val('').change();
    $("#restall").val(0);
});
function DataTablereload() {
    $('.reportstable').dataTable({});
}

//Import Contract
$(document).ready(function () {

    var supplierWithAddOption = (Number($('#supplierWithAddOption').val()) == 1) ? 0 : 1;
    var withNakdi = (Number($('#withNakdi').val()) == 1) ? 0 : 1;
    var clientval = $('#clientsearchvalue').val();
    if(!clientval)
        clientval=  0;
    $(".select2Supp").select2({
        placeholder: "العميل",
        minimumInputLength: clientval,
        inimumInputLength: 0,
        multiple: false,
        quietMillis: 100,
        formatInputTooShort: function (input, min) {
            var n = min - input.length;
            $lenMsg = '<ul class="select2-results">';
            if (supplierWithAddOption == 1)
                $lenMsg += '<li class="select2-results-dept-0 select2-result select2-result-selectable" onclick="newOptionAtInputTooShort();"><div class="select2-result-label newoption"><span class="newoption">اضافة عميل جديد</span></div></li>';
            $lenMsg += '</ul><div class="select2-result-label"><span>من فضلك أدخل ' + n + ' حروف أكثر</span></div>';
            // Append it to the select
            return $lenMsg;
        },
        ajax: {
            url: "clientControllerAjax.php?do=select2ClientsAjax",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 7, // page size
                    withAddOption: supplierWithAddOption,
                    withNakdi: withNakdi,
                    //jsonRowRet: 1,
                };
            },
            results: function (data) {
                return { results: data };
            }
        },
        formatResult: function (data) {
            if (Number(data.id) == -2) {
                return '<span class="newoption">' + data.text + '</span >';
            } else {
                return '<span>' + data.text + '</span >';
            }
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = { id: item[0], text: item[1], productquantity: item[2], price: item[3] };
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    }).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
        $('.newoption').parent().addClass('newoption');
    }).on("select2-selecting", function (e) {
        // the class to make diffrence of change from select2 itself "choose another option" ,it wont exist for triggering change
        $('#supplier').addClass('selectingClass');
    })
    //this is needed for ajax =>to obtain id from it  and use in ajax
    $('#supplier').select2('data', { id: $('#oldsupplierid').val(), text: $('#oldsuppliername').val() });
    
    $("#supplier").change(function (e, changePrice, initialSupp_PriceType = '', dontRepeat = '', action = '') {
        var suppdata = $('#supplier').select2('data');
    
        var theselectedvalue = $(this).val();
        multiclient = $("#multiclient").val();
        //alert( var multiclient);
        //alert('sellbillAjaxController.php?do=clientprice&id='+theselectedvalue);
        if (theselectedvalue == "-2") {
            var elemposition = $(this).data('position');
            $("#myModal1").find(".savemodel1").attr('data-position', elemposition);
            $('#myModal1').modal('show');
        }
        return false;
    });

    $('#chasiNo').on('change', function () {
        let chasis = $(this).val();
        let contractId = $('#contractId').val();
        if (chasis != '') {
            $.post('importContractController.php?do=checkExist', { chasis: chasis, id:contractId }, function (data) {
                if(data != -1){
                    if(data == 1){
                        alert('رقم الشاسيه موجود بالفعل');
                        $('#chasiNo').val('');
                    }
                }
            });
        }
    });
});


function newOptionAtInputTooShort() {
    var suppdata = $('#supplier').select2('data');
    $('#supplier').select2('data', { id: -2, text: 'اضافة عميل جديد' }).change();
    $('#supplieridBeforeChange').val(suppdata.id);
    $('#suppliernameBeforeChange').val(suppdata.text);
}

$('body').on('click', '.carsformajax', function () {
    if ($("#carsformajax").valid() === true && $('#productid').val() > 0) {
        $('.carsformajax').prop("disabled", true);
        $('.carsformajax').css("background", "red");
        $("#carsformajax").submit();
    } else {
        if ($('#productid').val() <= 0) {
            alert('يجب اختيار المنتج اولا');
        }
        $('.carsformajax').prop("disabled", false);
    }
});

$('form#carsformajax').submit(function (e) {
    e.preventDefault();
    var action = $('#carsformajax').attr('action');
    var dosave = $('#carsformajax').attr('data-dosave');
    var formData = new FormData(this);
    $.ajax({
        url: action + dosave,
        type: 'POST',
        dataType: 'json',
        data: formData,
        success: function (data) {
            if (data > 0) {
                window.location = action + '?do=show';
            } else {
                window.location = action;
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });
});
    