
//On Enter Move the cursor to desigtation Id
function shift_cursor(kevent,target){

    if(kevent.keyCode==13){
		$("#"+target).focus();
    }
	
}


$('#save,#update').on("click",function (e) {
	var base_url=$("#base_url").val();

    //Initially flag set true
    var flag=true;

    function check_field(id)
    {

      if(!$("#"+id).val() ) //Also check Others????
        {

            $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
           // $('#'+id).css({'background-color' : '#E8E2E9'});
            flag=false;
        }
        else
        {
             $('#'+id+'_msg').fadeOut(200).hide();
             //$('#'+id).css({'background-color' : '#FFFFFF'});    //White color
        }
    }


   //Validate Input box or selection box should not be blank or empty
	  
    check_field("adjustment_date");

    //check_field("warehouse_id");
	/*if(!isNaN($("#amount").val()) && parseInt($("#amount").val())==0){
        toastr["error"]("You have entered Payment Amount! <br>Please Select Payment Type!");
        return;
    }*/
	if(flag==false)
	{
		toastr["error"]("You have missed Something to Fillup!");
		return;
	}

	//Atleast one record must be added in stock_adjustment table 
    var rowcount=document.getElementById("hidden_rowcount").value;
	var flag1=false;
	var batch_validation_error = false;
	var batch_error_message = '';
	var missing_batch_items = [];
	
	for(var n=1;n<=rowcount;n++){
		var qty_input = $("#td_data_"+n+"_3");
		if(qty_input.length > 0 && qty_input.val() != null && qty_input.val() !== ''){
			flag1=true;
			
			// Check batch validation for positive adjustments (adding stock)
			var adjustment_qty = parseFloat(qty_input.val()) || 0;
			var item_id_input = $("#tr_item_id_"+n);
			
			if(item_id_input.length === 0){
				console.warn('Row '+n+': tr_item_id_'+n+' not found!');
				continue;
			}
			
			var item_id = item_id_input.val();
			if(!item_id || item_id === ''){
				continue;
			}
			
			// Try both .data() and .attr() to ensure we get the value
			var batch_tracking_enabled_data = item_id_input.data('batch-tracking-enabled');
			var batch_tracking_enabled_attr = item_id_input.attr('data-batch-tracking-enabled');
			var batch_tracking_enabled = batch_tracking_enabled_attr || batch_tracking_enabled_data;
			var batch_number_input = $("#batch_number_"+n);
			var batch_number = (batch_number_input.length > 0) ? (batch_number_input.val() || '') : '';
			
			// DEBUG: Log batch tracking status
			console.log('=== VALIDATION CHECK Row '+n+' ===');
			console.log('Item ID:', item_id);
			console.log('Batch Enabled (.attr):', batch_tracking_enabled_attr);
			console.log('Batch Enabled (.data):', batch_tracking_enabled_data);
			console.log('Using value:', batch_tracking_enabled);
			console.log('Adjustment Qty:', adjustment_qty);
			console.log('Batch Number field exists:', batch_number_input.length > 0);
			console.log('Batch Number value:', batch_number);
			
			// ALTERNATIVE: Check batch icon presence - if batch icon exists, item has batch tracking
			var batch_icon = $("#row_"+n).find('.fa-cubes');
			var has_batch_icon = batch_icon.length > 0;
			console.log('Batch icon present:', has_batch_icon);
			
			// Convert batch_tracking_enabled to number for proper comparison
			// Handle: undefined, null, '0', 0, '', '1', 1
			var is_batch_tracked = false;
			if(batch_tracking_enabled !== undefined && batch_tracking_enabled !== null && batch_tracking_enabled !== ''){
				var batch_val = parseInt(batch_tracking_enabled) || 0;
				is_batch_tracked = (batch_val === 1);
				console.log('Row '+n+': Parsed batch_tracking_enabled='+batch_val+', is_batch_tracked='+is_batch_tracked);
			} else {
				// If data attribute is missing, check by batch icon presence as fallback
				if(has_batch_icon){
					console.log('Row '+n+': data attribute missing BUT batch icon exists - treating as batch tracked');
					is_batch_tracked = true;
				} else {
					console.log('Row '+n+': batch_tracking_enabled is empty/undefined/null and no icon - treating as NOT batch tracked');
				}
			}
			
			// IMPORTANT: Only validate batch details for items WITH batch tracking enabled
			// Items WITHOUT batch tracking are NOT affected by this validation
			if(adjustment_qty > 0 && is_batch_tracked === true){
				console.log('Row '+n+': Item has batch tracking AND positive adjustment - VALIDATING batch details');
				// This item has batch tracking enabled - batch details are REQUIRED
				if(!batch_number || batch_number.trim() === ''){
					console.log('Row '+n+': VALIDATION FAILED - Batch number is missing!');
					var item_name_element = $("#td_data_"+n+"_1");
					var item_name = item_name_element.find('a').text().trim() || item_name_element.text().trim();
					// Remove batch display from item name for clean display
					item_name = item_name.replace(/<br><small[^>]*>.*?<\/small>/gi, '').trim();
					
					batch_error_message += '• ' + item_name + ' (Row ' + n + ')\n';
					missing_batch_items.push({
						row: n,
						name: item_name,
						item_id: item_id
					});
					batch_validation_error = true;
				} else {
					console.log('Row '+n+': VALIDATION PASSED - Batch number is present: '+batch_number);
				}
			} else {
				if(adjustment_qty <= 0){
					console.log('Row '+n+': Skipping validation - adjustment quantity is not positive ('+adjustment_qty+')');
				} else if(!is_batch_tracked){
					console.log('Row '+n+': Skipping validation - item does not have batch tracking enabled');
				}
			}
			console.log('=== END VALIDATION Row '+n+' ===');
			// Items without batch tracking (is_batch_tracked === false) are skipped - no validation needed
		}	
	}
	
    // CRITICAL: Validate batch details FIRST before checking if items are selected
    // This ensures batch errors are shown before generic "no items" error
    console.log('=== BATCH VALIDATION SUMMARY ===');
    console.log('batch_validation_error:', batch_validation_error);
    console.log('missing_batch_items count:', missing_batch_items.length);
    console.log('batch_error_message:', batch_error_message);
    console.log('================================');
    
    if(batch_validation_error){
    	console.log('🚫 SAVE BLOCKED - Missing batch details detected!');
    	// PREVENT FORM SUBMISSION IMMEDIATELY
    	e.preventDefault();
    	e.stopPropagation();
    	e.stopImmediatePropagation();
    	
    	var full_message = "Batch details required for:\n" + batch_error_message;
    	full_message += "\nClick 📦 icon next to each item to add batch details.";
    	
    	toastr["error"](full_message, "Batch Details Missing", {
    		timeOut: 8000,
    		extendedTimeOut: 3000
    	});
    	
    	// Highlight the rows that need batch details
    	missing_batch_items.forEach(function(item){
    		$("#row_"+item.row).css('background-color', '#ffeeee').animate({'background-color': '#ffffff'}, 2000);
    	});
    	
    	// Focus on first missing batch item - highlight the batch icon
    	if(missing_batch_items.length > 0){
    		var first_missing = missing_batch_items[0];
    		var batch_icon = $("#row_"+first_missing.row).find('.fa-cubes');
    		if(batch_icon.length > 0){
    			// Flash the icon to draw attention
    			batch_icon.css('color', '#ff0000');
    			setTimeout(function(){
    				batch_icon.css('color', '#5bc0de');
    				setTimeout(function(){
    					batch_icon.css('color', '#ff0000');
    					setTimeout(function(){
    						batch_icon.css('color', '#5bc0de');
    					}, 300);
    				}, 300);
    			}, 300);
    		}
    	}
    	
    	console.log('BATCH VALIDATION FAILED: Save blocked due to missing batch details');
    	return false; // BLOCK SAVE - This will prevent "Please Select Item" message
    }
    //end
    
    if(flag1==false){
    	toastr["warning"]("Please Select Item!!");
        $("#item_search").focus();
		return false;
    }
    
    // If we reached here, batch validation passed (or no batch items)
    if(batch_validation_error === false){
    	console.log('✅ BATCH VALIDATION PASSED - Proceeding with save');
    } else {
    	// Double-check - if somehow we got here with validation error, block again
    	console.error('ERROR: batch_validation_error is true but we reached save code - blocking save!');
    	e.preventDefault();
    	e.stopPropagation();
    	e.stopImmediatePropagation();
    	return false;
    }

    
    var this_id=this.id;
    
			//if(confirm("Do You Wants to Save Record ?")){
				e.preventDefault();
				data = new FormData($('#stock_adjustment-form')[0]);//form name
        /*Check XSS Code*/
        if(!xss_validation(data)){ return false; }
        
        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
        $("#"+this_id).attr('disabled',true);  //Enable Save or Update button
				$.ajax({
				type: 'POST',
				url: base_url+'stock_adjustment/stock_adjustment_save_and_update?command='+this_id+'&rowcount='+rowcount,
				data: data,
				cache: false,
				contentType: false,
				processData: false,
				success: function(result){
         // alert(result);return;
				result=result.split("<<<###>>>");
					if(result[0]=="success")
					{
						location.href=base_url+"stock_adjustment/details/"+result[1];
					}
					else if(result[0]=="failed")
					{
					   toastr['error']("Sorry! Failed to save Record.Try again");
					}
					else if(result[0] && result[0].indexOf("error:") === 0)
					{
						// Server-side validation error (batch details required)
						var error_msg = result[0].replace("error:", "");
						toastr['error'](error_msg, "Batch Details Required", {
							timeOut: 10000,
							extendedTimeOut: 5000
						});
					}
					else
					{
						alert(result);
					}
					$("#"+this_id).attr('disabled',false);  //Enable Save or Update button
					$(".overlay").remove();

			   }
			   });
		//}
  
});

