$(document).ready(function() {
    $('#searchbarcode').focus();
    var table = $('#productsdatatable').DataTable({
        "processing": true,
        "serverSide": true,
        "aLengthMenu": [
                [20, 50, 100],
                [20, 50, 100]
            ],
        "sPaginationType": "bootstrap",
        "sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
        "tableTools": {
            "aButtons": [
                "copy"
            ]
        },
        "ajax":{
            "url": base_url+"inventory/products/datatableGetproductDetails",
            "dataType": "json",
            "type": "POST",
            "data": function(d){
                d.searchbarcode = $('#searchbarcode').val();
                d.searchbyitemtype = $('#searchbyitemtype').val();
                d.searchbycategory = $('#searchbycategory').val();
//                d.account = $('#transaction_account').val();
//                d.type = $('#transaction_type').val();
//                d.search_btn = $('#search_btn').val();
            }
        },
        "oLanguage": {
            "sLengthMenu": "\_MENU_",
            "sSearch": "" 
        },

        "columns": [
                { "data": "sl",
                  "bSortable": true},
                { "data": "categoryname",
                  "bSortable": true},
                { "data": "REFERENCE",
                  "bSortable": true},
                { "data": "CODE" ,
                  "bSortable": true},
                { "data": "NAME" ,
                  "bSortable": true},
                { "data": "PRICEBUY",
                  "bSortable": true},
                { "data": "PRICESELL",
                  "bSortable": true},
                { "data": "taxcategory",
                  "bSortable": true},
              { "data": "TAXRATE",
                  "bSortable": true},
              { "data": "ID",
                  "bSortable": false}
//              { "data": "ISMAT",
//                  "bSortable": false,
//                  "bVisible": false,
//              }
            ]	 
        });


$('#searchbarcode').on( 'keyup', function (e) {
    if(e.which == 13) {
        table.draw();
        $('#searchbarcode').select();
    }
} );

$('#searchbyitemtype').on( 'change', function (e) {
    table.draw();
} );
$('#searchbycategory').on( 'change', function (e) {
    table.draw();
} );

    $('.toggle-vis').change(function(e){
        if($(this).val()!='') {
            $(".table-responsive").css("overflow-x","scroll"); 
            var tbl_width =  $("#productsdatatable").attr("style");
            var tbl_width = tbl_width.split(":");   
            if(table.column( $(this).val() ).visible()==false) {
               table.column( $(this).val() ).visible( true, true );           
              var wd = parseInt(tbl_width[1].slice(0,-3))+100;
              $("#productsdatatable").attr("style","width:"+wd+"px;");
            } else {
              table.column( $(this).val() ).visible( false, false );
               var wd = parseInt(tbl_width[1].slice(0,-3))-100;
              $("#productsdatatable").attr("style","width:"+wd+"px;");
            }
        }   
    });
    // productCategory();
    $(".general_tabs").click(function(){
        $(".general_tabs").removeClass("active");
        $(this).addClass("active");
        $(".general_tabs_div").hide();
        var currentId = $(this).attr("id");
        $("#"+currentId+"_div").show();
    });
    $('#incatalog').on('change', function(event){
        $("#order").val("");
        if($('#incatalog').prop("checked")==true) {
           $("#order").attr("disabled",false);
        } else {
           $("#order").attr("disabled",true);
        }
    });
    $('#breakdown').on('change', function(event) {
        $("#general_tabs4").toggle();
    });
    $("#pricebuy").change(function(){
        var sellPrice = $("#pricesell").val();
        var buyPrice = $("#pricebuy").val(); 
        profitCalculation(sellPrice,buyPrice);
    });
    $("#sellpricehd").keyup(function(){ 
      var sellPrice = $("#sellpricehd").val();
      $("#pricesell").val(sellPrice);
      var buyPrice = $("#pricebuy").val();   
      var taxCategory = $("#taxcat").val();
      profitCalculation(sellPrice,buyPrice);
      sellPricewithTaxCalculation(sellPrice,taxCategory);
   });





    $("#sellpricewithtax").change(function(){
      var sellpricewithtax = $("#sellpricewithtax").val(); 
      var sellPrice = $("#pricesell").val();     
       sellPriceFromsellpricewithtaxCalculation(sellpricewithtax,sellPrice)
    });

    $("#profit").change(function(){
       var buyPrice = $("#pricebuy").val();
       var profitPrice = $(this).val();
       sellPricefromProfitCalculation(buyPrice,profitPrice);
    });

    function profitCalculation(sellPrice,buyPrice) {
        var currencyDecimel = $("#currencyDecimel").val();
        if(sellPrice!='' && buyPrice!=''){
            var profit    = (parseFloat(sellPrice)/parseFloat(buyPrice)-1)*100;
            $("#profit").val(profit.toFixed(currencyDecimel));
        } else {
           $("#profit").val("");
        }
    }

   function sellPricewithTaxCalculation(sellPrice,taxCategory) {
     var currencyDecimel = $("#currencyDecimel").val();
     var sellPrice = $("#sellpricehd").val(); 
    if(sellPrice!='') {
      $.ajax({    //create an ajax request to load_page.php
            type: "POST",
            data:  {tax_id:taxCategory},
            dataType: "JSON",
            url: base_url+"settings/taxes/taxCalcultion",                   
            success: function(response){
                if(response!=false) {
                    var taxRate = response[0].MAXRATE;
                    var sellPricewithTax = (parseFloat(sellPrice)*taxRate)+parseFloat(sellPrice);
                } else {
                    var sellPricewithTax = sellPrice;
                }
                $("#sellpricewithtax").val(parseFloat(sellPricewithTax).toFixed(currencyDecimel));
            }
        });
     } else {
        $("#sellpricewithtax").val("");
     }
     
   }



    function sellPriceFromsellpricewithtaxCalculation(sellpricewithtax,sellPrice)
   {
    // alert(sellpricewithtax);
    var currencyDecimel = $("#currencyDecimel").val();
    if(sellpricewithtax!='')
    {

    var taxCategory = $("#taxcat").val();
      $.ajax({    //create an ajax request to load_page.php
            type: "POST",
            data:  {tax_id:taxCategory},
            dataType: "JSON",
            url: base_url+"settings/taxes/taxCalcultion",                   
            success: function(response){ 

                if(response!=false)
                {
                   var taxRate = response[0].MAXRATE;
                    var sellpriceValue = (parseFloat(sellpricewithtax)*100)/(100+(100*taxRate));
                }
                else
                {
                   var sellpriceValue = sellpricewithtax;
                }
                
                
                $("#sellpricehd").val(parseFloat(sellpriceValue).toFixed(currencyDecimel));
                $("#pricesell").val(sellpriceValue);
                profitCalculation($("#pricesell").val(),$("#pricebuy").val());
              }
            
        });
     }
     else
     {
      $("#pricesell,#profit").val("");
     }
    
   }

   $("#taxcat").change(function(){

      var sellPrice = $("#pricesell").val();
      var taxCategory = $("#taxcat").val();
      sellPricewithTaxCalculation(sellPrice,taxCategory);
   });


function sellPricefromProfitCalculation(buyPrice,profitPrice)
{
    var currencyDecimel = $("#currencyDecimel").val();
    $("#pricesell").val("");

    if(profitPrice!='' && !isNaN(profitPrice))
    {

      var sellpriceFromProfit =  ((parseFloat(profitPrice)/100)*parseFloat(buyPrice))+parseFloat(buyPrice); 
      
     $("#pricesell").val(sellpriceFromProfit);
     
     $("#sellpricehd").val(parseFloat(sellpriceFromProfit).toFixed(currencyDecimel));
     
     var taxCategory = $("#taxcat").val();
     sellPricewithTaxCalculation($("#pricesell").val(),taxCategory);
    }
    else
    {
       $("#pricesell").val("");
       $("#sellpricewithtax").val("");
    }
 
}

   $('#image').change(function(){

  $("#refresimage").css("display","block");
  $("#deleteimage").css("display","none");
    var uploadfile = $("#image").val();
    // alert(uploadfile);
    $("#imgfile").val(uploadfile);
// // check image size
//      var size = parseFloat($("#image")[0].files[0].size / 1024).toFixed(2);

        
//     var ext = uploadfile.split('.').pop();      
//     if(ext.toLowerCase()=='jpeg' || ext.toLowerCase()=='jpg' || ext.toLowerCase()=='png')
//     {
//       if(ext=='jpg'){ext = 'jpeg'; } else { ext = ext; }

       

//       var oFReader = new FileReader();
//       oFReader.readAsDataURL(this.files[0]);
//       console.log(this.files[0]);
//       oFReader.onload = function (oFREvent) {
//       var image = new Image();

//       image.src = oFREvent.target.result;
//         image.onload = function () {
//         var height = this.height;
//         var width = this.width;    
              
//          if(width>=120 && height>=120)
//           {
//             if(size>15)
//             {
//               $(".spanerrorimg").css("display","block");
//               $("#spanerrorimg").attr("title","choose valid image size!");
//               $('#image').css("border","1px solid #dd4b39");
//               $("#image").val('');
//               $("#preview_img").attr("src","../assets/images/img.png");
//               $("#imgfile").val(''); 
//             }
//             else
//             {
              
//               var imgfile = oFREvent.target.result.replace("data:image/"+ext+";base64,", "");   
               
//                 $("#imgfile").val(imgfile);
//                 $("#preview_img").show();              
//                 $("#preview_img").attr("src", oFREvent.target.result);                
//                 $('#image').css("border","1px solid #ccc");
//                 $(".spanerrorimg,.pdt_img").css("display","none");
//             }
            
//            }
//            else
//            {
//             $(".spanerrorimg").css("display","block");
//             $("#spanerrorimg").attr("title","choose valid image diamenssion!");
//             $('#image').css("border","1px solid #dd4b39");
//             $("#image").val('');
            
//             $("#imgfile").val('');
//            }
//          };
        
        
//       };
//     }
//     else
//     {
//       $(".spanerrorimg").css("display","block");
//       $("#spanerrorimg").attr("title","Choose valid image type!");
//       $('#image').css("border","1px solid #dd4b39");
//       $("#image").val('');
//       $("#preview").attr("src","../assets/images/img.png");
//       $("#imgfile").val('');
      
//     }

  });

// $('#myModal').modal({
//     backdrop: 'static',
//     keyboard: false
// })

    $("#reference_id").click(function(){
        // alert("d");
        $.ajax({    //create an ajax request to load_page.php
            type: "POST",            
            dataType: "JSON",
            url: base_url+"inventory/products/getConfiguration",                   
            success: function(response){ 
                if (typeof purchaseflag !== 'undefined' && purchaseflag!='') {
                    $(".prreference").val(response[0].NEXTBARCODE);
                    $("#code").val(response[0].NEXTBARCODE);
                }else{
                    $("#reference").val(response[0].NEXTBARCODE);
                    $("#code").val(response[0].NEXTBARCODE);
                }
            }
        });
    });

    $("#add_btn").click(function() {
        $(".general_tabs_div,#general_tabs4").hide();
        $("#general_tabs1_div,.pdt_img,#save_new").show();
        $(".general_tabs").removeClass("active");
        $("#general_tabs1").addClass("active");
        $('#form1')[0].reset();
        $("#preview_img").hide();  
        $("#order").attr("disabled",true);
        $("#tr_brk_dwn").html("");
        $("#form1")[0].reset();
        $("#id").val('');
        $('#incatalog').prop('checked', true);
        $(".form-control").css("border","1px solid #ccc");
        $(".display_error").css("display","none");
    });

    $('.save_btns').click(function() {
        buttonpressed = $(this).attr('name')
    })
    $("#form1").submit(function(event){
      event.preventDefault();
       // var val = $("input[type=submit][clicked=true]").val();
      // alert($(this).attr("button"));
      
      
        var inputnames = new Array("reference","code","name","sellpricehd","taxcat","category");
        var result = emptyform_validation(inputnames) ;
        if(result==true) {
            var formData = new FormData(this);
            $.ajax({
                //create an ajax request to load_page.php
                type: "POST",
                //data:$("#form1").serialize(),
                data:formData,
                processData: false,
                contentType: false,
                url: base_url+"inventory/products/addproducts",                   
                success: function(response){
                    var response = response.replace(/\s/g, '');
                    if(response=='false') {
                        $(".display_error").css("display","block");
                        $(".display_error").html("Combination of refrence,barcode or name is already exist!");
                        $(".general_tabs_div").hide();
                        $("#general_tabs1_div").show();
                        $(".general_tabs").removeClass("active");
                        $("#general_tabs1").addClass("active");
                    } else if(response=='brkfalse') {
                        $(".display_error").css("display","block");
                        $(".display_error").html("Your Selected combination is already exist! Please choose another one");
                        $(".general_tabs_div").hide();
                        $("#general_tabs4_div").show();
                        $(".general_tabs").removeClass("active");
                        $("#general_tabs4").addClass("active");
                    } else {
                        if(buttonpressed=='save_new') {
                          $('#form1')[0].reset(); 
                          $('#form1')[0].reset(); 
                          $(".success_msg").css("display","block");
                          $(".success_msg").html("The record is added successfuly");
                          var table = $('#productsdatatable').DataTable();
                          table.ajax.reload(i=0);
                          $( "#tr_brk_dwn" ).html('');
                          $("#general_tabs4").hide();
                          $("#reference").focus();
                        } else {
                            if (typeof purchaseflag !== 'undefined' && purchaseflag!='') {
                                var obj = JSON.parse(response);
                                var txtindex = $('.editfield').attr("data-ind");
                                $("#itemid_" + txtindex).val(obj.ID);
                                selectItemgrid(obj.ID, obj.CODE, obj.NAME, obj.PRICEBUY,obj.TAXCAT);
                                setTimeout(function() {
                                    location.reload();//reload page
                                }, 500);
                            }else{
                                $('#myModal').modal('hide');
                                window.location.href = base_url+'inventory/products';
                                $(".display_error").css("display","none");
                            }
                        }
                    }
                }
            });
        }
        
        
        
    });
    $("#pdt_columns").change(function(){
        var column_id = $(this).val();
        $("#"+column_id).toggle();
        $("#productsdatatable td:nth-child("+column_id+")").toggle();
    });


$("#excel_export").click(function(){

  // window.location.href = base_url+'inventory/products/excelExportData';

});


$("#pdf_export").click(function(){
    var value1 = $('.dataTables_filter input').val();
    var value = value1.replace(/ /g, "_");
    window.location.href = base_url+'inventory/products/exportPDFData/'+value;

});


} );




