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

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


// Track last checked supplier to prevent duplicate messages
var last_checked_supplier_id = null;
var supplier_currency_check_timeout = null;

// Check if supplier has different currency than base currency for Purchase
function check_supplier_currency_for_purchase() {
  var supplier_id = $("#supplier_id").val();
  var base_url = $("#base_url").val();
  
  console.log('Checking currency for supplier ID:', supplier_id);
  
  // Skip if same supplier was already checked
  if (supplier_id === last_checked_supplier_id) {
    console.log('Same supplier already checked, skipping...');
    return;
  }
  
  // Clear any existing timeout
  if (supplier_currency_check_timeout) {
    clearTimeout(supplier_currency_check_timeout);
  }
  
  // Add small delay to prevent rapid-fire checks
  supplier_currency_check_timeout = setTimeout(function() {
    // Update last checked supplier
    last_checked_supplier_id = supplier_id;
    
    // Hide currency info initially
    $("#supplier_currency_info").hide();
    
    if (supplier_id && supplier_id !== '' && supplier_id !== '1') {
      console.log('Making AJAX call to check supplier currency...');
      
      // Make AJAX call to check supplier currency
      $.ajax({
        url: base_url + 'suppliers/get_supplier_currency',
        type: 'POST',
        data: { supplier_id: supplier_id },
        dataType: 'json',
        success: function(currency_response) {
          console.log('Currency response:', currency_response);
          
          if (currency_response.status) {
            // Show supplier currency info
            var supplier_currency_text = '';
            if (currency_response.supplier_currency_name && currency_response.supplier_currency_code) {
              supplier_currency_text = currency_response.supplier_currency_name + ' (' + currency_response.supplier_currency_code + ')';
            } else {
              supplier_currency_text = currency_response.currency_name + ' (' + currency_response.currency_code + ')';
            }
            
            $("#supplier_currency_name").text(supplier_currency_text);
            $("#supplier_currency_info").show();
            
            // Update currency symbols in table headers
            // Get the currency symbol to use
            var currency_symbol = currency_response.supplier_currency_symbol || currency_response.currency_symbol || '$';
            
            // Update header currency symbols
            $("#purchase_price_currency_symbol").text(currency_symbol);
            $("#discount_currency_symbol").text(currency_symbol);
            
            // Update totals currency symbols
            $("#subtotal_currency_symbol").text(currency_symbol);
            $("#other_charges_currency_symbol").text(currency_symbol);
            $("#discount_to_all_currency_symbol").text(currency_symbol);
            $("#round_off_currency_symbol").text(currency_symbol);
            $("#total_amt_currency_symbol").text(currency_symbol);
            
            console.log('Supplier currency ID:', currency_response.supplier_currency_id);
            console.log('Base currency ID:', currency_response.base_currency_id);
            
            // Check if supplier currency is different from base currency
            if (currency_response.supplier_currency_id && 
                currency_response.supplier_currency_id != currency_response.base_currency_id) {
              
              console.log('Currency mismatch detected!');
              
              // Show concise error message
              var supplier_currency_text = currency_response.supplier_currency_name + ' (' + currency_response.supplier_currency_code + ')';
              var base_currency_text = currency_response.base_currency_name + ' (' + currency_response.base_currency_code + ')';
              
              toastr["error"](
                "Multi-Currency Not Allowed in Purchase!<br>" +
                "Supplier: " + supplier_currency_text + "<br>" +
                "System: " + base_currency_text + "<br>" +
                "Use Direct Purchase Invoice for multi-currency.",
                "Currency Mismatch",
                {
                  "timeOut": "5000",
                  "extendedTimeOut": "1000",
                  "closeButton": true,
                  "progressBar": false
                }
              );
              
              // Play error sound
              if (typeof failed !== 'undefined') {
                failed.currentTime = 0;
                failed.play();
              }
              
              // Reload page after a short delay to ensure proper walk-in supplier loading
              setTimeout(function() {
                console.log('Reloading page to load default supplier...');
                
                // Show loading message before reload
                toastr["info"]("Reloading Purchase to load default supplier...", "Please Wait", {
                  "timeOut": "1000",
                  "extendedTimeOut": "500",
                  "closeButton": false,
                  "progressBar": false
                });
                
                // Reload page after brief delay
                setTimeout(function() {
                  window.location.reload();
                }, 1000);
              }, 2000); // 2 second delay to let user see the toast message
            } else {
              console.log('Currency match - Purchase allowed');
              // Supplier has same currency as base - no need to show success message every time
              // Just show currency info, no toast message
            }
          } else {
            console.log('Currency response status is false');
          }
        },
        error: function(xhr, status, error) {
          console.log('AJAX Error:', xhr.responseText);
          console.log('Status:', status);
          console.log('Error:', error);
          toastr["warning"]("Unable to verify supplier currency. Please try again.");
        }
      });
    } else {
      console.log('No supplier selected');
      // No supplier selected - hide currency info and reset symbols
      $("#supplier_currency_info").hide();
      // Reset to system base currency
      var base_currency_symbol = $("#base_currency_symbol").val() || '$';
      $("#purchase_price_currency_symbol").text(base_currency_symbol);
      $("#discount_currency_symbol").text(base_currency_symbol);
      
      // Reset totals currency symbols
      $("#subtotal_currency_symbol").text(base_currency_symbol);
      $("#other_charges_currency_symbol").text(base_currency_symbol);
      $("#discount_to_all_currency_symbol").text(base_currency_symbol);
      $("#round_off_currency_symbol").text(base_currency_symbol);
      $("#total_amt_currency_symbol").text(base_currency_symbol);
    }
  }, 300); // 300ms delay
}

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

    //Initially flag set true
    var flag=true;

    // Check exchange rate validation before proceeding (non-blocking on server error so purchase can still save)
    var supplier_id = $("#supplier_id").val();
    console.log('Purchase form save clicked, supplier_id:', supplier_id);
    if (supplier_id) {
        var exchangeRateValid = true;
        $.ajax({
            url: base_url + 'exchange_rates/validate_supplier_exchange_rate',
            type: 'POST',
            data: { 
                supplier_id: supplier_id
            },
            dataType: 'json',
            async: false,
            success: function(response) {
                console.log('Exchange rate validation response:', response);
                if (!response || !response.valid) {
                    var msg = (response && response.message) ? response.message : '';
                    // When server returns generic error (e.g. exception), allow save - do not block; no toast to avoid noise
                    if (msg.indexOf('Please try again') !== -1 || msg.indexOf('Error checking') !== -1) {
                        exchangeRateValid = true;
                        return;
                    }
                    exchangeRateValid = false;
                    if (typeof showExchangeRateModal === 'function') {
                        showExchangeRateModal(msg || 'Exchange rate missing.', response && response.from_currency ? response.from_currency : '', response && response.to_currency ? response.to_currency : '', base_url);
                    } else {
                        if (typeof toastr !== 'undefined') toastr.warning('Exchange rate may be missing for this supplier. Add rate in Exchange Rates if needed.');
                    }
                }
            },
            error: function(xhr, status, err) {
                // Do NOT block save when endpoint fails (500/404/network) - allow form to submit; no toast to avoid noise
                exchangeRateValid = true;
            }
        });
        
        if (!exchangeRateValid) {
            return false;
        }
    }

    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("supplier_id");
    check_field("pur_date");
    check_field("purchase_status");
    //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 false;
	}

	//Atleast one record must be added in purchase 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 purchase quantities
			var purchase_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() || '') : '';
			
			// 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;
			
			// Convert batch_tracking_enabled to number for proper comparison
			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);
			} else {
				// If data attribute is missing, check by batch icon presence as fallback
				if(has_batch_icon){
					is_batch_tracked = true;
				}
			}
			
			// IMPORTANT: Only validate batch details for items WITH batch tracking enabled
			if(purchase_qty > 0 && is_batch_tracked === true){
				// This item has batch tracking enabled - batch details are REQUIRED
				if(!batch_number || batch_number.trim() === ''){
					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;
				}
			}
		}	
	}
	
    // CRITICAL: Validate batch details FIRST before checking if items are selected
    // This ensures batch errors are shown before generic "no items" error
    if(batch_validation_error){
    	// 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);
    		}
    	}
    	
    	return false; // BLOCK SAVE - This will prevent "Please Select Item" message
    }
    
    if(flag1==false){
    	toastr["warning"]("Please Select Item!!");
        $("#item_search").focus();
		return false;
    }
    //end

    // Helper function to extract numeric value from formatted text
    function extractNumericValue(element) {
      var text = $(element).text();
      // Remove currency symbols, commas, and any non-numeric characters except decimal point and minus
      text = text.replace(/[^0-9.\-]/g, '');
      var num = parseFloat(text);
      return isNaN(num) ? 0 : num;
    }
    
    var tot_subtotal_amt = extractNumericValue("#subtotal_amt");
    var other_charges_amt = extractNumericValue("#other_charges_amt");//other_charges include tax calcualated amount
    var tot_discount_to_all_amt = extractNumericValue("#discount_to_all_amt");
    var tot_round_off_amt = extractNumericValue("#round_off_amt");
    var tot_total_amt = extractNumericValue("#total_amt");

    var this_id=this.id;
    
			//if(confirm("Do You Wants to Save Record ?")){
				e.preventDefault();
				data = new FormData($('#purchase-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+'purchase/purchase_save_and_update?command='+this_id+'&rowcount='+rowcount+'&tot_subtotal_amt='+tot_subtotal_amt+'&tot_discount_to_all_amt='+tot_discount_to_all_amt+'&tot_round_off_amt='+tot_round_off_amt+'&tot_total_amt='+tot_total_amt+"&other_charges_amt="+other_charges_amt,
				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+"purchase/invoice/"+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();

			   },
			   error: function(xhr, status, error) {
				   $("#"+this_id).attr('disabled',false);  //Enable Save or Update button
				   $(".overlay").remove();
				   
				   // Handle timeout/error errors
				   if (status === 'timeout' || status === 'error') {
					   toastr["error"]("Request timed out. Please try again.");
				   } else {
					   toastr["error"]("An error occurred while saving. Please try again.");
				   }
			   }
			   });
		//}
  
});