$("#item_search").bind("paste", function(e){
    $("#item_search").autocomplete('search');
} );

$("#item_search").autocomplete({
    source: function(data, cb){
        $.ajax({
          autoFocus:true,
            url: $("#base_url").val()+'items/get_json_items_details',
            method: 'GET',
            dataType: 'json',
            /*showHintOnFocus: true,
      autoSelect: true, 
      
      selectInitial :true,*/
      
            data: {
                name: data.term,
                store_id:$("#store_id").val(),
                warehouse_id:$("#warehouse_id").val(),
                search_for:"purchase",
            },
            beforeSend: function() {
                if($("#warehouse_id").val()==''){
                  toastr['warning']("Please Select Wareshouse!");
                  $("#warehouse_id").select2('open');
                  $("#item_search").removeClass('ui-autocomplete-loading');
                  return;
                }
                $("#item_search").addClass('ui-autocomplete-loading');
            },
            success: function(res){
              //console.log(res);
                var result;
                result = [
                    {
                        //label: 'No Records Found '+data.term,
                        label: 'No Records Found ',
                        value: ''
                    }
                ];

                if (res.length) {
                    result = $.map(res, function(el){
                        return {
                            //label: el.item_code +'--'+ el.label + ' (Stock: '+ el.stock + ')',
                            label: el.item_code +'--'+ el.label,
                            value: '',
                            id: el.id,
                            item_name: el.value,
                           // mobile: el.mobile,
                            //customer_dob: el.customer_dob,
                            //address: el.address,
                        };
                    });
                }

                cb(result);
            }
        });
    },

        response:function(e,ui){
          if(ui.content.length==1){
            $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
            $(this).autocomplete("close");
          }
          //console.log(ui.content[0].id);
        },

        //loader start
        search: function (e, ui) {
        },
        select: function (e, ui) { 
          
            //$("#mobile").val(ui.item.mobile)
            //$("#item_search").val(ui.item.value);
            //$("#customer_dob").val(ui.item.customer_dob)
            //$("#address").val(ui.item.address)
            //alert("id="+ui.item.id);
            if(typeof ui.content!='undefined'){
              console.log("Autoselected first");
              if(isNaN(ui.content[0].id)){
                return;
              }
              //var stock=ui.content[0].stock;
              var item_id=ui.content[0].id;
            }
            else{
              console.log("manual Selected");
              //var stock=ui.item.stock;
              var item_id=ui.item.id;
            }

            return_row_with_data(item_id);
            $("#item_search").val('');
        },   
        //loader end
});

