// $(document).on('change', "#clientid", function () {
//         var clientid = $(this).val();
//         $.post('comentclientController.php?do=get', {clientid: clientid}, function (data) {
//             alert(data);
//                     $('#clientdata').html(data);

//         });

//     });


//   $('#order_client').on('click', "#day", function () {

// } );


$(document).ready(function () {
    $('#commentsclient').DataTable({
        "order": [[0, "desc"]]
    });
});

$(document).on('change', "#changecoment", function ()
{
    var id = $("#clientid").val();
    var date = $(this).val();
    $.post('comentclientController.php?do=change', {id: id, date: date}, function (data) {
        if (data = 1) {
            alert("تم التعديل التعليق بنجاح");
        } else {
            alert("لم  يتم التعديل");

        }

    });


});


$(document).on('change', "#editcomets", function ()
{
    var id = $(this).attr("data-id");
    var date = $(this).val();

    $.post('comentclientController.php?do=edit', {id: id, date: date}, function (data) {
        if (data = 1) {
            location.reload(true);

            alert("تم التعديل التعليق بنجاح");
        } else {
            alert("لم  يتم التعديل");

        }

    });




});


$(document).on('change', "#chosseclient", function ()
{
    $('#chosseclients').click();

});

$(document).on('click', "#formclient", function ()
{


    var client = $("#clientid").val();

    if (client === "" || client < 0) {

        alert('يجب اختيار العميل  لاضافة التعليق ');

        return false;



    }
});



$(document).on('click', ".delecomment", function ()
{
    var id = $(this).attr("data-id");
    if (confirm("هل تريد حذف التعليق"))
    {
        $.post('comentclientController.php?do=del', {id: id}, function (data) {
            $('#comment' + id).remove();
        });

    } else {
        return false;
    }
});


$(document).on('click', ".editco", function ()
{
    var id = $(this).attr("data-id");
    $('.hico' + id).toggle();
    $('.edco' + id).toggle();

});


$(document).on('click', ".taba", function ()
{

    $('#taba1').toggle();
    $('#taba2').toggle();

});




$(document).on('click', "#day", function () {


    var day = $('#day').val();

    if (day == 0) {
        // $('#names').html(
        //     '<th class="text-center" > التاريخ  </th><th class="text-center" >الاجل</th><th class="text-center"> النقدى</th><th class="text-center"> الاجمالى</th>'

        // );

        // myTable.row( ':eq(0)' ).delete();

        $('#day').val(1);
    } else {
        // $('#names').html(
        //     ' <th class="text-center"  > اسم الفاتوره  </th><th class="text-center" > التاريخ  </th><th class="text-center" >الاجل</th><th class="text-center"> النقدى</th><th class="text-center"> الاجمالى</th>'
        // );

        $('#day').val(0);

    }

    $("#searchclient").click();


});


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

    $('.input-daterange').datepicker({
        todayBtn: 'linked',
        format: "yyyy-mm-dd",
        autoclose: true
    });

    fetch_data('no');

    function fetch_data(is_date_search, start_date = '', end_date = '', day = '')
    {

        var dataTable = $('#order_client').DataTable({
            "processing": true,
            "serverSide": true,
            "displayLength": 10,
            "ajax": {url: "elemam.php",
                type: "POST",
                data: {
                    is_date_search: is_date_search,
                    start_date: start_date,
                    end_date: end_date,
                    day: day,
                }

            },
            "stateSave": true,
            "paginate": true,
            "serverSide": true,
                    // "paginationType": "full_numbers",
                    "aoColumnDefs": [
                        {
                            'targets': [0],
                            'searchable': false,
                            'orderable': false,
                            'className': 'dt-body-center',
                        },
                        {
                            'sClass': 'accountDtails',
                            'orderable': true,
                            "searchable": true,
                            "targets": [1]
                        },
                    ],
            "lengthMenu"
                    : [
                        [5, 10, 25, 50, 100, -1],
                        [5, 10, 25, 50, 100, "All"] // change per page values here
                    ],
            "order"
                    : [
                        [1, "desc"]       // order by drug cat
                    ],
            // set the initial value
            "pageLength": 10,
            "language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "لا يوجد بيانات متاحه",
                "info": "",
                "infoEmpty": "No records found",
                "infoFiltered": "(filtered1 from _MAX_ total records)",
                "lengthMenu": "العدد _MENU_",
                "search": "بحث:",
                "zeroRecords": "No matching records found",
                "paginate": {
                    "previous": "السابق",
                    "next": "التالى",
                    "last": "الاخير",
                    "first": "الاول"
                }
            },
        });
        // $('a.toggle-vis').on( 'click', function (e) {
        //       e.preventDefault();

        //       // Get the column API object
        //       var column = table.column( $(this).attr('data-column') );

        //       // Toggle the visibility
        //       column.visible( ! column.visible() );
        //   } );
    }

    $('#searchclient').click(function () {
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        var day = $('#day').val();


        $('#order_client').DataTable().destroy();
        fetch_data('yes', start_date, end_date, day);

    });



});