function productCategory(count)
{
    $.ajax({    //create an ajax request to load_page.php
            type: "POST",            
            // dataType: "JSON",
            url: base_url+"inventory/products/getProductCategories",                   
            success: function(response){ 
                $("#brk_category"+count).html(response);
               
              }
            
        });
}



function productMaterials(count)
{
    $.ajax({    //create an ajax request to load_page.php
            type: "POST",            
            // dataType: "JSON",
            url: base_url+"inventory/products/getProductMaterials",                   
            success: function(response){ 
                $("#brk_material"+count).html(response);
               
              }
            
        });
}

        function add_brk_dwn(){
            var count   = parseInt($('#hdcounter').val()) + parseInt('1');
            var con = '';
            con += '<tr id="brk_dwn'+count+'" class="brk_dwnlistdiv">';        
            con += '<td>';
            con += '<input name="brk_barcode[]" class="form-control ui-autocomplete-input autoc" id="brk_barcode'+count+'" data-metid="'+count+'"  placeholder="Barcode">';
            con += '</td>';
            con += '<td>';
            con += '<select name="brk_category[]" id="brk_category'+count+'" class="form-control" onchange="getMaterials(this.value,'+count+')"><option value="">--- Select ---</option></select>';
            con += '</td>';
            con += '<td>';
            con += '<select name="brk_material[]" required id="brk_material'+count+'" class="form-control"><option value="">--- Select ---</option></select>';
            con += '</td>';
            con += '<td>';
            con += '<input type="text" class="form-control" id="brk_units'+count+'" placeholder="Units" value="1" name="brk_units[]" >';
            con += '</td>';
            con += '<td style="width:10px;"><button onclick="removebrk_dwn('+count+')" id="bomdelete" class="brk_close_btn"><i class="fa fa-minus-circle" aria-hidden="true"></i></button><input type="hidden" name="brk_pdt[]" value="" id="brk_pdt"></td>';
            con += '</tr>';
            $( "#tr_brk_dwn" ).append(con);
            $('#hdcounter').val(count);
            productCategory(count);
            productMaterials(count);
        }

        function removebrk_dwn(id) {
            if($("#brk_pdt").val()!='') {
                var pdt_id = $("#brk_pdt").val();
                $.ajax({    //create an ajax request to load_page.php
                    type: "POST",      
                    data:{delete_brk:id,pdt_id:pdt_id},
                    // dataType: "JSON",
                    url: base_url+"inventory/products/deleteBreakdownData",                   
                    success: function(response){ 
                        alert("successfuly removed!");

                      }

                });
            }
            $("#brk_dwn"+id).closest('tr').remove();
        }