function check_same_item(item_id){

  if($("#adjustment_table tr").length>1){
    var rowcount=$("#hidden_rowcount").val();
    for(i=0;i<=rowcount;i++){
            if($("#tr_item_id_"+i).val()==item_id){
              increment_qty(i);
              failed.currentTime = 0;
              failed.play();
              return false;
            }
      }//end for
  }
  return true;
}

function return_row_with_data(item_id){
  //CHECK SAME ITEM ALREADY EXIST IN ITEMS TABLE 
  var item_check=check_same_item(item_id);
  if(!item_check){return false;}
  //END
  
  $("#item_search").addClass('ui-autocomplete-loader-center');
	var base_url=$("#base_url").val();
	var rowcount=$("#hidden_rowcount").val();
$.post(base_url+"stock_adjustment/return_row_with_data/"+rowcount+"/"+item_id,
    { warehouse_id: $("#warehouse_id").val() },
    function(result){
        //alert(result);
        $('#adjustment_table tbody').append(result);
       	$("#hidden_rowcount").val(parseInt(rowcount)+1);
        success.currentTime = 0;
        success.play();
        final_total();
        $("#item_search").removeClass('ui-autocomplete-loader-center');
        $("#item_search").removeClass('ui-autocomplete-loading');
    }); 
}
//INCREMENT ITEM
function increment_qty(rowcount){
  var item_qty=$("#td_data_"+rowcount+"_3").val();
    item_qty=parseFloat(item_qty)+1;
    $("#td_data_"+rowcount+"_3").val(format_qty(item_qty));
  final_total();
}
//DECREMENT ITEM
function decrement_qty(rowcount){
  var item_qty=$("#td_data_"+rowcount+"_3").val();
  /*if(item_qty<=1){
    $("#td_data_"+rowcount+"_3").val(1);
    return;
  }*/
  $("#td_data_"+rowcount+"_3").val((format_qty(item_qty)-1));
  final_total();
}





  //Delete Record start
