formatResult = function (data) {
    if (Number(data.id) == -1) {
        return  '<span class="newoption">' + data.text + '</span >';
    } else {
        return  '<span>' + data.text + '</span >';
    }
    //return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">' + data.price + '</span ><span  style="float: left;  margin-left: 5px;"  > ' + data.productquantity + '';

}
$('.productprog').select2({
    placeholder: "اختر منتج",
    //allowClear: true,
    minimumInputLength: document.getElementById("searchvalue").value,
    //minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "sellbillAjaxController.php?do=getProducts2",
        dataType: 'json',
        data: function (term, page) {
            var proitr = $(this).data('itr');
            return {
                term: term, //search term
                page_limit: 10, // page size
                catid: $('#catprog' + proitr).val(),
                newProductOption: 1,
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: formatResult,
    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);
    }
}).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
    $('.newoption').parent().addClass('newoption');
}).on('change', function (e) {
    var proitr = $(this).data('itr');
    $('#sizeprog' + proitr).val('').change();
    $('#colorprog' + proitr).val('').change();
});
$('.catprog').select2({
    placeholder: "اختر تصنيف",
    //allowClear: true,
    minimumInputLength: 0, //document.getElementById("searchvalue").value,
    //minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "productControllerAjax.php?do=gellastlevelcats",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, //search term
                page_limit: 10, // page size
                newProductOption: 1, // page size
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: formatResult,
    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);
    }
}).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
    $('.newoption').parent().addClass('newoption');
}).on('change', function (e) {
    var catitr = $(this).data('itr');
    $('#productprog' + catitr).val('').change();
});
$('.sizeprog').select2({
    placeholder: "اختر مقاس",
    //allowClear: true,
    minimumInputLength: 0, //document.getElementById("searchvalue").value,
    //minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "productControllerAjax.php?do=getsizecolor",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, //search term
                page_limit: 10, // page size
                newOption: 1, // page size
                type: 0, // page size
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: formatResult,
    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);
    }
}).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
    $('.newoption').parent().addClass('newoption');
}).on('change', function (e) {
//    var catitr = $(this).data('itr');
//    $('#productprog' + catitr).val('').change();
});

$('.colorprog').select2({
    placeholder: "اختر لون",
    //allowClear: true,
    minimumInputLength: 0, //document.getElementById("searchvalue").value,
    //minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "productControllerAjax.php?do=getsizecolor",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, //search term
                page_limit: 10, // page size
                newOption: 1, // page size
                type: 1, // page size
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: formatResult,
    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);
    }
}).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
    $('.newoption').parent().addClass('newoption');
}).on('change', function (e) {
//    var catitr = $(this).data('itr');
//    $('#productprog' + catitr).val('').change();
});


$('#billAsExcelFile').change(function () {
    var extention = $(this).val().split('.').pop().toLowerCase();
    var allowedExt = ['xlsx', 'xls', 'csv'];
    if (allowedExt.includes(extention)) {
        $('#billAsExcelForm').submit();
    } else {
        alert('عفوا امتذاذ الملف غير مسموح به');
    }
});



$('#savebtn').click(function () {
    if (!$(this).hasClass('processing...')) {
        $(this).addClass('processing...');
        var thisis = $(this);
        var itr = Number($('#itr').val());
        var flag1 = validateFromCheckExist(itr);
        if (flag1 == 0) {
            alert('عفوا بعض الحقول المطلوبة فارغة');
            thisis.removeClass('processing...');
            return false;
        }
        $('#myProductForm').submit();
    }
});

function validateFromCheckExist(itr) {
    var flag = 1;
    for (var i = 1; i <= itr; i++) {
        if ($('#catprog' + i).val() == "" || $('#productprog' + i).val() == "" || $('#sellAllPrice' + i).val() == "" || $('#sellHalfPrice' + i).val() == "" || $('#sellUnitPrice' + i).val() == "") {
            $('#sellAllPrice' + i).parent().parent().addClass('danger');
            flag = 0;
        } else {
            $('#sellAllPrice' + i).parent().parent().removeClass('danger');
        }
    }
    return flag;
}
function validateFromCheckRepeat(itr) {
    //here we check if names of cats and products are repeated
    var flag = 1;
    for (var i = 1; i <= itr; i++) {
        if (Number($('#catprog' + i).val()) == -1 && Number($('#catIsLinked' + i).val()) == 0) {
            var checkRes = goAjax($('#catname' + i).val(), 'productcat');
            if (checkRes == 0) {//not repeated
                $('#sellAllPrice' + i).parent().parent().removeClass('danger');
            } else if (checkRes == 1) {//repeated
                $('#sellAllPrice' + i).parent().parent().addClass('danger');
                $('#catNameFromUser' + i).attr('type', 'text');
                flag = 0;
                return flag;
            }
        }
        //if cat is new so will be the product so check only for existing cats
        if (Number($('#catprog' + i).val()) > 0 && Number($('#productprog' + i).val()) == -1 && Number($('#productIsLinked' + i).val()) == 0) {
            var checkRes = goAjax($('#productprog' + i).val(), 'product&catid=' + $('#catprog' + i).val());
            if (checkRes == 0) {//not repeated
                $('#sellAllPrice' + i).parent().parent().removeClass('danger');
            } else if (checkRes == 1) {//repeated
                $('#sellAllPrice' + i).parent().parent().addClass('danger');
                $('#productNameFromUser' + i).attr('type', 'text');
                flag = 0;
                return flag;
            }
        }
    }
    return flag;
}
function goAjax(name, tableName, fieldName, i) {
    var ajaxRes = 1;//default repeated
    $.ajax({
        //type: "POST",
        url: 'checkRedundantNames.php?name=' + name + '&tablename=' + tableName,
        async: false,
        success: function (data) {
            ajaxRes = data;
        }
    });
    return ajaxRes;
}

$(function () {
    //set default as add new
    var itr = Number($('#itr').val());
    for (var i = 1; i <= itr; i++) {
        if ($('#catprog' + i).val() == "" && Number($('#catIsLinked' + i).val()) == 0) {
            $('#catprog' + i).select2("data", {id: -1, text: 'تصنيف جديد'});

        }
        //if cat is new so will be the product so check only for existing cats
        if ($('#productprog' + i).val() == "" && Number($('#productIsLinked' + i).val()) == 0) {
            $('#productprog' + i).select2("data", {id: -1, text: 'منتج جديد'});
        }
        //if cat is new so will be the product so check only for existing cats
        if ($('#sizeprog' + i).val() == "" && Number($('#sizeIsLinked' + i).val()) == 0) {
            $('#sizeprog' + i).select2("data", {id: -1, text: 'مقاس جديد'});
        }
        //if cat is new so will be the product so check only for existing cats
        if ($('#colorprog' + i).val() == "" && Number($('#colorIsLinked' + i).val()) == 0) {
            $('#colorprog' + i).select2("data", {id: -1, text: 'لون جديد'});
        }
    }
});