$("#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,
                            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($("#purchase_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();
	var supplier_id=$("#supplier_id").val();
	$.post(base_url+"purchase/return_row_with_data/"+rowcount+"/"+item_id,{supplier_id:supplier_id},function(result){
        //alert(result);
        $('#purchase_table tbody').append(result);
       	$("#hidden_rowcount").val(parseInt(rowcount)+1);
        success.currentTime = 0;
        success.play();
        enable_or_disable_item_discount();
        // Explicitly call final_total to ensure quantities are calculated
        if(typeof final_total === 'function'){
            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();
  var available_qty=$("#tr_available_qty_"+rowcount+"_13").val();
  //if(parseInt(item_qty)<parseInt(available_qty)){
    item_qty=parseFloat(item_qty)+1;
    $("#td_data_"+rowcount+"_3").val(format_qty(item_qty));
  //}
  
  calculate_tax(rowcount);
}
//DECREMENT ITEM
function decrement_qty(rowcount){
  var item_qty=parseFloat($("#td_data_"+rowcount+"_3").val());
  if(item_qty<=1){
    $("#td_data_"+rowcount+"_3").val(format_qty(1));
    return;
  }
  $("#td_data_"+rowcount+"_3").val(format_qty(item_qty-1));
  calculate_tax(rowcount);
}

//CALCUALATED SALES PRICE
function calculate_sales_price(rowcount){
  var purchase_price = (isNaN(parseFloat($("#td_data_"+rowcount+"_10").val()))) ? 0 :parseFloat($("#td_data_"+rowcount+"_10").val()); 
  var profit_margin = (isNaN(parseFloat($("#td_data_"+rowcount+"_12").val()))) ? 0 :parseFloat($("#td_data_"+rowcount+"_12").val()); 
  var tax_type = $("#tax_type").val();
  var sales_price =parseFloat(0);
    sales_price = purchase_price + ((purchase_price*profit_margin)/parseFloat(100));
  $("#td_data_"+rowcount+"_13").val(sales_price.toFixed(2));
}
//END
//CALCULATE PROFIT MARGIN PERCENTAGE
function calculate_profit_margin(rowcount){
  var purchase_price = (isNaN(parseFloat($("#td_data_"+rowcount+"_10").val()))) ? 0 :parseFloat($("#td_data_"+rowcount+"_10").val()); 
  var sales_price = (isNaN(parseFloat($("#td_data_"+rowcount+"_13").val()))) ? 0 :parseFloat($("#td_data_"+rowcount+"_13").val());  
  var profit_margin = (sales_price-purchase_price);
  var profit_margin = (profit_margin/purchase_price)*parseFloat(100);
  $("#td_data_"+rowcount+"_12").val(profit_margin.toFixed(2));
}
//END

function update_paid_payment_total() {
  var rowcount=$("#paid_amt_tot").attr("data-rowcount");
  var tot=0;
  for(i=1;i<rowcount;i++){
    if(document.getElementById("paid_amt_"+i)){
      tot += parseFloat($("#paid_amt_"+i).html());
    }
  }
  $("#paid_amt_tot").html(to_Fixed(tot));
}
function delete_payment(payment_id){
 if(confirm("Do You Wants to Delete Record ?")){
    var base_url=$("#base_url").val();
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
   $.post(base_url+"purchase/delete_payment",{payment_id:payment_id},function(result){
   //alert(result);return;
   result=result;
     if(result=="success")
        {
          toastr["success"]("Record Deleted Successfully!");
          $("#payment_row_"+payment_id).remove();
          success.currentTime = 0; 
          success.play();
        }
        else if(result=="failed"){
          toastr["error"]("Failed to Delete .Try again!");
          failed.currentTime = 0; 
          failed.play();
        }
        else{
          toastr["error"](result);
          failed.currentTime = 0; 
          failed.play();
        }
        $(".overlay").remove();
        update_paid_payment_total();
   });
   }//end confirmation   
  }

  //Delete Record start
function delete_purchase(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+"purchase/delete_purchase",{q_id:q_id},function(result){
   //alert(result);return;
     if(result=="success")
        {
          toastr["success"]("Record Deleted Successfully!");
          $('#example2').DataTable().ajax.reload();
        }
        else if(result=="failed"){
          toastr["error"]("Failed to Delete .Try again!");
        }
        else{
           toastr["error"](result);
        }
        $(".overlay").remove();
        return false;
   });
   }//end confirmation
}
//Delete Record end
function multi_delete(){
  var base_url=$("#base_url").val();
    var this_id=this.id;
    
    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+'purchase/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
}

function pay_now(purchase_id){
  var base_url=$("#base_url").val();
  $.post(base_url+'purchase/show_pay_now_modal', {purchase_id: purchase_id}, function(result) {
    $(".pay_now_modal").html('').html(result);
    //Date picker
    $('.datepicker').datepicker({
      autoclose: true,
    format: 'dd-mm-yyyy',
     todayHighlight: true
    });
    $('#pay_now').modal('toggle');

  });
}
function view_payments(purchase_id){
  var base_url=$("#base_url").val();
  $.post(base_url+'purchase/view_payments_modal', {purchase_id: purchase_id}, function(result) {
    $(".view_payments_modal").html('').html(result);
    $('#view_payments_modal').modal('toggle');
  });
}

function save_payment(purchase_id){
  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("amount");
    check_field("payment_date");


    var payment_date=$("#payment_date").val();
    var amount=$("#amount").val();
    var payment_type=$("#payment_type").val();
    var payment_note=$("#payment_note").val();
    var account_id=$("#account_id").val();
    var supplier_id=$("#supplier_id").val();

    if(amount == 0){
      toastr["error"]("Please Enter Valid Amount!");
      return false; 
    }

    if(amount > parseFloat($("#due_amount_temp").html())){
      toastr["error"]("Entered Amount Should not be Greater than Due Amount!");
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $(".payment_save").attr('disabled',true);  //Enable Save or Update button
    $.post(base_url+'purchase/save_payment', {supplier_id:supplier_id,account_id:account_id,purchase_id: purchase_id,payment_type:payment_type,amount:amount,payment_date:payment_date,payment_note:payment_note}, function(result) {
      result=result;
  //alert(result);return;
        if(result=="success")
        {
          $('#pay_now').modal('toggle');
          toastr["success"]("Payment Recorded Successfully!");
          success.currentTime = 0; 
          success.play();
          $('#example2').DataTable().ajax.reload();
        }
        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();
        }
        $(".payment_save").attr('disabled',false);  //Enable Save or Update button
        $(".overlay").remove();
    });
}

function delete_purchase_payment(payment_id){
 if(confirm("Do You Wants to Delete Record ?")){
    var base_url=$("#base_url").val();
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
   $.post(base_url+"purchase/delete_payment",{payment_id:payment_id},function(result){
   //alert(result);return;
   result=result;
     if(result=="success")
        {
          $('#view_payments_modal').modal('toggle');
          toastr["success"]("Record Deleted Successfully!");
          success.currentTime = 0; 
          success.play();
          $('#example2').DataTable().ajax.reload();
        }
        else if(result=="failed"){
          toastr["error"]("Failed to Delete .Try again!");
          failed.currentTime = 0; 
          failed.play();
        }
        else{
          toastr["error"](result);
          failed.currentTime = 0; 
          failed.play();
        }
        $(".overlay").remove();
   });
   }//end confirmation   
  }

  $('#item_search').keypress(function (e) {
 var key = e.which;
 // the enter key code
 if(key == 13){
    $("#item_search").autocomplete('search');
  }
});

// Supplier currency change event
// Initialize currency on page load
$(document).ready(function() {
  // Wait a bit for all elements to load
  setTimeout(function() {
    var supplier_id = $("#supplier_id").val();
    var base_currency_symbol = $("#base_currency_symbol").val() || '$';
    
    if (supplier_id && supplier_id !== '' && supplier_id !== '1') {
      // Trigger supplier change to load currency
      $("#supplier_id").trigger('change');
    } else {
      // No supplier or walk-in - use base currency
      $("#purchase_price_currency_symbol").text(base_currency_symbol);
      $("#discount_currency_symbol").text(base_currency_symbol);
      $("#subtotal_currency_symbol").text(base_currency_symbol);
      $("#other_charges_currency_symbol").text(base_currency_symbol);
      $("#discount_to_all_currency_symbol").text(base_currency_symbol);
      $("#round_off_currency_symbol").text(base_currency_symbol);
      $("#total_amt_currency_symbol").text(base_currency_symbol);
    }
  }, 200);
});

$("#supplier_id").on("change", function() {
  show_supplier_currency();
});

// Show supplier currency information
function show_supplier_currency() {
  var supplier_id = $("#supplier_id").val();
  var base_url = $("#base_url").val();
  
  // Hide currency display first
  $("#supplier_currency_info").hide();
  
  if (supplier_id) {
    // Check if it's a walk-in supplier (ID 1 or contains "walk-in" in text)
    var supplierText = $("#supplier_id option:selected").text();
    if (supplier_id === '1' || supplierText.toLowerCase().includes('walk-in')) {
      console.log('Walk-in supplier detected in show_supplier_currency');
      // Show walk-in supplier currency display in GREEN
      var baseCurrency = window.baseCurrencyName || 'Base Currency';
      var baseCode = window.baseCurrencyCode || 'USD';
      var baseSymbol = window.baseCurrencySymbol || '$';
      
      var supplierText = baseCurrency + " (" + baseCode + ")";
      $("#supplier_currency_name").text(supplierText);
      $("#supplier_currency_info").show().removeClass('label-danger').addClass('label-success');
      
      // Update currency symbols for headers and totals
      $("#purchase_price_currency_symbol").text(baseSymbol);
      $("#discount_currency_symbol").text(baseSymbol);
      $("#subtotal_currency_symbol").text(baseSymbol);
      $("#other_charges_currency_symbol").text(baseSymbol);
      $("#discount_to_all_currency_symbol").text(baseSymbol);
      $("#round_off_currency_symbol").text(baseSymbol);
      $("#total_amt_currency_symbol").text(baseSymbol);
      return;
    }
    
    $.ajax({
      url: base_url + 'purchase/check_currency_availability',
      type: 'POST',
      data: { supplier_id: supplier_id },
      dataType: 'json',
      success: function(response) {
        if (response.success) {
          // Get supplier currency details
          $.ajax({
            url: base_url + 'suppliers/get_supplier_currency',
            type: 'POST',
            data: { supplier_id: supplier_id },
            dataType: 'json',
            success: function(currency_response) {
              if (currency_response.currency_name) {
                var supplierText = currency_response.currency_name + ' (' + currency_response.currency_code + ')';
                $("#supplier_currency_name").text(supplierText);
                $("#supplier_currency_info").show().removeClass('label-danger').addClass('label-success');
                
                // Change currency symbols in table headers
                var symbol = currency_response.currency_symbol || currency_response.currency_code;
                $("#purchase_price_currency_symbol").text(symbol);
                $("#discount_currency_symbol").text(symbol);
                $("#other_charges_currency_symbol").text(symbol);
                $("#round_off_currency_symbol").text(symbol);
                $("#total_amt_currency_symbol").text(symbol);
              } else {
                $("#supplier_currency_info").hide();
                // Reset to base currency symbol
                var baseSymbol = '$';
                $("#purchase_price_currency_symbol").text(baseSymbol);
                $("#discount_currency_symbol").text(baseSymbol);
                $("#other_charges_currency_symbol").text(baseSymbol);
                $("#round_off_currency_symbol").text(baseSymbol);
                $("#total_amt_currency_symbol").text(baseSymbol);
              }
            }
          });
        } else {
          // Show error message
          $("#supplier_currency_name").text('Error: ' + response.message);
          $("#supplier_currency_info").show().removeClass('label-info label-danger').addClass('label-success');
        }
      },
      error: function() {
        $("#supplier_currency_info").hide();
      }
    });
  } else {
    $("#supplier_currency_info").hide();
    // Reset to base currency symbol
    var baseSymbol = '$';
    $("#purchase_price_currency_symbol").text(baseSymbol);
    $("#discount_currency_symbol").text(baseSymbol);
    $("#other_charges_currency_symbol").text(baseSymbol);
    $("#round_off_currency_symbol").text(baseSymbol);
    $("#total_amt_currency_symbol").text(baseSymbol);
  }
}

// Supplier change event listener
$("#supplier_id").on("change select2:select", function() {
  console.log('Supplier ID changed to:', $(this).val());
  // Check if supplier has different currency than base currency
  check_supplier_currency_for_purchase();
});

// Also check currency when supplier is loaded via AJAX
function set_supplier_currency() {
  // Check currency when supplier is selected (use the same debounced function)
  console.log('Supplier selected via set_supplier_currency, checking currency...');
  check_supplier_currency_for_purchase();
}

// Purchase Payment Functions
var paymentCurrencyLoading = false;
var accountLoading = false;
var accountCache = {}; // Cache for loaded accounts

function updatePaymentCurrencyPurchase() {
  // Prevent multiple simultaneous calls
  if (paymentCurrencyLoading) {
    console.log('Payment currency update already in progress, skipping...');
    return;
  }
  
  var selected_currency = $('#payment_currency').val();
  var base_currency_id = '<?= get_base_currency()->id; ?>';
  var supplier_currency_id = null;

  if (!selected_currency) {
    $('#account_id').html('<option value="">-Select Currency First-</option>');
    return;
  }

  paymentCurrencyLoading = true;
  console.log('Updating payment currency to:', selected_currency);

  // Get supplier currency if available
  var supplier_id = $('#supplier_id').val();
  if (supplier_id) {
    $.ajax({
      url: base_url + 'purchase/get_supplier_currency',
      type: 'POST',
      data: { supplier_id: supplier_id },
      dataType: 'json',
      success: function(response) {
        paymentCurrencyLoading = false;
        if (response && response.status) {
          supplier_currency_id = response.supplier_currency_id;
          // Auto-select supplier currency account if payment currency matches supplier currency
          if (selected_currency == supplier_currency_id) {
            autoSelectCurrencyAccountPurchase();
          } else {
            // Load accounts for selected currency
            loadAccountsForPaymentCurrency(selected_currency);
          }
        } else {
          loadAccountsForPaymentCurrency(selected_currency);
        }
      },
      error: function() {
        paymentCurrencyLoading = false;
        loadAccountsForPaymentCurrency(selected_currency);
      }
    });
  } else {
    paymentCurrencyLoading = false;
    loadAccountsForPaymentCurrency(selected_currency);
  }
}

function loadAccountsForPaymentCurrency(currency_id) {
  if (!currency_id) return;
  
  // Check if accounts are already cached for this currency
  if (accountCache[currency_id]) {
    console.log('Using cached accounts for currency:', currency_id);
    displayCachedAccounts(currency_id);
    return;
  }
  
  // Prevent multiple simultaneous calls
  if (accountLoading) {
    console.log('Account loading already in progress, skipping...');
    return;
  }
  
  accountLoading = true;
  console.log('Loading accounts for currency:', currency_id);
  
  // Show loading state
  $('#account_id').html('<option value="">Loading accounts...</option>');
  
  $.ajax({
    url: base_url + 'purchase/get_accounts_by_currency',
    type: 'POST',
    data: { currency_id: currency_id },
    dataType: 'json',
    success: function(response) {
      accountLoading = false;
      console.log('Accounts loaded:', response);
      
      if (response && response.accounts && response.accounts.length > 0) {
        // Cache the accounts
        accountCache[currency_id] = response;
        
        // Display the accounts
        displayCachedAccounts(currency_id);
        
        // Auto-select first account with sufficient balance if payment currency matches supplier currency
        if (response.supplier_currency_id && currency_id == response.supplier_currency_id) {
          setTimeout(function() {
            autoSelectCurrencyAccountPurchase();
          }, 100);
        }
      } else {
        $('#account_id').html('<option value="">No accounts available for this currency</option>');
      }
    },
    error: function() {
      accountLoading = false;
      console.log('Error loading accounts');
      $('#account_id').html('<option value="">Error loading accounts</option>');
    }
  });
}

function displayCachedAccounts(currency_id) {
  var response = accountCache[currency_id];
  if (!response || !response.accounts) return;
  
  var options = '<option value="">-Select Account-</option>';
  $.each(response.accounts, function(index, account) {
    var balance = parseFloat(account.balance) || 0;
    var balanceText = balance >= 0 ? 
      ' (Balance: ' + account.currency_symbol + ' ' + balance.toFixed(2) + ')' : 
      ' (Balance: ' + account.currency_symbol + ' ' + balance.toFixed(2) + ')';
    options += '<option value="' + account.id + '" data-balance="' + balance + '" data-currency="' + account.currency_id + '">' + 
              account.account_name + balanceText + '</option>';
  });
  $('#account_id').html(options);
  // Track current currency to prevent reloading
  $('#account_id').data('current-currency', currency_id);
}

function autoSelectCurrencyAccountPurchase() {
  var supplier_id = $('#supplier_id').val();
  var payment_currency = $('#payment_currency').val();
  
  if (!supplier_id || !payment_currency) return;
  
  console.log('Auto-selecting currency account for supplier:', supplier_id, 'currency:', payment_currency);
  
  // Get supplier currency
  $.ajax({
    url: base_url + 'purchase/get_supplier_currency',
    type: 'POST',
    data: { supplier_id: supplier_id },
    dataType: 'json',
    success: function(response) {
      if (response && response.status) {
        var supplier_currency_id = response.supplier_currency_id;
        
        // Load accounts for supplier currency (will use cache if available)
        loadAccountsForPaymentCurrency(supplier_currency_id);
        
        // Auto-select the account with highest balance after accounts are loaded
        setTimeout(function() {
          var maxBalance = -999999;
          var selectedAccountId = '';
          
          $('#account_id option').each(function() {
            var balance = parseFloat($(this).data('balance')) || 0;
            if (balance > maxBalance) {
              maxBalance = balance;
              selectedAccountId = $(this).val();
            }
          });
          
          if (selectedAccountId) {
            console.log('Auto-selecting account:', selectedAccountId, 'with balance:', maxBalance);
            $('#account_id').val(selectedAccountId).trigger('change');
          }
        }, 500); // Reduced timeout since we're using cache
      }
    }
  });
}

function checkAccountBalance() {
  var account_id = $('#account_id').val();
  var payment_amount = parseFloat($('#amount').val()) || 0;
  var payment_currency = $('#payment_currency').val();
  
  if (!account_id) {
    $('#account_balance_display').html('');
    return;
  }
  
  $.ajax({
    url: base_url + 'purchase/get_account_balance',
    type: 'POST',
    data: { account_id: account_id },
    dataType: 'json',
    success: function(response) {
      if (response && response.success) {
        var balance = parseFloat(response.balance) || 0;
        var currency_symbol = response.currency_symbol || '$';
        var account_currency = response.currency_id;
        
        // Display balance
        var balanceText = 'Available Balance: ' + currency_symbol + ' ' + balance.toFixed(2);
        var balanceClass = balance >= payment_amount ? 'text-success' : 'text-danger';
        $('#account_balance_display').html('<span class="' + balanceClass + '">' + balanceText + '</span>');
        
        // Check currency mismatch
        if (account_currency != payment_currency) {
          $('#account_currency_alert').show();
        } else {
          $('#account_currency_alert').hide();
        }
        
        // Check sufficient balance
        if (payment_amount > 0 && balance < payment_amount) {
          var shortfall = payment_amount - balance;
          var shortfallText = '<br><span class="text-danger"><i class="fa fa-exclamation-triangle"></i> Insufficient balance. Shortfall: ' + 
                             currency_symbol + ' ' + shortfall.toFixed(2) + '</span>';
          $('#account_balance_display').append(shortfallText);
        }
      } else {
        $('#account_balance_display').html('<span class="text-danger">Error loading account balance</span>');
      }
    },
    error: function() {
      $('#account_balance_display').html('<span class="text-danger">Error loading account balance</span>');
    }
  });
}

function validateAccountCurrencyPurchase() {
  var account_currency = $('#account_id option:selected').data('currency');
  var payment_currency = $('#payment_currency').val();
  
  if (account_currency && payment_currency && account_currency != payment_currency) {
    $('#account_currency_alert').show();
  } else {
    $('#account_currency_alert').hide();
  }
}

function checkPaymentCurrencyExchangeRatePurchase() {
  var payment_currency = $('#payment_currency').val();
  var base_currency_id = '<?= get_base_currency()->id; ?>';
  
  if (payment_currency && payment_currency != base_currency_id) {
    // Check if exchange rate exists for this currency
    $.ajax({
      url: base_url + 'exchange_rates/check_exchange_rate',
      type: 'POST',
      data: { 
        from_currency_id: payment_currency,
        to_currency_id: base_currency_id
      },
      dataType: 'json',
      success: function(response) {
        if (!response || !response.exists) {
          toastr.warning('Exchange rate not found for this currency. Please add exchange rate in Exchange Rates Management.');
        }
      }
    });
  }
}

// Function to clear account cache
function clearAccountCache() {
  accountCache = {};
  console.log('Account cache cleared');
}

// Make functions globally available
window.updatePaymentCurrencyPurchase = updatePaymentCurrencyPurchase;
window.autoSelectCurrencyAccountPurchase = autoSelectCurrencyAccountPurchase;
window.checkAccountBalance = checkAccountBalance;
window.validateAccountCurrencyPurchase = validateAccountCurrencyPurchase;
window.checkPaymentCurrencyExchangeRatePurchase = checkPaymentCurrencyExchangeRatePurchase;
window.clearAccountCache = clearAccountCache;

// Batch Details Modal Functions
function show_batch_details_modal(row_id, item_id) {
    console.log('show_batch_details_modal called with row_id:', row_id, 'item_id:', item_id);
    
    // Get item tracking information from hidden fields
    var batch_tracking_enabled = $('#batch_tracking_enabled_' + row_id).val();
    var tracking_type = $('#tracking_type_' + row_id).val();
    var expiry_enabled = $('#expiry_enabled_' + row_id).val();
    
    console.log('Batch tracking enabled:', batch_tracking_enabled);
    console.log('Tracking type:', tracking_type);
    console.log('Expiry enabled:', expiry_enabled);
    
    if (batch_tracking_enabled == 1) {
        console.log('Opening batch modal...');
        
        // Set the item name in modal title
        var item_name = $('#td_data_' + row_id + '_1').text();
        $('#modal_item_name').text(item_name);
        
        // Set current quantity as default
        var current_qty = $('#td_data_' + row_id + '_3').val();
        $('#batch_quantity').val(current_qty);
        
        // Load existing batch details if they exist
        var existing_batch_number = $('#batch_number_' + row_id).val();
        var existing_manufacturing_date = $('#manufacturing_date_' + row_id).val();
        var existing_expiry_date = $('#expiry_date_' + row_id).val();
        var existing_batch_notes = $('#batch_notes_' + row_id).val();
        
        // Set existing values or clear fields
        $('#batch_number').val(existing_batch_number || '');
        $('#batch_notes').val(existing_batch_notes || '');
        
        // Handle dates based on tracking type - convert from YYYY-MM-DD to DD-MM-YYYY for display
        if (tracking_type === 'expiry_only') {
            // Only show expiry date, hide manufacturing date
            $('#manufacturing_date').closest('.form-group').hide();
            $('#expiry_date').closest('.form-group').show();
            
            // Clear manufacturing date
            $('#manufacturing_date').val('');
            
            // Set expiry date if exists
            if (existing_expiry_date && existing_expiry_date !== '0000-00-00') {
                var exp_parts = existing_expiry_date.split('-');
                if (exp_parts.length === 3 && exp_parts[0] !== '0000') {
                    var exp_formatted = exp_parts[2] + '-' + exp_parts[1] + '-' + exp_parts[0]; // DD-MM-YYYY
                    $('#expiry_date').val(exp_formatted);
                }
            } else {
                $('#expiry_date').val('');
            }
            
        } else if (tracking_type === 'mfg_only') {
            // Only show manufacturing date, hide expiry date
            $('#manufacturing_date').closest('.form-group').show();
            $('#expiry_date').closest('.form-group').hide();
            
            // Clear expiry date
            $('#expiry_date').val('');
            
            // Set manufacturing date if exists
            if (existing_manufacturing_date && existing_manufacturing_date !== '0000-00-00') {
                var mfg_parts = existing_manufacturing_date.split('-');
                if (mfg_parts.length === 3 && mfg_parts[0] !== '0000') {
                    var mfg_formatted = mfg_parts[2] + '-' + mfg_parts[1] + '-' + mfg_parts[0]; // DD-MM-YYYY
                    $('#manufacturing_date').val(mfg_formatted);
                }
            } else {
                // Set today's date as default for manufacturing date
                var today = new Date();
                var formattedDate = today.getDate().toString().padStart(2, '0') + '-' + 
                                  (today.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                  today.getFullYear(); // DD-MM-YYYY
                $('#manufacturing_date').val(formattedDate);
            }
            
        } else if (tracking_type === 'both') {
            // Show both manufacturing and expiry dates
            $('#manufacturing_date').closest('.form-group').show();
            $('#expiry_date').closest('.form-group').show();
            
            // Set manufacturing date if exists
            if (existing_manufacturing_date && existing_manufacturing_date !== '0000-00-00') {
                var mfg_parts = existing_manufacturing_date.split('-');
                if (mfg_parts.length === 3 && mfg_parts[0] !== '0000') {
                    var mfg_formatted = mfg_parts[2] + '-' + mfg_parts[1] + '-' + mfg_parts[0]; // DD-MM-YYYY
                    $('#manufacturing_date').val(mfg_formatted);
                }
            } else {
                // Set today's date as default for manufacturing date
                var today = new Date();
                var formattedDate = today.getDate().toString().padStart(2, '0') + '-' + 
                                  (today.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                  today.getFullYear(); // DD-MM-YYYY
                $('#manufacturing_date').val(formattedDate);
            }
            
            // Set expiry date if exists
            if (existing_expiry_date && existing_expiry_date !== '0000-00-00') {
                var exp_parts = existing_expiry_date.split('-');
                if (exp_parts.length === 3 && exp_parts[0] !== '0000') {
                    var exp_formatted = exp_parts[2] + '-' + exp_parts[1] + '-' + exp_parts[0]; // DD-MM-YYYY
                    $('#expiry_date').val(exp_formatted);
                }
            } else {
                $('#expiry_date').val('');
            }
            
        } else {
            // tracking_type === 'none' - hide both date fields
            $('#manufacturing_date').closest('.form-group').hide();
            $('#expiry_date').closest('.form-group').hide();
            
            // Clear both dates
            $('#manufacturing_date').val('');
            $('#expiry_date').val('');
        }
        
        // Fields are already shown/hidden based on tracking type above
        
        // Store current row ID for saving
        window.current_batch_row_id = row_id;
        
        // Hide only the main purchase date picker to prevent interference
        $('#pur_date').datepicker('hide');
        
        // Show the modal
        $('#batch_details_modal').modal('show');
        
        console.log('Modal should be showing now');
    } else {
        alert('This item does not have batch tracking enabled.');
    }
}

// No cleanup function needed - we handle this in the modal show event

// Modal closed - restore main date picker
$('#batch_details_modal').on('hidden.bs.modal', function() {
    console.log('Modal closed, restoring main date picker');
    
    // Re-initialize the main purchase date picker
    $('#pur_date').datepicker({
        autoclose: true,
        format: 'dd-mm-yyyy',
        todayHighlight: true
    });
    
    console.log('Main date picker restored');
});

// Fix modal z-index issues when shown
$('#batch_details_modal').on('shown.bs.modal', function() {
    console.log('Modal shown, initializing date pickers...');
    
    // Initialize batch modal date pickers
    $('#manufacturing_date, #expiry_date').datepicker({
        autoclose: true,
        format: 'dd-mm-yyyy',
        todayHighlight: true
    });
    
    console.log('Modal date pickers initialized');
});

// Initialize batch modal date pickers when modal opens (original design)
$('#batch_details_modal').on('show.bs.modal', function() {
    console.log('Modal about to show, initializing date pickers...');
    
    // Initialize batch modal date pickers using the same method as main form
    setTimeout(function() {
        $('#manufacturing_date, #expiry_date').datepicker({
            autoclose: true,
            format: 'dd-mm-yyyy',
            todayHighlight: true
        });
        
        console.log('Batch modal date pickers initialized');
    }, 100);
});

// Ensure the save button is properly bound when document is ready
$(document).ready(function() {
    // Remove any existing click handlers to avoid duplicates
    $('#save_batch_details').off('click');
    
    // Bind the click handler
    $('#save_batch_details').on('click', function() {
        console.log('Save batch details clicked');
        
        var row_id = window.current_batch_row_id;
        var batch_number = $('#batch_number').val();
        var batch_quantity = $('#batch_quantity').val();
        var manufacturing_date = $('#manufacturing_date').val();
        var expiry_date = $('#expiry_date').val();
        var batch_notes = $('#batch_notes').val();
        
        console.log('Values:', {
            row_id: row_id,
            batch_number: batch_number,
            batch_quantity: batch_quantity,
            manufacturing_date: manufacturing_date,
            expiry_date: expiry_date,
            batch_notes: batch_notes
        });
        
        // Validate required fields
        if (!batch_number || !batch_number.trim()) {
            alert('Please enter batch number');
            $('#batch_number').focus();
            return;
        }
        
        if (!batch_quantity || batch_quantity <= 0) {
            alert('Please enter valid quantity');
            $('#batch_quantity').focus();
            return;
        }
        
        // Check if row_id is valid
        if (!row_id) {
            alert('Error: No row ID found. Please try again.');
            console.error('No row_id found');
            return;
        }
        
        // Convert date format from DD-MM-YYYY to YYYY-MM-DD for database
        var manufacturing_date_db = '';
        var expiry_date_db = '';
        
        if (manufacturing_date) {
            // Handle DD-MM-YYYY format (system default)
            var mfg_parts = manufacturing_date.split('-');
            if (mfg_parts.length === 3) {
                manufacturing_date_db = mfg_parts[2] + '-' + mfg_parts[1].padStart(2, '0') + '-' + mfg_parts[0].padStart(2, '0');
            }
        }
        
        if (expiry_date) {
            // Handle DD-MM-YYYY format (system default)
            var exp_parts = expiry_date.split('-');
            if (exp_parts.length === 3) {
                expiry_date_db = exp_parts[2] + '-' + exp_parts[1].padStart(2, '0') + '-' + exp_parts[0].padStart(2, '0');
            }
        }
        
        console.log('Date conversion:', {
            manufacturing_date: manufacturing_date,
            expiry_date: expiry_date,
            manufacturing_date_db: manufacturing_date_db,
            expiry_date_db: expiry_date_db
        });
        
        // Store batch details in hidden fields (update existing or create new)
        $('#batch_number_' + row_id).val(batch_number);
        $('#manufacturing_date_' + row_id).val(manufacturing_date_db);
        $('#expiry_date_' + row_id).val(expiry_date_db);
        $('#batch_notes_' + row_id).val(batch_notes);
        
        console.log('Hidden fields updated');
        
        // If hidden fields don't exist, create them
        if ($('#batch_number_' + row_id).length === 0) {
            $('#tr_item_id_' + row_id).after(
                '<input type="hidden" id="batch_number_' + row_id + '" name="batch_number_' + row_id + '" value="' + batch_number + '">' +
                '<input type="hidden" id="batch_quantity_' + row_id + '" name="batch_quantity_' + row_id + '" value="' + batch_quantity + '">' +
                '<input type="hidden" id="manufacturing_date_' + row_id + '" name="manufacturing_date_' + row_id + '" value="' + manufacturing_date_db + '">' +
                '<input type="hidden" id="expiry_date_' + row_id + '" name="expiry_date_' + row_id + '" value="' + expiry_date_db + '">' +
                '<input type="hidden" id="batch_notes_' + row_id + '" name="batch_notes_' + row_id + '" value="' + batch_notes + '">'
            );
        }
        
        // Update quantity in the table
        $('#td_data_' + row_id + '_3').val(batch_quantity);
        
        // Add batch info display to the table
        var batch_display = '';
        if (batch_number) batch_display += '<br><small class="text-info"><strong>Batch:</strong> ' + batch_number + '</small>';
        if (manufacturing_date) batch_display += '<br><small class="text-info"><strong>MFG:</strong> ' + manufacturing_date + '</small>';
        if (expiry_date) batch_display += '<br><small class="text-warning"><strong>EXP:</strong> ' + expiry_date + '</small>';
        
        // Update the item name cell to show batch info
        var current_item_name = $('#td_data_' + row_id + '_1').text();
        $('#td_data_' + row_id + '_1').html(current_item_name + batch_display);
        
        // Close the modal
        $('#batch_details_modal').modal('hide');
        
        // Recalculate totals
        calculate_tax(row_id);
        
        console.log('Batch details saved for row:', row_id);
        console.log('Batch number:', batch_number);
        console.log('Manufacturing date:', manufacturing_date_db);
        console.log('Expiry date:', expiry_date_db);
        
        // No success message - just close modal silently
});
    
    console.log('Save batch details button bound');
});

// Multi-Unit Functions for Purchase
function updateUnitPriceWithPrevious(rowcount) {
    var unitSelect = $("#unit_type_"+rowcount);
    var unitType = unitSelect.val();
    var previousUnitType = unitSelect.data('previous-unit') || 'main';
    var conversionFactor = parseFloat($("#conversion_factor_"+rowcount).val()) || 1.0;
    
    if (!conversionFactor || conversionFactor <= 0) {
        // Update previous unit and return
        unitSelect.data('previous-unit', unitType);
        return; // No multi-unit support
    }
    
    // Get current price value - handle formatted values
    var priceInput = $("#td_data_"+rowcount+"_4");
    var currentPriceRaw = priceInput.val() || '0';
    var currentPrice = parseFloat(currentPriceRaw.toString().replace(/[^0-9.]/g, '')) || 0;
    
    console.log('updateUnitPriceWithPrevious called for row:', rowcount);
    console.log('  - Previous unit:', previousUnitType);
    console.log('  - New unit:', unitType);
    console.log('  - Current price:', currentPrice);
    console.log('  - Conversion factor:', conversionFactor);
    
    var newPrice = 0;
    
    // Only convert if unit actually changed AND we have a price
    if (previousUnitType != unitType && currentPrice > 0) {
        if (unitType == 'main' && previousUnitType == 'alternate') {
            // Converting from alternate to main: multiply
            newPrice = currentPrice * conversionFactor;
            console.log('  - Converting alternate to main:', currentPrice, 'x', conversionFactor, '=', newPrice);
        } else if (unitType == 'alternate' && previousUnitType == 'main') {
            // Converting from main to alternate: divide
            newPrice = currentPrice / conversionFactor;
            console.log('  - Converting main to alternate:', currentPrice, '/', conversionFactor, '=', newPrice);
        }
    } else if (currentPrice > 0) {
        // Unit didn't change or no conversion needed, keep current price
        newPrice = currentPrice;
    } else {
        // No current price, try to get stored price for selected unit
        if (unitType == 'main') {
            var storedMainPrice = parseFloat($("#purchase_price_main_"+rowcount).val()) || 0;
            if (storedMainPrice > 0) {
                newPrice = storedMainPrice;
            }
        } else if (unitType == 'alternate') {
            var storedAltPrice = parseFloat($("#purchase_price_alternate_"+rowcount).val()) || 0;
            if (storedAltPrice > 0) {
                newPrice = storedAltPrice;
            } else {
                // Calculate from main price if available
                var storedMainPrice = parseFloat($("#purchase_price_main_"+rowcount).val()) || 0;
                if (storedMainPrice > 0 && conversionFactor > 0) {
                    newPrice = storedMainPrice / conversionFactor;
                }
            }
        }
    }
    
    // Update the price field
    if (newPrice > 0) {
        priceInput.val(newPrice.toFixed(2));
        console.log('  - Updated price to:', newPrice.toFixed(2));
        
        // Update stored prices
        if (unitType == 'main') {
            $("#purchase_price_main_"+rowcount).val(newPrice.toFixed(2));
            if (conversionFactor > 0) {
                $("#purchase_price_alternate_"+rowcount).val((newPrice / conversionFactor).toFixed(2));
            }
        } else if (unitType == 'alternate') {
            $("#purchase_price_alternate_"+rowcount).val(newPrice.toFixed(2));
            if (conversionFactor > 0) {
                $("#purchase_price_main_"+rowcount).val((newPrice * conversionFactor).toFixed(2));
            }
        }
    }
    
    // Update the previous unit type for next conversion
    unitSelect.data('previous-unit', unitType);
    
    // Recalculate tax after price change
    calculate_tax(rowcount);
}

// Legacy function name for backwards compatibility
function updateUnitPrice(rowcount) {
    updateUnitPriceWithPrevious(rowcount);
}

function updateUnitConversion(rowcount) {
    var unitType = $("#unit_type_"+rowcount).val();
    var conversionFactor = parseFloat($("#conversion_factor_"+rowcount).val()) || 1.0;
    var qty = parseFloat($("#td_data_"+rowcount+"_3").val()) || 0;
    
    if (!conversionFactor || conversionFactor <= 0 || qty <= 0) {
        return; // No conversion needed
    }
    
    // The quantity is already in the selected unit, so we just need to ensure
    // the price matches the selected unit. The conversion for storage happens on save.
    // For display purposes, we can show a tooltip or update the price field.
    
    // Update price based on unit type (already handled in updateUnitPrice)
    updateUnitPrice(rowcount);
}