
var formatResult;

$('.savemodelclient').on('click', function () {
    var formData = new FormData($('#clientInfo')[0]);
    formData.append("file_faida", "file_faida");
    $.ajax({
        type: 'POST',
        url: 'clientControllerAjax.php?do=addclient',
        data: formData,
        processData: false,
        contentType: false,

        success: function (data) {
            if (data == '2')//اسم العميل مكرر
            {
                $("#newclientName").val("");
                $("#nameError").css("display", "block");
            }
            else
            {


                if (data == "3") //كود العميل مكرر
                {
                    alert('كود العميل مكرر');
                }
                else if (data == "1") //ادخل اسم العميل
                {
                    alert('ادخل اسم العميل');
                }
                else//success
                {
                    $("#clientDiv").html(data);
                    //alert("يرجى إدخال البيانات بشكل صحيح");
                    $('#myModal1').modal('hide');
                    var theselectedvalue = $("#newclientName").val();
                    $("#tempclientName").val($("#supplier option[value='" + theselectedvalue + "']").text());
                    //empty modal box's inputs' values
                    emptyClientModalForm();
                }
            }
        }
    });

});

$('.savemodel2').on('click', function () {


    $('#myModal1').modal('hide');

    $("#supplier").val("1");
    $('select').select2();

    $("#tempclientName").val("نقدى");

    emptyClientModalForm();
});

function emptyClientModalForm()
{

    $('#clientInfo').find(':input').each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (type == 'text' || type == 'password' || tag == 'textarea' ||type == 'number'||type == 'file')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.value = '-1';

    });
}


$('#clientareaid').select2({
    placeholder: "اختر الشركة  - المنطقة",
    //minimumInputLength: 2,
    //triggerChange: true,
    //allowClear: true,
    ajax: {
        url: 'clientControllerAjax.php?do=getclientarea',
        dataType: 'json',
        type: "POST",
        data: function (term) {
            return {
                searchTerms: term,
                //governmentid : $('#clientgovernmentid').val()
            };
        },
        results: function (data) {
            return {
                results: data,
            };
        }
    },
    formatResult: formatResult,
//        initSelection: function (element, callback) {
//            var item = element.val().split(':');
//            var data = {id: item[0], name: item[1]};
//            callback(data);
//        }
});
$('#clientareaid2').select2({
    placeholder: "اختر الشركة  - المنطقة",
    //minimumInputLength: 2,
    //triggerChange: true,
    //allowClear: true,
    ajax: {
        url: 'clientControllerAjax.php?do=getclientarea',
        dataType: 'json',
        type: "POST",
        data: function (term) {
            return {
                searchTerms: term,
                //governmentid : $('#clientgovernmentid').val()
            };
        },
        results: function (data) {
            return {
                results: data,
            };
        }
    },
    formatResult: formatResult,
//        initSelection: function (element, callback) {
//            var item = element.val().split(':');
//            var data = {id: item[0], name: item[1]};
//            callback(data);
//        }
});
$("#clientareaid2").select2("data", {id: $('#clientareaId').val(), text: $('#governmentName').val() + ' - ' + $('#clientareaName').val()});


var mydate=new Date();
jQuery(document).on('focus',".date", function(){
    jQuery(this).datetimepicker({
        format : 'yyyy-mm-dd',
        autocomplete:false,
        autoclose :  true,
        todayHighlight : true,
        pickTime: false,
        minView: 2,
        zIndex:9999,
        startDate : new Date()

    }).on('changeDate', function(ev)
    {
        mydate=jQuery('.awdatepicker').val();
    });
});




$(document).on('click',function (event) {
    var modal = document.getElementById("myModal");;
//
    if (event.target == modal) {
        $('#myModal').modal('hide');
        // $('.modal-backdrop').modal('hide');
        $('.modal-backdrop').remove();
    }

});

$(document).on('click', '#approval,#Refusal ', function () {

    var id = $(this).data('id');

    $.post("FaidaAjaxController.php?do=getDataFaida", {id: id}, function (data) {
        var obj = jQuery.parseJSON( data );

        $('.store').val(obj.storeName);
        $('.client').val(obj.clientname);
        $('.premium').val(obj.premmium);
        $('.totalafteprem').val(obj.total_amount);
        $('.textDetails').val(obj.comment);
        $('.faida_id').val(obj.id);
        $('.prem').val(obj.installment_duration).change();
        $('.presenter').val(obj.presenter);


    });

});