$(document).on('click', "#days", function () {
    var day = $('#days').val();

    if (day == 0) {


        $('#days').val(1);
    } else {

        $('#days').val(0);

    }

    $(".sell").click();


});
//
$(document).ready(function () {

    $('.input-daterange').datepicker({
        todayBtn: 'linked',
        format: "yyyy-mm-dd",
        autoclose: true
    });

    fetch_data('no');

    function fetch_data(is_date_search, sell = '', start_date = '', end_date = '', day = '')
    {
        var dataTable = $('#order_clients').DataTable({
            "processing": true,
            "serverSide": true,
            "displayLength": 10,
            "ajax": {url: "elemam.php?do=add",
                type: "POST",
                data: {
                    is_date_search: is_date_search,
                    sell: sell,
                    start_date: start_date,
                    end_date: end_date,
                    day: day,
                }

            },
            "stateSave": true,
            "paginate": true,
            "serverSide": true,
                    // "paginationType": "full_numbers",
                    "aoColumnDefs": [
                        {
                            'targets': [0],
                            'searchable': false,
                            'orderable': false,
                            'className': 'dt-body-center',
                        },
                        {
                            'sClass': 'accountDtails',
                            'orderable': true,
                            "searchable": true,
                            "targets": [1]
                        },
                    ],
            "lengthMenu"
                    : [
                        [5, 10, 25, 50, 100, -1],
                        [5, 10, 25, 50, 100, "All"] // change per page values here
                    ],
            "order"
                    : [
                        [1, "desc"]       // order by drug cat
                    ],
            // set the initial value
            "pageLength": 10,
            "language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "لا يوجد بيانات متاحه",
                "info": "",
                "infoEmpty": "No records found",
                "infoFiltered": "(filtered1 from _MAX_ total records)",
                "lengthMenu": "العدد _MENU_",
                "search": "بحث:",
                "zeroRecords": "No matching records found",
                "paginate": {
                    "previous": "السابق",
                    "next": "التالى",
                    "last": "الاخير",
                    "first": "الاول"
                }
            },
        });

    }

    $('.sell').click(function () {
        var sell = $(this).attr('data-id');
        var start_date = $('#start_dates').val();
        var end_date = $('#end_dates').val();
        var day = $('#days').val();


        $('#order_clients').DataTable().destroy();
        fetch_data('yes', sell, start_date, end_date, day);

    });



});

















// // $(document).ready(function() {
// //     var table = $('#order_client').DataTable( {
// //         "scrollY": "200px",
// //         "paging": false
// //     } );

// //     $('a.toggle-vis').on( 'click', function (e) {
// //         e.preventDefault();

// //         // Get the column API object
// //         var column = table.column( $(this).attr('data-column') );

// //         // Toggle the visibility
// //         column.visible( ! column.visible() );
// //     } );
// // } );




$(document).ready(function () {

 $(".select2product").select2({
                placeholder: "المنتج",
                minimumInputLength: 2,
                multiple: false,
                quietMillis: 100,
                containerCssClass: "wdt300",
                ajax: {
                    url: "sellbillAjaxController.php?do=getProducts2",
                    dataType: 'json',
                    data: function (term, page) {
                        //alert("sellbillAjaxController.php?do=getProducts&term="+term+"&page_limit=10&storeid="+document.getElementById("storeid").value);
                        return {
                            term: term, //search term
                            page_limit: 10, // page size,
                        };
                    },
                    results: function (data) {

                        return {results: data};
                    }
                },
                formatResult: function (data) {
                    return data.text;
                    //            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], productquantity: item[2], price: item[3]};
                    callback(data);
                }

            });
    $("#myTexts").focus();
    // $('#mynameTexts').select2('focus');
    $('#mynameTexts').select2('open');
    $(document).on('keypress', "#myTexts", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            e.stopPropagation();
            getDataAjax($("#myTexts").val());
        }
    });
    $(document).on('change', "#mynameTexts", function (e) {

            getDatanameAjax($("#mynameTexts").val());
        
    });

    $('#searchByParcodeForm').on('submit', function (e) {
        e.preventDefault();
        e.stopPropagation();
        getDataAjax($("#myTexts").val());
    });


     $('#searchByParcodenameForm').on('submit', function (e) {
        getDatanameAjax($("#mynameTexts").val());
    });

});