function getMaterials(category,count)
{
  $.ajax({    //create an ajax request to load_page.php
            type: "POST",      
            data:{cate_id:category},
            // dataType: "JSON",
            url: base_url+"inventory/products/getProductMaterials",                   
            success: function(response){ 
                $("#brk_material"+count).html(response);
               
              }
            
        });
}

function myFunction(id) {
    $(".loading-container").removeClass("loading-inactive");
    if (typeof purchaseflag !== 'undefined' && purchaseflag!='') {
        $("#productlistselect").hide();
        $("#createproductform").show();
        $("#buttoncreateproduct").hide();
        $("#buttonlistproduct").show();
        $("#searchbarcodepi").hide();
//        console.log("sssss");
    }
  var currencyDecimel = $("#currencyDecimel").val();
  $(".success_msg").hide();
  var id = id;
  
              $("#save_new").hide();
              $(".general_tabs_div").hide();
              $("#general_tabs1_div").show();
              $(".general_tabs").removeClass("active");
              $("#general_tabs1").addClass("active");
              // $("#general_tabs4").hide();

 breakdown_data(id);
  $.ajax({    //create an ajax request to load_page.php
        type: "POST",
        data: {pid:id},
        url: base_url+"inventory/products/getproductdetailsWithID",   
        dataType: "JSON",             
        success: function(response){
//            console.log(JSON.stringify(response));
            if (typeof purchaseflag !== 'undefined' && purchaseflag!='') {
                $(".prreference").val(response[0].REFERENCE);
                //$("#code").val(response[0].NEXTBARCODE);
            }else{
                $("#reference").val(response[0].REFERENCE);
                //$("#code").val(response[0].NEXTBARCODE);
            }
               //$("#reference").val(response[0].REFERENCE);
               
               $("#id").val(response[0].ID); 
               $("#code").val(response[0].CODE);
               $("#name").val(response[0].NAME);              
               $("#pricebuy").val(response[0].PRICEBUY);
               
               $("#pricesell").val(response[0].HDPRICESELL);
               $("#sellpricehd").val(response[0].PRICESELL);
               
               $("#taxcat").val(response[0].TAXCAT);
               $("#category").val(response[0].CATEGORY);
               $("#attributeset_id").val(response[0].ATTRIBUTESET_ID);
               $("#stock_cost_by_year").val(response[0].STOCKCOST);
               $("#stock_volume").val(response[0].STOCKVOLUME);
               $("#order").val(response[0].CATORDER);
               
               $(".propoties_textarea").val(response[0].ATTRIBUTES);
               if(response[0].INCAT==1)
               {
                  $("#incatalog").prop("checked",true);
                  $("#order").attr("disabled",false);
               }
               else
               {
                 $("#incatalog").prop("checked",false);
                 $("#order").attr("disabled",true);
               }

               if(response[0].ISCOM==1)
                $("#auxilary").prop("checked",true);
               else
                 $("#auxilary").prop("checked",false);
             
             
                if(response[0].ITEMTYPE==1)
                    $("#ITEMTYPE").prop("checked",true);
                else
                    $("#ITEMTYPE").prop("checked",false);

               if(response[0].ISSCALE==1)
                $("#scale").prop("checked",true);
               else
                 $("#scale").prop("checked",false);
               
               
               
               // profit calculation


                  if(response[0].PRICESELL!='' && response[0].PRICEBUY!='')
                  {
                    var profit    = (parseFloat(response[0].PRICESELL)/parseFloat(response[0].PRICEBUY)-1)*100;
                    $("#profit").val(profit.toFixed(currencyDecimel));
                  }
                  else
                  {
                     $("#profit").val("");
                  }

                  // taxcalculation

                  if(response[0].PRICESELL!='')
                    {

                    
                      $.ajax({    //create an ajax request to load_page.php
                            type: "POST",
                            data:  {tax_id:response[0].TAXCAT},
                            dataType: "JSON",
                            url: base_url+"settings/taxes/taxCalcultion",                   
                            success: function(response1){
                                
                                if(response1!=false)
                                {
                                   var taxRate = response1[0].MAXRATE;
                                    var sellPricewithTax = (parseFloat(response[0].HDPRICESELL)*taxRate)+parseFloat(response[0].HDPRICESELL);
                                }
                                else
                                {
                                   var sellPricewithTax = response[0].PRICESELL;
                                }
                               
                                $("#sellpricewithtax").val(parseFloat(sellPricewithTax).toFixed(currencyDecimel));
                              }
                            
                        });
                     }
                     else
                     {
                        $("#sellpricewithtax").val("");
                     }
                 
                 $.ajax({    //create an ajax request to load_page.php
                    type: "POST",
                    data: {},
                    url: base_url+"inventory/products/getproductimage/"+id,            
                    success: function(response){ 
                        $("#productimageview").attr("src","data:image/png;base64,"+response);
                    }});
        }

    });
$(".loading-container").addClass("loading-inactive");
 
}

  function breakdown_data(id)
  {
      $('#breakdown').prop('checked', false);
    // $("#general_tabs4").show();
    $(".brk_dwnlistdiv").remove();

     $.ajax({    //create an ajax request to load_page.php
        type: "POST",
        data: {pid:id},
        url: base_url+"inventory/products/getBreakdownDetails",   
        dataType: "JSON",             
        success: function(response)
        {
            $( "#tr_brk_dwn" ).html('');
          // alert(response);
          if(response==false)
          {
            $("#general_tabs4").hide();
          }
          else
          {
            $("#general_tabs4").show(); 
          }
          for(var i=0;i<response.length;i++)
          {
                var txtproductid = response[i]['MATERIAL'];
                var txtproductbuyprice = response[i]['MATERIAL_PRICEBUY'];
                var txtqty = response[i]['AMOUNT'];
                var txtitemname = response[i]['MATERIAL_NAME'];
                var txtbarcode = response[i]['BARCODE'];
                var con = '<tr><td><input type="hidden" class="" name="brk_material[]" value="'+txtproductid+'" />\n\
                    <input type="hidden" class="brk_price" value="'+(txtproductbuyprice*txtqty)+'" />\n\
                    <input type="hidden" class="brk_units" name="brk_units[]" value="'+txtqty+'" />\n\
                    '+txtbarcode+'</td><td>'+txtitemname+'</td><td>'+txtqty+'</td>';
                if (typeof purchaseflag === 'undefined' || purchaseflag=='') {
                    con = con+'<td><button onclick="removerow(this);" type="button" \n\
                     class="btn btn-danger btn-xs shiny"><i class="fa fa-trash" aria-hidden="true"></i></button></td>';
                }
                con = con+'</tr>';
                $( "#tr_brk_dwn" ).append(con);
                $('#breakdown').prop('checked', true);
          }
         }

  });
}


function printFunction(divId) {
  document.location.href = base_url+"inventory/products/printlabel/" + divId;

}


 function confirmFunction(id) {
    $("#okid").val(id);
    $(".display_error").hide();
}

  function deleteFunction() {
     id = $("#okid").val();

    $.ajax({
        url: base_url + 'inventory/products/deleteproducts/'+ id,
        success:function(data){
//            alert(data);
          if(data!='true')
          {
            $(".display_error").show();
          }
          else
          {
           $("#confirmmodal").hide();
           $("#modal-success").show();
           location.reload(true);
          }
         

        }
    });
}

$(document).on('keydown', '#txtbarcode', function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (e.type == 'keydown') {
        if (code == 13) {
            e.preventDefault();
            $.ajax({
                method: "GET",
                url: base_url+"inventory/Products/getproductsfromcode/",
                data: {term: $(this).val()},
                dataType: "json"
            }).done(function (msg) {
                $.each(msg, function (index, element) {
                    $('#txtproductid').val(element.ID);
                    $('#txtitemname').html(element.NAME);
                    $('#txtproductbuyprice').val(element.PRICEBUY);
                    $('#txtqty').focus();
                });
            });
        }
    }
    
});