$(document).ready(function () {
    $("#client").select2({
        placeholder: "اختر عميل ",
        minimumInputLength: 0,
        //  minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "clientControllerAjax.php?do=select2ClientsAjax",
            dataType: 'json',
            data: function (term, page) {
                //  alert(term);
                return {
                    term: term, //search term
                    page_limit: 10,
                    withAddOption: 1,
                };
            },
            results: function (data) {
                // alert(term);
                return {results: data};
            }
        },
        formatResult: function (data) {
            return  data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });
    $("#client").live('change', function (e) {
        var val = $(this).val();
        if (val == '-2') {
            $('#newclientName').val("");
            $('#clientRFID').val("");
            $('#newclientdebt').val(0);
            $('#clientaddress').val("");
            $('#clientphone').val("");
            $('#clientmobile').val("");
            $('#clientdetails').val("");
//            if ($('#PSCard').length > 0) {
//                $('#PSCard').select2('data', {id: '', text: ''});
//            }
            $('#myclientModal1').modal('show');
        } else if (val != "") {
//            if ($('#PSCard').length > 0) {
//                //$('#PSCard').select2('data', {id: '', text: ''});
//            }
            //choose client data"phone,address" to print
            $.post('clientControllerAjax.php?do=getclientdata', {id: val, getPsCardVal: 1}, function (data) {
                data = JSON.parse(data);
                $('#mobile').val(data.clientmobile);
                $('#rfid').val(data.clientRFID);
                //$('#PSCardVal').val(data.availablePSCardValue);
                $('#PSCardVal').val((data.clientdebt * -1));
            });
        }
    });
    $('.savemodel1').on('click', function (e) {
        //alert($('#clientInfomain').validate().form())
        if ($('#clientInfomain').validate().form())
        {

            var newclientName = $('#newclientName').val();
            var clientRFID = $('#clientRFID').val();
            var clientareaid = $('#clientareaid').val();
            var newclientdebt = $('#newclientdebt').val();
            var clientaddress = $('#clientaddress').val();
            var clientphone = $('#clientphone').val();
            var clientmobile = $('#clientmobile').val();
            var clientdetails = $('#clientdetails').val();

            if (newclientName == '') {
                e.preventDefault();
                if ($('#nameError').html() == "")
                {
                    $('#nameError').append("<p style='color: red;'>ادخل اسم العميل </p>");
                }
            } else {
                $.post('clientControllerAjax.php?do=addclient3', {newclientName: newclientName, clientRFID: clientRFID, clientaddress: clientaddress, clientphone: clientphone, clientmobile: clientmobile, newclientdebt: newclientdebt, clientdetails: clientdetails, clientareaid: clientareaid, control: 1}, function (data) {

                    /// document.getElementById('').style.display = 'none';
                    $('#myclientModal1').modal('hide');
                    if (data == 2) {
                        alert('هذا العميل تمت اضافتة من قبل ');
                        //location.reload();
                    } else if (data == 3) {
                        alert('رقم الكود تمت اضافتة من قبل ');
                        //location.reload();
                    } else {
                        data = data.split(',');
                        $("#client").val(data[0]).change();
                        $("#client").select2("data", {id: data[0], text: data[1]});

                        //$("#clientDiv").html(data);


                        $(':input', '#clientInfo').val('');
                    }
                });
            }

        }


    });
    //
    $('#rfid').on('blur', function (e) {
        var rfid = $('#rfid').val();
        getclientDataByRFID(rfid);
    });
    $('#rfid').on('keydown', function (e) {
        var key = e.which || e.keyCode;
        if (key == 13) {
            e.preventDefault();
            e.stopPropagation();
            var rfid = $('#rfid').val();
            getclientDataByRFID(rfid);
        }
    });
    function getclientDataByRFID(rfid) {
        if (rfid == "") {
            $('#mobile').val("");
            $('#rfid').val("");
            $("#client").select2("data", {id: "", text: ""});
        } else {
            $.post('clientControllerAjax.php?do=getclientdatarfid', {rfid: rfid, getPsCardVal: 1}, function (data) {
                data = JSON.parse(data);
                $('#mobile').val(data.clientmobile);
                $('#rfid').val(data.clientRFID);
//                $('#PSCardVal').val(data.availablePSCardValue);
                $('#PSCardVal').val((data.clientdebt * -1));
                //$("#client").val(data[0]).change();
                $("#client").select2("data", {id: data.clientid, text: data.clientname});
            });
        }
    }
});