$(function () {
    setTimeout(function () {
        $('#myTexts').focus();
    }, 1000);
    setTimeout(function () {
         $('#mynameTexts').select2('open');
    }, 1000);
});
var timeOutFunc;
function getDataAjax(search_text) {
    $.ajax({
        type: "POST",
        url: 'productbycode.php?do=getDataAjax',
        data: {search_text: search_text},
        async: false,
        success: function (data) {
            $('#resserror').html("");
            $('#ressEmpty').hide();
            $('#ress').html(data);
            $("#myTexts").val("");
            $("#myTexts").focus();
            clearTimeout(timeOutFunc);
            timeOutFunc = setTimeout(function () {
                $('#ress').html("");
                $('#ressEmpty').show();
                $("#myTexts").focus();
            }, 60000);
        },
        error: function (xhr, ajaxOptions, thrownError) {
//            alert(xhr.status);
//            alert(thrownError);

            $('#ress').html("");
            $('#ressEmpty').hide();
            $('#resserror').html("<br/> <span style='color:red;background-color:yellow;padding: 5px;border-radius: 17px;'>عفوا حدث خطأ حاول مرة اخرى</span> ");
            $("#myTexts").val("");
            $("#myTexts").focus();
            setTimeout(function () {
                $('#ress').html("");
                $('#ressEmpty').show();
                $("#myTexts").focus();
            }, 5000);
        }
    });
}
var timeOutFuncName;
function getDatanameAjax(search_text) {
    $.ajax({
        type: "POST",
        url: 'productbycodename.php?do=getDataAjax',
        data: {search_text: search_text},
        async: false,
        success: function (data) {
            $('#resserror').html("");
            $('#ressEmpty').hide();
            $('#ress').html(data);
            $("#mynameTexts").val("");
              $('#mynameTexts').select2('open');
            clearTimeout(timeOutFunc);
            timeOutFunc = setTimeout(function () {
                $('#ress').html("");
                $('#ressEmpty').show();
                 $('#mynameTexts').select2('open');
            }, 60000);
        },
        error: function (xhr, ajaxOptions, thrownError) {
//            alert(xhr.status);
//            alert(thrownError);

            $('#ress').html("");
            $('#ressEmpty').hide();
            $('#resserror').html("<br/> <span style='color:red;background-color:yellow;padding: 5px;border-radius: 17px;'>عفوا حدث خطأ حاول مرة اخرى</span> ");
            $("#mynameTexts").val("");
              $('#mynameTexts').select2('open');
            setTimeout(function () {
                $('#ress').html("");
                $('#ressEmpty').show();
                  $('#mynameTexts').select2('open');
            }, 5000);
        }
    });
}
// setInterval(#myTexts, 3000);

// load_data();

// function load_data(query)
// {
//  $.ajax({
//   url:"productbycode.php",
//   method:"POST",
//   data:{query:query},
//   success:function(data)
//   {
//   }
//  });
// }
// $('#myTexts').keyup(function(){
//  var search = $(this).val();
//  if(search != '')
//  {
//   load_data(search);
//  }
//  else
//  {
//   load_data();
//  }
// });


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

//  load_data();

//  function load_data(query)
//  {
//   $.ajax({
//    url:"productbycode.php",
//    method:"POST",
//    data:{query:query},
//    success:function(data)
//    {
//     // $('#result').html(data);
//    }
//   });
//  }
//  $('#search_text').keyup(function(){
//   var search = $(this).val();
//   if(search != '')
//   {
//    load_data(search);
//   }
//   else
//   {
//    load_data();
//   }
//  });
// });


//azmy

function matcher(term, text, opt) {
    //var label = $(opt).val();//.attr('id');
    var mobile = String($(opt).data('mobile')); //data of option to search into it too
    var phone = String($(opt).data('phone')); //data of option to search into it too
    var code = String($(opt).data('clientcode')); //data of option to search into it too
    var id = String($(opt).data('id')); //data of option to search into it too

    term = term.toUpperCase(); //term to search
    text = text.toUpperCase(); //text of option

    if (text.indexOf(term) > -1
            || (mobile !== undefined && mobile.toUpperCase().indexOf(term) > -1)
            || (phone !== undefined && phone.toUpperCase().indexOf(term) > -1)
            || (code !== undefined && code.toUpperCase().indexOf(term) > -1)
            || (id !== undefined && id.toUpperCase().indexOf(term) > -1)) {
        return true;
    }

    return false;
}
$('.select2').select2({
    matcher: matcher
});