$(document).on('click', '#approval,#Refusal', function () {

    var id = $(this).data('id');

    $.post("FaidaAjaxController.php?do=getDataFaidaProduct", {id: id }, function (data) {
        // console.log(data);
        $('.pro').html(data);
    });

});

function CustomAlert(){



    this.alert = function(message,title){
        var id = $('.faida_id').val();
        document.body.innerHTML = document.body.innerHTML + '<form action="FaidaDireController.php?do=refusal" method="post" id="form1" class="form-horizontal">'+
            '<div id="dialogoverlay"></div><div id="dialogbox" class="slit-in-vertical"><div><div id="dialogboxhead">' +
            '</div><div id="dialogboxbody"></div><div id="dialogboxfoot"></div></div></div>'+'</form>';

        let dialogoverlay = document.getElementById('dialogoverlay');
        let dialogbox = document.getElementById('dialogbox');

        let winH = window.innerHeight;
        dialogoverlay.style.height = winH+"px";

        dialogbox.style.top = "50px";

        dialogoverlay.style.display = "block";
        dialogbox.style.display = "block";

        document.getElementById('dialogboxhead').style.display = 'block';

        if(typeof title === 'undefined') {
            document.getElementById('dialogboxhead').style.display = 'none';
        } else {
            document.getElementById('dialogboxhead').innerHTML = '<i class="fa fa-exclamation-circle" aria-hidden="true"></i> '+"سبب الرفــــــــــض";
        }
        document.getElementById('dialogboxbody').innerHTML ='<label style="' +
            '    margin-bottom: 20px;' +
            '">التعليق : </label>'+'<textarea name="comment" id="comment" cols="65" rows="5"></textarea> <input type="hidden" id="faida_id" name="faida_id" value="'+id+'">';
        document.getElementById('dialogboxfoot').innerHTML = '<button class="pure-material-button-contained" style="' +
            'float: left;' + 'margin-right: 13px;'+
            'margin-bottom: 20px;' +
            '" onclick="customAlert.cancel()">الغاء</button>'

            +'<button class="pure-material-button-contained active" style="' +
            'float: left;' +
            'margin-bottom: 20px;' +
            '" onclick="customAlert.ok()">موافق</button>';

    }

    this.ok = function(){
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dialogoverlay').style.display = "none";
        document.getElementById("myModal").style.display = "none";
        // var modal = document.getElementById("myModal");
//
        $('#myModal').modal('hide');
        // $('.modal-backdrop').modal('hide');
        $('.modal-backdrop').remove();
    }

    this.cancel = function(){
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dialogoverlay').style.display = "none";
        document.getElementById("myModal").style.display = "none";
        // var modal = document.getElementById("myModal");
//
        $('#myModal').modal('hide');
        // $('.modal-backdrop').modal('hide');
        $('.modal-backdrop').remove();
    }
}

let customAlert = new CustomAlert();



var tablesellnotreviewed = $('#approvalTable');
var otablesellnotreviewed = tablesellnotreviewed.DataTable({
    "processing": true,
    "stateSave": true,
    "serverSide": true,
    "ajax": {url: 'FaidaAjaxController.php?do=showallajaxapproval', type: 'POST',
    }, //  server side processing
    dom: 'Bfrtip',
    buttons: [//'csv', 'pdf'
        {
            extend: "print",
            className: "btn dark btn-outline",
            text: "طباعه<i class='fa fa-print'></i>",
            exportOptions: {
                //columns: '.show-print'
                columns: ':visible'
            },
            customize: function (win) {
                $(win.document.body).find('table')
                //.addClass('compact')
                    .css('direction', 'rtl');
            }
        }, {
            extend: "copy",
            className: "btn red btn-outline",
            text: "نسخ",
            exportOptions: {
                //columns: '.show-print'
                columns: ':visible'
            }
        }, {
            extend: "excel",
            className: "btn yellow btn-outline ",
            text: "اكسل",
            exportOptions: {
                //columns: '.show-print'
                columns: ':visible'
            }
        }, {
            extend: "colvis",
            className: "btn dark btn-outline",
            text: "المكونات"
        }
    ], "bStateSave": true,
    "language": {
        "aria": {
            "sortAscending": ": Used to order Ascending",
            "sortDescending": ": Used to order Descending"
        },
        "emptyTable": "لا يوجد بيانات",
        "info": "عرض من  _START_ إلى  _END_  - عدد الاقساط الموافق عليها البحث _TOTAL_",
        "infoEmpty": "لا يوجد بيانات",
        "infoFiltered": "(تنقيه  من عدد الاقساط كلى _MAX_)",
        "lengthMenu": " _MENU_ عنصر",
        "search": "البحث:",
        "zeroRecords": "لا يوجد بيانات تشابه البحث"
    },
    responsive: !0,
    "columnDefs": [],
    order: [
        [0, "asc"]
    ],
    paging: true,
    lengthMenu: [
        [5, 10, 15, 20, 50, -1],
        [5, 10, 15, 20, 50, "All"]
    ],
    pageLength: 10,
    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>>"
});