/*if ($('#PSCard').length > 0) {
 $("#PSCard").select2({
 placeholder: "اختر كارت العميل ",
 minimumInputLength: 0,
 //  minimumInputLength: 3,
 multiple: false,
 quietMillis: 100,
 ajax: {
 url: "clientControllerAjax.php?do=getClientPSCards",
 dataType: 'json',
 data: function (term, page) {
 //  alert(term);
 return {
 term: term, //search term
 page_limit: 10,
 client: $("#client").val(),
 };
 },
 results: function (data) {
 // alert(term);
 return {results: data};
 }
 },
 formatResult: function (data) {
 return  data.text;
 },
 initSelection: function (element, callback) {
 var item = element.val().split(':');
 var data = {id: item[0], text: item[1]};
 callback(data);
 }
 }).on('change', function () {
 $('#PSCardVal').val($("#PSCard").select2('data').cardVal);
 $('#cardid').val($("#PSCard").select2('data').cardid);
 var totalReq = Number($('#totalReq').val());
 var PSCardVal = Number($('#PSCardVal').val());
 if (PSCardVal >= totalReq) {
 $('#cardPayed').val(totalReq);

 $('#cashPayed').val("");
 $('#cashPayedDiv').hide();

 $('#Remain').val(0);
 } else {
 $('#cardPayed').val(PSCardVal);

 $('#cashPayed').val("");
 $('#cashPayedDiv').show();

 var remain = (totalReq - PSCardVal).toFixed(2);
 $('#Remain').val(remain);
 }
 });

 }*/
if ($('#PSCardNoClient').length > 0) {
    $("#PSCardNoClient").select2({
        placeholder: "اختر كارت ",
        minimumInputLength: 0,
        //  minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "clientControllerAjax.php?do=getPSCards",
            dataType: 'json',
            data: function (term, page) {
                //  alert(term);
                return {
                    term: term, //search term
                    page_limit: 10,
                    //client: $("#client").val(),
                };
            },
            results: function (data) {
                // alert(term);
                return {results: data};
            }
        },
        formatResult: function (data) {
            return  data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });
}


$('#saveIncBtn').on('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    if (!$(this).hasClass('processing...')) {
        $(this).addClass('processing...');

        var client = Number($('#client').val());
        var cardid = Number($('#cardid').val());
        if (client > 0 && cardid > 0) {
            $('#chargeCardForm').submit();
        } else {
            $(this).removeClass('processing...');
            alert('عفوا لم تختر عميل');
        }
    }
});
$('.calcRemain').on('change', function (e) {
    var PSCardVal = Number($('#PSCardVal').val());
    var cardPayed = Number($('#cardPayed').val());
    var totalReq = Number($('#totalReq').val());

    var remain = (totalReq - cardPayed).toFixed(2);
    $('#Remain').val(remain);
    $('#cashPayed').val(remain);

    if (remain > 0) {
        $('#cashPayedDiv').show();
    } else {
        $('#cashPayedDiv').hide();
    }
});
$('#paycard').on('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    if (!$(this).hasClass('processing...')) {
        $(this).addClass('processing...');

        var flag = checkPayCardRequired();
        if (flag == 1) {
            $('#chargeCardForm').submit();
        } else {
            $(this).removeClass('processing...');
        }
    }
});
function checkPayCardRequired() {
    var flag = 1;
    if (Number($('#client').val()) == 0) {
        flag = 0;
        $('#clientError').show();
    } else {
        $('#clientError').hide();
    }

//    if (Number($('#PSCard').val()) == 0) {
//        flag = 0;
//        $('#PSCardError').show();
//    } else {
//        $('#PSCardError').hide();
//    }

    if (Number($('#cardPayed').val()) == 0) {
        flag = 0;
        $('#cardPayedError').show();
    } else {
        $('#cardPayedError').hide();
    }
    //there is remain after card , no cash payed =>payment is req
    if (Number($('#cashPayed').val()) == 0 && Number($('#Remain').val()) > 0) {
        flag = 0;
        $('#cashPayedError').text('*');
        $('#cashPayedError').show();
    } else if (Number($('#cashPayed').val()) != Number($('#Remain').val())) {
        flag = 0;
        $('#cashPayedError').text('لا بد من دفع المبلغ المطلوب');
        $('#cashPayedError').show();
    } else {
        $('#cashPayedError').hide();
    }
    return flag;
}