function delete_stock_adjustment(q_id)
{
    var base_url=$("#base_url").val();
   if(confirm("Do You Wants to Delete Record ?")){
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $.post(base_url+"stock_adjustment/delete_stock_adjustment",{q_id:q_id},function(result){
   //alert(result);return;
     result = result.trim(); // Trim whitespace
     if(result=="success")
        {
          toastr["success"]("Record Deleted Successfully!");
          // Reload table after short delay to ensure clean state
          setTimeout(function(){
              $('#example2').DataTable().ajax.reload(null, false); // false = don't reset pagination
          }, 500);
        }
        else if(result=="failed" || result.indexOf("failed:") === 0){
          toastr["error"]("Failed to Delete. Try again!");
        }
        else{
           // Show error message (may contain line breaks)
           var errorMsg = result.replace(/\\n/g, '\n'); // Convert \n to actual newlines
           toastr["error"](errorMsg, "Deletion Error", {
               timeOut: 10000,
               extendedTimeOut: 5000
           });
        }
        $(".overlay").remove();
        return false;
   }).fail(function(xhr, status, error) {
        // Handle AJAX errors to prevent DataTables JSON parsing errors
        console.error("Delete failed:", status, error);
        toastr["error"]("An error occurred while deleting. Please try again.");
        $(".overlay").remove();
   });
   }//end confirmation
}
//Delete Record end
function multi_delete(){
  //var base_url=$("#base_url").val();
    var this_id=this.id;
    var base_url=$("#base_url").val();
    if(confirm("Are you sure ?")){
      data = new FormData($('#table_form')[0]);//form name
      /*Check XSS Code*/
      if(!xss_validation(data)){ return false; }
      
      $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
      $("#"+this_id).attr('disabled',true);  //Enable Save or Update button
      $.ajax({
      type: 'POST',
      url: base_url+'stock_adjustment/multi_delete',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result){
        result=result;
  //alert(result);return;
        if(result=="success")
        {
          toastr["success"]("Record Deleted Successfully!");
          success.currentTime = 0; 
            success.play();
          $('#example2').DataTable().ajax.reload();
          $(".delete_btn").hide();
          $(".group_check").prop("checked",false).iCheck('update');
        }
        else if(result=="failed")
        {
           toastr["error"]("Sorry! Failed to save Record.Try again!");
           failed.currentTime = 0; 
           failed.play();
        }
        else
        {
          toastr["error"](result);
          failed.currentTime = 0; 
            failed.play();
        }
        $("#"+this_id).attr('disabled',false);  //Enable Save or Update button
        $(".overlay").remove();
       }
       });
  }
  //e.preventDefault
}
$('#item_search').keypress(function (e) {
 var key = e.which;
 // the enter key code
 if(key == 13){
    $("#item_search").autocomplete('search');
  }
});  