var tablesellnotreviewed = $('#RefusalTable');
var otablesellnotreviewed = tablesellnotreviewed.DataTable({
    "processing": true,
    "stateSave": true,
    "serverSide": true,
    "ajax": {url: 'FaidaAjaxController.php?do=showallajaxRefusal', type: 'POST',
    }, //  server side processing
    dom: 'Bfrtip',
    buttons: [//'csv', 'pdf'
        {
            extend: "print",
            className: "btn dark btn-outline",
            text: "طباعه<i class='fa fa-print'></i>",
            exportOptions: {
                //columns: '.show-print'
                columns: ':visible'
            },
            customize: function (win) {
                $(win.document.body).find('table')
                //.addClass('compact')
                    .css('direction', 'rtl');
            }
        }, {
            extend: "copy",
            className: "btn red btn-outline",
            text: "نسخ",
            exportOptions: {
                //columns: '.show-print'
                columns: ':visible'
            }
        }, {
            extend: "excel",
            className: "btn yellow btn-outline ",
            text: "اكسل",
            exportOptions: {
                //columns: '.show-print'
                columns: ':visible'
            }
        }, {
            extend: "colvis",
            className: "btn dark btn-outline",
            text: "المكونات"
        }
    ], "bStateSave": true,
    "language": {
        "aria": {
            "sortAscending": ": Used to order Ascending",
            "sortDescending": ": Used to order Descending"
        },
        "emptyTable": "لا يوجد بيانات",
        "info": "عرض من  _START_ إلى  _END_  - عدد الاقساط المرفوضه البحث _TOTAL_",
        "infoEmpty": "لا يوجد بيانات",
        "infoFiltered": "(تنقيه  من عدد الاقساط كلى _MAX_)",
        "lengthMenu": " _MENU_ عنصر",
        "search": "البحث:",
        "zeroRecords": "لا يوجد بيانات تشابه البحث"
    },
    responsive: !0,
    "columnDefs": [],
    order: [
        [0, "asc"]
    ],
    paging: true,
    lengthMenu: [
        [5, 10, 15, 20, 50, -1],
        [5, 10, 15, 20, 50, "All"]
    ],
    pageLength: 10,
    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>>"
});


$('body').on('change', '.prem', function () {

    var total = 0;
    var rate = Number($(this).val());
    $('#premium').val(rate);
    var totalafteprem = Number($('#totalaftepremhidden').val());

    if(!totalafteprem){
        var totalafteprem = Number($('#sellbillprice').val());
    }

    total += totalafteprem + (totalafteprem*rate/100);

    $('#totalafteprem').val(total);
    // $('#totalaftepremhidden').val(total);


});

$(document).on('keyup', '#premium', function () {
    var total = 0;
    var rate = Number($(this).val());
    // var total_amount = Number($('#sellbillprice').val());
    // total += total_amount + (total_amount*rate/100);
    var totalafteprem = Number($('#totalaftepremhidden').val());

    if(!totalafteprem){
        var totalafteprem = Number($('#sellbillprice').val());
    }


    total += totalafteprem + (totalafteprem*rate/100);
    $('#totalafteprem').val(total);
    // $('#totalaftepremhidden').val(total);

});


$(document).on('keyup', '#presenter', function () {
    var total = 0;
    var presenter = Number($(this).val());
    var total_amount = Number($('#sellbillprice').val());
    total += total_amount - presenter;
    $('#totalafteprem').val(total);
    $('#totalaftepremhidden').val(total);

});