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

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

}
/*Email validation code*/
function validateEmail(sEmail) {
  var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,9}|[0-9]{1,3})(\]?)$/;
  if (filter.test(sEmail)) {
      return true;
  }
  else {
      return false;
  }
}

function uncheck_allow_tot_advance(){
//verify is checked ?
if($("#allow_tot_advance").is(':checked')){
  $("#click_to_uncheck").trigger("click");
}
}

$("#pay_all").on("click",function(){
// Check account before proceeding with Pay All
check_pay_all_account();
});

function save(print=false,pay_all=false){

//$('.make_sale').on("click",function (e) {

var base_url=$("#base_url").val();
  
  if($(".items_table tr").length==1){
    toastr["warning"]("Empty Sales List!!");
  return;
  }

  // Check stock availability before saving (always, regardless of online/offline)
  var stock_check_passed = true;
  var stock_error_message = '';
  
  // Check each item for stock availability
  $(".items_table tbody tr").each(function(index) {
      var row = $(this);
      var item_id = row.find('input[name^="tr_item_id_"]').val();
      var service_bit = row.find('input[name^="service_bit_"]').val();
      var qty = row.find('input[id^="item_qty_"]').val();
      var stock = row.find('td:nth-child(2)').text().trim(); // Stock is in 2nd column
      
      if (service_bit != '1' && stock != '') {
          if (parseFloat(stock) < 0) {
              stock_check_passed = false;
              stock_error_message = 'Some items have negative stock. Please check inventory.';
              return false;
          }
          if (parseFloat(qty) > parseFloat(stock)) {
              stock_check_passed = false;
              stock_error_message = 'Not enough stock available for some items.';
              return false;
          }
      }
  });
  
  if (!stock_check_passed) {
      toastr["error"](stock_error_message, "Stock Issue");
      failed.currentTime = 0;
      failed.play();
      return;
  }

// Check if customer has different currency than base currency
  var customer_id = $("#customer_id").val();
  if (customer_id && customer_id !== '' && customer_id !== '1') {
      // Make synchronous AJAX call to check customer currency
      var currency_check_passed = true;
      $.ajax({
          url: base_url + 'customers/get_customer_currency',
          type: 'POST',
          data: { customer_id: customer_id },
          dataType: 'json',
          async: false, // Make it synchronous
          success: function(currency_response) {
              if (currency_response.status) {
                  // Check if customer currency is different from base currency
                  if (currency_response.customer_currency_id && 
                      currency_response.customer_currency_id != currency_response.base_currency_id) {
                      currency_check_passed = false;
                  }
              }
          },
          error: function() {
              // Error checking customer currency for POS
          }
      });
      
      if (!currency_check_passed) {
          toastr["error"](
            "Cannot Save POS Transaction!<br>" +
            "Customer has different currency.<br>" +
            "Use Direct Sales Invoice for multi-currency.",
            "Currency Mismatch",
            {
              "timeOut": "4000",
              "extendedTimeOut": "1000",
              "closeButton": true,
              "progressBar": false
            }
          );
          failed.currentTime = 0;
          failed.play();
          return;
      }
  }


//RETRIVE ALL DYNAMIC HTML VALUES
  var tot_qty=$(".tot_qty").text();
  var tot_amt=$(".tot_amt").text();
  var tot_disc=$(".tot_disc").text();
  var tot_grand=$(".tot_grand").text();

  var paid_amt=(pay_all) ? tot_grand : $(".sales_div_tot_paid").text();
  var balance=(pay_all) ? 0 : parseFloat($(".sales_div_tot_balance").text());


 /* var paid_amt=$(".sales_div_tot_paid").text();
  var balance=parseFloat($(".sales_div_tot_balance").text());*/
  //var walk_in_customer_name=$("#walk_in_customer_name").text();
  var customer_id=$("#customer_id").val();

  /* walk_in_customer_name defined in pos.php */
  if($('option:selected', "#customer_id").attr('data-delete_bit')==1 && balance!=0){
    toastr["warning"]("Walk-in Customer Should Pay Complete Amount!!");
  return;
  }
  if(document.getElementById("sales_id")){
    var command = 'update';
  }
  else{
    var command = 'save';
  }
  var this_btn='make_sale';

//swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
     // if(sure) {//confirmation start

  
$("#"+this_btn).attr('disabled',true);  //Enable Save or Update button
//e.preventDefault();
var data = new Array(2);
data= new FormData($('#pos-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>');
$.ajax({
  type: 'POST',
  url: base_url+'pos/pos_save_update?command='+command+'&tot_qty='+tot_qty+'&tot_amt='+tot_amt+'&tot_disc='+tot_disc+'&tot_grand='+tot_grand+"&paid_amt="+paid_amt+'&balance='+balance+"&pay_all="+pay_all,
  data: data,
  cache: false,
  contentType: false,
  processData: false,
  timeout: 30000, // 30 seconds timeout - gives local database time to respond even without internet
    success: function(result){
      //alert(result);//return;

      result=result.split("<<<###>>>");
      
        if(result[0]=="success")
        {
                toastr['success']("Record Saved Successfully!!");
                success.currentTime = 0;
                success.play();
          var warehouse_id=$("#warehouse_id").val();
          var print_done=true;
          if(print){
            var print_done =window.open(base_url+"pos/print_invoice_pos/"+result[1], "_blank", "scrollbars=1,resizable=1,height=300,width=450");
          }
          if(print_done){
            if(command=='update'){
              window.location=base_url+"sales";		
            }
            else{
              $(".items_table > tbody").empty();
              $(".discount_input").val(0);

              /**
               * Note:
               * Uncheck the advance checkbox
               * Add this code before hiding modal
               */
              uncheck_allow_tot_advance();
              

              $('#multiple-payments-modal').modal('hide');
              var rc=$("#payment_row_count").val();
              while(rc>1){
                remove_row(rc);
                rc--;
              }
              $("#pos-form")[0].reset();

              //$("#customer_id").val(customer_id).select2();

              //console.log("result[4]="+result[4]);
              $("#customer_id").find(':selected').attr('data-tot_advance',to_Fixed(result[4])).trigger('change');
              



              $("#search_it").val('');
              
              /*if warehouse enabled*/
              if(warehouse_module){
                $("#warehouse_id").val(warehouse_id).select2();	
              }

              
              final_total();
              get_details(null,true);
                      hold_invoice_list();
                      get_coupon_details();
              //window.location=base_url+"pos";		
            }
            
          }
          $("#init_code").val(result[2]);
          $("#count_id").val(result[3]);
          
        }
        else if(result[0]=="failed")
        {
           toastr['error']("Sorry! Failed to save Record.Try again");
        }
        else
        {
          // Handle error responses with toast notifications
          var errorMessage = result;
          
          // Ensure errorMessage is a string
          if (typeof errorMessage !== 'string') {
            errorMessage = String(errorMessage);
          }
          
          // Clean up HTML tags if any
          errorMessage = errorMessage.replace(/<[^>]*>/g, '');
          errorMessage = errorMessage.replace(/\s+/g, ' ').trim();
          
          // Handle specific error patterns
          if (errorMessage.includes('Payble amount should not be exceeds Invoice Amount')) {
            errorMessage = 'ERROR: Payable amount exceeds invoice amount! Please check your payment amounts.';
          } else if (errorMessage.includes('batch_required:')) {
            errorMessage = errorMessage.replace('batch_required:', 'BATCH REQUIRED - CANNOT PROCEED:');
          }
          
          toastr['error'](errorMessage);
        }
      
      $("#"+this_btn).attr('disabled',false);  //Enable Save or Update button
      $(".overlay").remove();
     },
         error: function(xhr, status, error) {
      // Handle AJAX errors (network issues)
      console.log('AJAX Error:', status, error, xhr);
      
      // Check if this is a local installation
      var isLocalInstallation = window.location.hostname === 'localhost' || 
                               window.location.hostname === '127.0.0.1' || 
                               window.location.hostname.startsWith('192.168.') ||
                               window.location.hostname === '::1';
      
      // Handle timeout errors
      if (status === 'timeout') {
        $(".overlay").remove();
        $("#"+this_btn).attr('disabled',false);
        if (isLocalInstallation) {
          toastr['error']("Server timeout. Please check if Apache/MySQL is running.");
        } else {
          toastr['error']("Request timed out. The server may be slow or unreachable.");
        }
        return;
      }
      
      // Only queue if:
      // 1. User is offline (no internet)
      // 2. Request actually failed (not local server)
      // 3. OfflineSyncManager exists
      if (status === 'error' && !navigator.onLine && !isLocalInstallation && typeof window.OfflineSyncManager !== 'undefined') {
        console.log('User offline and server unreachable - queueing transaction');
        
        // Get base_url in this scope
        var base_url = $("#base_url").val();
        
        // Ensure base_url ends with / 
        if (base_url && !base_url.endsWith('/')) {
          base_url += '/';
        }
        
        console.log('DEBUG: base_url value:', base_url);
        
          // Remove overlay immediately for offline queueing
          $(".overlay").remove();
          
          // Enable button
          $("#"+this_btn).attr('disabled',false);
          
          console.log('Offline detected, queueing transaction...');
          
          // Capture form data as object
          var formData = {};
          var form = $('#pos-form')[0];
          var formArray = $(form).serializeArray();
          
          // Convert to object
          $.each(formArray, function(i, field) {
            formData[field.name] = field.value;
          });
          
          // Add computed values
          formData['command'] = command;
          formData['tot_qty'] = tot_qty;
          formData['tot_amt'] = tot_amt;
          formData['tot_disc'] = tot_disc;
          formData['tot_grand'] = tot_grand;
          formData['paid_amt'] = paid_amt;
          formData['balance'] = balance;
          formData['pay_all'] = pay_all;
          
          // Log batch information to verify it's captured
          console.log('Capturing offline transaction. Form fields count:', formArray.length);
          var batchFields = Object.keys(formData).filter(k => k.includes('batch') || k.includes('manufacturing') || k.includes('expiry'));
          console.log('Batch-related fields captured:', batchFields);
          
          // Log if there are items with batch tracking enabled
          var hasBatchTracking = false;
          var hiddenRowcount = parseInt(formData.hidden_rowcount) || 0;
          for (var i = 0; i < hiddenRowcount; i++) {
            var batchNum = formData['batch_number_' + i];
            if (batchNum && batchNum.trim() !== '') {
              hasBatchTracking = true;
              console.log('Found batch data for row', i, ':', batchNum);
            }
          }
          if (hasBatchTracking) {
            console.log('Transaction includes batch tracked items. Batch data will be preserved.');
          }
          
        // Build URL with query parameters (same as original AJAX call)
        // Ensure base_url is properly set
        // Remove leading slash from endpoint if present since base_url already has it
        var endpoint = 'pos/pos_save_update';
        if (endpoint.startsWith('/')) {
          endpoint = endpoint.substring(1);
        }
        var url = base_url + endpoint + '?command='+command+'&tot_qty='+tot_qty+'&tot_amt='+tot_amt+'&tot_disc='+tot_disc+'&tot_grand='+tot_grand+"&paid_amt="+paid_amt+'&balance='+balance+"&pay_all="+pay_all;
        
        console.log('DEBUG: Final URL for queueing:', url);
        
        var transactionData = {
          type: 'sale',
          url: url,
          data: formData
        };
          
          // Store transaction data for offline printing
          transactionData['print'] = print || false;
          transactionData['timestamp'] = new Date().toISOString();
          
        window.OfflineSyncManager.queueFailedTransaction(transactionData);
        
        // Show SINGLE warning message  
        toastr['warning']("Server unreachable. Transaction queued. Printing receipt...", "Offline Mode", {timeOut: 3000});
        
        // Get all transaction data before cart is cleared
        var itemsData = [];
        $(".items_table tbody tr").each(function() {
          var item_name = $(this).find('td:first').text().replace(/[\r\n]/g, '').trim();
          var qty_input = $(this).find('input[id^="item_qty_"]');
          var price_input = $(this).find('input[id^="sales_price_"]');
          var sub_input = $(this).find('input[id^="td_data_"][id$="_4"]');
          
          if (item_name && item_name !== '') {
            itemsData.push({
              name: item_name,
              qty: qty_input.val() || '1',
              price: price_input.val() || '0',
              total: sub_input.val() || '0'
            });
          }
        });
        
        // Get actual customer name from the select element
        var actual_customer_name = $('#customer_id option:selected').text() || 'Walk-in Customer';
        if (actual_customer_name.includes('Select Customer') || actual_customer_name.includes('Walk-in')) {
          actual_customer_name = 'Walk-in Customer';
        }
        
        // Open receipt using standard format
        var base_url = $("#base_url").val();
        var receiptHTML = createOfflineReceipt(actual_customer_name, itemsData, tot_qty, tot_amt, tot_disc, tot_grand, paid_amt, balance);
        
        var printWindow = window.open('', '_blank', 'width=600,height=800');
        printWindow.document.write(receiptHTML);
        printWindow.document.close();
        
        setTimeout(function() {
          printWindow.print();
        }, 500);
        
        // Clear cart after printing
        setTimeout(function() {
          $(".items_table > tbody").empty();
          $(".discount_input").val(0);
          uncheck_allow_tot_advance();
          var rc=$("#payment_row_count").val();
          while(rc>1){ remove_row(rc); rc--; }
          $("#pos-form")[0].reset();
          final_total();
          get_details(null,true);
          hold_invoice_list();
          get_coupon_details();
          toastr['success']("Cart cleared. Ready for next customer.", "Offline Mode");
        }, 1500);
        
        // Exit error handler after offline queueing
        return;
      }
      
      // For local installations that encounter errors (not offline sync issue)
      if (isLocalInstallation && status === 'error') {
        $(".overlay").remove();
        $("#"+this_btn).attr('disabled',false);
        var errorMsg = 'Failed to save transaction. ';
        if (xhr.status === 0) {
          errorMsg += 'Server appears to be down. Please check Apache and MySQL services.';
        } else if (xhr.status === 500) {
          errorMsg += 'Server error. Please check logs.';
        } else {
          errorMsg += 'Error: ' + status;
        }
        toastr['error'](errorMsg);
        return;
      }
      
      // All other errors - show error and clean up
      $(".overlay").remove();
      $("#"+this_btn).attr('disabled',false);
      toastr['error']("Failed to save transaction. Please check your connection and try again.");
     }
   });
//} //confirmation sure
  //}); //confirmation end

//e.preventDefault


//});
}

/**
* Create offline receipt using exact same format as sal-invoice-pos.php
*/
function createOfflineReceipt(customer_name, items, tot_qty, tot_amt, tot_disc, tot_grand, paid_amt, balance) {
var store_name = $('b.hidden-xs').first().text() || 'Your Store';

// Get invoice number from form (init_code + count_id) like online receipt
var init_code = $('#init_code').val() || '';
var count_id = $('#count_id').val() || '0';
var invoice_num = init_code + count_id;

// If not available, generate a temporary offline number
if (!init_code || count_id === '0') {
  var now = new Date();
  var year = now.getFullYear();
  var counter = Math.floor(Math.random() * 99999) + 1;
  invoice_num = 'TMP-' + year + '-' + String(counter).padStart(5, '0');
}

var current_date = new Date().toLocaleDateString('en-GB');
var current_time = new Date().toLocaleTimeString();

// Try to get store address from session or hidden elements
var store_address = '';
var store_city = '';
var store_postcode = '';
var store_phone = '';
var store_email = '';

// Look for store information in hidden div - get ALL elements with this attribute
var store_info_divs = $('[data-store-address]');
console.log('DEBUG: Total store info divs found:', store_info_divs.length);

// Get the first one that has data
if (store_info_divs.length > 0) {
  var first_div = store_info_divs.first();
  
  // Try both .data() and .attr() methods
  var div_address = first_div.data('store-address');
  var div_city = first_div.data('store-city');
  var div_postcode = first_div.data('store-postcode');
  var div_phone = first_div.data('store-phone');
  var div_email = first_div.data('store-email');
  
  // Fallback to attr if data() returns undefined
  store_address = (div_address !== undefined && div_address !== null && div_address !== '') ? div_address : (first_div.attr('data-store-address') || '');
  store_city = (div_city !== undefined && div_city !== null && div_city !== '') ? div_city : (first_div.attr('data-store-city') || '');
  store_postcode = (div_postcode !== undefined && div_postcode !== null && div_postcode !== '') ? div_postcode : (first_div.attr('data-store-postcode') || '');
  store_phone = (div_phone !== undefined && div_phone !== null && div_phone !== '') ? div_phone : (first_div.attr('data-store-phone') || '');
  store_email = (div_email !== undefined && div_email !== null && div_email !== '') ? div_email : (first_div.attr('data-store-email') || '');
  
  console.log('DEBUG: Store data retrieved -');
  console.log('  Address:', store_address);
  console.log('  City:', store_city);
  console.log('  Postcode:', store_postcode);
  console.log('  Phone:', store_phone);
  console.log('  Email:', store_email);
  console.log('  Full div HTML:', first_div[0] ? first_div[0].outerHTML.substring(0, 500) : 'N/A');
  console.log('  Div visible?', first_div.is(':visible'));
  console.log('  Div display style:', first_div[0] ? window.getComputedStyle(first_div[0]).display : 'N/A');
} else {
  console.log('ERROR: No store info div found with data-store-address attribute!');
  console.log('Searching entire page for any divs:', $('div').length);
  console.log('Searching for hidden divs:', $('div[style*="display: none"]').length);
  console.log('Searching for data-store-address:', $('[data-store-address]').length);
}

var html = '<!DOCTYPE html><html><head><title>Default Invoice Format</title>';
html += '<style type="text/css">';
html += 'body{font-family:arial;font-size:13px;font-weight:bold;margin:0;padding:20px;max-width:100%;}';
html += 'table{width:100%;border-collapse:collapse;word-wrap:break-word;}';
html += '.table-container{width:95%;margin:0 auto;max-width:100%;}';
html += '.no-print{display:none;}';
html += 'td,th{word-wrap:break-word;overflow-wrap:break-word;}';
html += '@media screen and (max-width:600px){body{font-size:11px;padding:10px;}table{font-size:10px;}td,th{padding:2px;font-size:9px;}}';
html += '/* Responsive print styles for different paper sizes */';
html += '@media print{';
html += 'body{margin:0;padding:0;font-size:11px;}';
html += '.table-container{width:100%;margin:0;}';
html += 'table{font-size:10px;}';
html += 'td,th{padding:3px;}';
html += '.no-print{display:none !important;}';
html += '}';
html += '/* A4 size (default) */';
html += '@page{size:A4;margin:1cm;}';
html += '@media print and (min-width: 210mm){';
html += 'body{font-size:11px;}';
html += 'table{font-size:10px;}';
html += 'td,th{padding:3px;}';
html += '}';
html += '/* 80mm thermal printer */';
html += '@media print and (max-width: 85mm){';
html += '@page{size:80mm auto;margin:2mm;}';
html += 'body{margin:0;padding:5px;font-size:9px;}';
html += 'table{font-size:8px;width:100%;}';
html += 'td,th{padding:2px 1px;font-size:8px;}';
html += '.table-container{width:100%;margin:0;}';
html += '}';
html += '/* 58mm thermal printer */';
html += '@media print and (max-width: 63mm){';
html += '@page{size:58mm auto;margin:2mm;}';
html += 'body{margin:0;padding:3px;font-size:8px;}';
html += 'table{font-size:7px;width:100%;}';
html += 'td,th{padding:1px;font-size:7px;}';
html += '.table-container{width:100%;margin:0;}';
html += '}';
html += '</style></head><body>';

html += '<div class="table-container"><table width="100%">';
html += '<tr><td align="center"><strong>' + store_name + '</strong></td></tr>';

// Add store address if available (debug mode - always show at least header)
html += '<tr><td align="center">';
var address_shown = false;

if (store_address) {
  html += store_address + '<br>';
  address_shown = true;
}
if (store_city) {
  html += store_city;
  if (store_postcode) html += '-' + store_postcode;
  html += '<br>';
  address_shown = true;
}
if (store_phone) {
  html += store_phone + '<br>';
  address_shown = true;
}
if (store_email) {
  html += store_email + '<br>';
  address_shown = true;
}

// If no store info found, show debug message
if (!address_shown) {
  console.log('WARNING: No store address information found in page');
}

html += '</td></tr>';

html += '<tr><td align="center"><strong>-----------------Invoice-----------------</strong></td></tr>';
html += '<tr><td><table width="100%">';
html += '<tr><td width="40%">Invoice</td><td><b>#' + invoice_num + '</b></td></tr>';
html += '<tr><td>Name</td><td>' + customer_name + '</td></tr>';
html += '<tr><td>Date</td><td>' + current_date + '</td></tr>';
html += '<tr><td>Time</td><td style="text-align:right;">' + current_time + '</td></tr>';
html += '</table></td></tr>';

html += '<tr><td><table width="100%" cellpadding="0" cellspacing="0"><thead>';
html += '<tr style="border-top-style:dashed;border-bottom-style:dashed;border-width:0.1px;">';
html += '<th style="font-size:11px;text-align:left;padding-left:2px;padding-right:2px;">#</th>';
html += '<th style="font-size:11px;text-align:left;padding-left:2px;padding-right:2px;">Description</th>';
html += '<th style="font-size:11px;text-align:center;padding-left:2px;padding-right:2px;">Quantity</th>';
html += '<th style="font-size:11px;text-align:right;padding-left:2px;padding-right:2px;">Rate</th>';
html += '<th style="font-size:11px;text-align:right;padding-left:2px;padding-right:2px;">Total</th>';
html += '</tr></thead><tbody style="border-bottom-style:dashed;border-width:0.1px;">';

for (var i = 0; i < items.length; i++) {
  html += '<tr>';
  html += '<td style="padding-left:2px;padding-right:2px;" valign="top">' + (i + 1) + '</td>';
  html += '<td style="padding-left:2px;padding-right:2px;">' + items[i].name + '</td>';
  html += '<td style="text-align:center;padding-left:2px;padding-right:2px;">' + items[i].qty + '</td>';
  html += '<td style="text-align:right;padding-left:2px;padding-right:2px;">' + items[i].price + '</td>';
  html += '<td style="text-align:right;padding-left:2px;padding-right:2px;">' + items[i].total + '</td>';
  html += '</tr>';
}

html += '</tbody><tfoot>';
html += '<tr><td style="padding-left:2px;padding-right:2px;" colspan="4" align="right">Total</td><td style="padding-left:2px;padding-right:2px;" align="right">' + tot_grand + '</td></tr>';
html += '<tr><td style="padding-left:2px;padding-right:2px;" colspan="4" align="right">Paid Amount</td><td style="padding-left:2px;padding-right:2px;" align="right">' + paid_amt + '</td></tr>';
if (parseFloat(balance) > 0) {
  html += '<tr><td style="padding-left:2px;padding-right:2px;" colspan="4" align="right">Balance</td><td style="padding-left:2px;padding-right:2px;" align="right">' + balance + '</td></tr>';
}
html += '</tfoot></table></td></tr>';
html += '<tr><td colspan="5" align="center">----------Thanks you visit again----------</td></tr>';
html += '</table></div>';
html += '<center class="no-print"><button onclick="window.print();" class="btn btn-success btn-xs">Print</button></center>';
html += '</body></html>';

return html;
}


/* *********************** HOLD INVOICE START****************************/
$('#hold_invoice').on("click",function (e) {

//table should not be empty
if($(".items_table tr").length==1){
    toastr["error"]("Please Select Items from List!!");
    failed.currentTime = 0;
  failed.play();
  return;
  }

swal({
  title: "Hold Invoice ? Same Reference will replace the old list if exist!!",icon: "warning",buttons: true,dangerMode: true,
  content: {
    element: "input",attributes: 
    {
      placeholder: "Please Enter Reference Number!",
      type: "text",
      
      inputAttributes: {
          maxlength: '5'
        }
    },},
  }).then(name => {
    //If input box blank Throw Error
    if (!name){ throw null; return false; }
    var reference_id = name;
    /* ********************************************************** */
    var base_url=$("#base_url").val();
  
    //RETRIVE ALL DYNAMIC HTML VALUES
      var tot_qty=$(".tot_qty").text();
      var tot_amt=$(".tot_amt").text();
      var tot_disc=$(".tot_disc").text();
      var tot_grand=$(".tot_grand").text();
      var hidden_rowcount=$("#hidden_rowcount").val();

      var this_id=this.id;//id=save or id=update

      e.preventDefault();
      data = new FormData($('#pos-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+'pos/hold_invoice?command='+this_id+'&tot_qty='+tot_qty+'&tot_amt='+tot_amt+'&tot_disc='+tot_disc+'&tot_grand='+tot_grand+"&reference_id="+reference_id,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(result){
          //alert(result);return;
          $("#hidden_invoice_id").val('');
          result=result.split("<<<###>>>");
          
            if(result[0]=="success")
            {
              $('#pos-form-tbody').html('');
              //CALCULATE FINAL TOTAL AND OTHER OPERATIONS
                final_total();

              hold_invoice_list();
              success.currentTime = 0;
              success.play();
            }
            else if(result[0]=="failed")
            {
               toastr['error']("Sorry! Failed to save Record.Try again");
            }
            else
            {
              // Handle error responses with toast notifications
              var errorMessage = result;
              
              // Clean up HTML tags if any
              errorMessage = errorMessage.replace(/<[^>]*>/g, '');
              errorMessage = errorMessage.replace(/\s+/g, ' ').trim();
              
              // Handle specific error patterns
              if (errorMessage.includes('Payble amount should not be exceeds Invoice Amount')) {
                errorMessage = 'ERROR: Payable amount exceeds invoice amount! Please check your payment amounts.';
              } else if (errorMessage.includes('batch_required:')) {
                errorMessage = errorMessage.replace('batch_required:', 'BATCH REQUIRED - CANNOT PROCEED:');
              }
              
              toastr['error'](errorMessage);
            }
          
          $("#"+this_id).attr('disabled',false);  //Enable Save or Update button
          $(".overlay").remove();
         }
       });
    /* ********************************************************** */

  }) //name end
.catch(err => {
    toastr['error']("Failed!! Invoice Not Saved! <br/>Please Enter Reference Number");
    failed.currentTime = 0;
  failed.play();
});//swal end

}); //hold_invoice end

function hold_invoice_list(){
var base_url=$("#base_url").val();
$.post(base_url+"pos/hold_invoice_list",{},function(result){
  //alert(result);
  var data = jQuery.parseJSON(result)
  $("#hold_invoice_list").html('').html(data['result']);
  $(".hold_invoice_list_count").html('').html(data['tot_count']);
});
}
function hold_invoice_delete(invoice_id){
swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
if(sure) {//confirmation start
var base_url=$("#base_url").val();
$.post(base_url+"pos/hold_invoice_delete/"+invoice_id,{},function(result){
  result=result;
  if(result=='success'){
    toastr["success"]("Success! Invoice Deleted!!");
    success.currentTime = 0;
  success.play();
    hold_invoice_list();
  }
  else{
    toastr['error']("Failed to Delete Invoice! Try again!!");
    failed.currentTime = 0;
  failed.play();
  }
});
} //confirmation sure
  }); //confirmation end
}

function hold_invoice_edit(id){

swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
if(sure) {//confirmation start
var base_url=$("#base_url").val();

$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
$.post(base_url+"pos/hold_invoice_edit",{hold_id:id},function(result){


    result=result.split("<<<###>>>");
    $('#pos-form-tbody').html('').append(result[0]);
    $('#discount_input').val(result[1]);
    $('#discount_type').val(result[2]);
    /*if(store_module){
      $('#store_id').val(result[4]).select2();
    }
    else{*/
      $('#store_id').val(result[4]);
    /*}*/
    if(warehouse_module){
      $('#warehouse_id').val(result[5]).select2();
    }
    else{
      $('#warehouse_id').val(result[5]);
    }

    //$('#customer_id').val(result[3]).select2();
    //$("#customer_id").trigger("change");
    
    //$('#temp_customer_id').val(result[3]);

    autoLoadFirstCustomer(result[3]);
    //$('#customer_id').val(result[3]).select2();
    $("#hidden_invoice_id").val(result[7]);
    $("#hidden_rowcount").val(parseInt($(".items_table tr").length)-1);
    final_total();
    get_details(null,true);
    $(".overlay").remove();
    
    if(result[5]==1){
      $( "#binvoice" ).prop( "checked", true );
      $('#binvoice').parent('div').addClass('checked');
    }
    });

      
  } //confirmation sure
}); //confirmation end
}
/* *********************** HOLD INVOICE END****************************/
/* *********************** ORDER INVOICE START****************************/
function get_id_value(id){
return $("#"+id).val();
}
$('#collect_customer_info').on("click",function (e) {

//table should not be empty
if($(".items_table tr").length==1){
    toastr["error"]("Please Select Items from List!!");
    failed.currentTime = 0;
  failed.play();
  return;
  }
  if(get_id_value('customer_id')==1){
    //$('#customer-modal').modal('toggle');
    toastr["error"]("Please Select Customer!!");
    failed.currentTime = 0;
  failed.play();
    return false;
  }
  else{
    $('#delivery-info').modal('toggle');
  }
}); //hold_invoice end
$('.show_payments_modal').on("click",function (e) {

//table should not be empty
if($(".items_table tr").length==1){
    toastr["error"]("Please Select Items from List!!");
    failed.currentTime = 0;
  failed.play();
  return;
  }
  else{
    adjust_payments();
    $("#add_payment_row,#payment_type_1").parent().show();
    $("#amount_1").parent().parent().removeClass('col-md-12').addClass('col-md-6');
    $('#multiple-payments-modal').modal('toggle');
  }
}); //hold_invoice end
$('#show_cash_modal').on("click",function (e) {
//table should not be empty
if($(".items_table tr").length==1){
    toastr["error"]("Please Select Items from List!!");
    failed.currentTime = 0;
  failed.play();
  return;
  }
  else{
    adjust_payments();
    $("#add_payment_row,#payment_type_1").parent().hide();
    $("#amount_1").focus();
    $("#amount_1").parent().parent().removeClass('col-md-6').addClass('col-md-12');
    $('#multiple-payments-modal').modal('toggle');
  }
}); //hold_invoice end

$('#add_payment_row').on("click",function (e) {

var base_url=$("#base_url").val();
//table should not be empty
if($(".items_table tr").length==1){
    toastr["error"]("Please Select Items from List!!");
    failed.currentTime = 0;
  failed.play();
  return;
  }
  /*if(get_id_value('customer_id')==1){
    //$('#customer-modal').modal('toggle');
    toastr["error"]("Please Select Customer!!");
    failed.currentTime = 0;
failed.play();
    return false;
  }*/
  else{
    /*BUTTON LOAD AND DISABLE START*/
    var this_id=this.id;
    var this_val=$(this).html();
    $("#"+this_id).html('<i class="fa fa-spinner fa-spin"></i> Please Wait..');
    $("#"+this_id).attr('disabled',true);  
    /*BUTTON LOAD AND DISABLE END*/

    var payment_row_count=get_id_value("payment_row_count");
    $.post(base_url+"pos/add_payment_row",{payment_row_count:payment_row_count},function(result){
      $('.payments_div').parent().append(result);
      $("#payment_row_count").val(parseInt(payment_row_count)+1);

      /*BUTTON LOAD AND DISABLE START*/
      $("#"+this_id).html(this_val);
      $("#"+this_id).attr('disabled',false); 
      /*BUTTON LOAD AND DISABLE END*/    	
      failed.currentTime = 0;
    failed.play();
      adjust_payments();
    });
  }
}); //hold_invoice end
function remove_row(id){
$(".payments_div_"+id).html('');
failed.currentTime = 0;
failed.play();
adjust_payments();
}
function calculate_payments(){
adjust_payments();
}

function get_item_details(item_id){
var base_url=$("#base_url").val();
var warehouse_id=$("#warehouse_id").val();
var customer_id=$("#customer_id").val();

$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
$.post(base_url+"pos/get_item_details",{item_id:item_id,warehouse_id:warehouse_id,customer_id:customer_id},function(result){
  var item = jQuery.parseJSON(result);

  var obj = {};
  obj['item_id']        = item['id'];
  obj['item_name']      = item['item_name'];
  obj['stock']          = item['stock'];
  obj['sales_price']    = item['sales_price'];
  obj['purchase_price'] = item['purchase_price'];
  obj['tax_id']         = item['tax_id'];
  obj['tax_type']       = item['tax_type'];
  obj['tax']            = item['tax'];
  obj['tax_name']       = item['tax_name'];
  obj['item_tax_amt']   = item['item_tax_amt'];
  obj['discount_type']  = item['discount_type'];
  obj['discount']       = item['discount'];
  obj['service_bit']    = item['service_bit'];
  obj['batch_tracking_enabled'] = item['batch_tracking_enabled'];
  obj['tracking_type']  = item['tracking_type'];
  addrow(null,obj);
  $(".overlay").remove();
});

}

// Function to refresh existing items with customer-specific pricing
function refresh_existing_items_with_customer_pricing(){
var customer_id = $("#customer_id").val();
var warehouse_id = $("#warehouse_id").val();
var base_url = $("#base_url").val();

// Only proceed if customer is selected and not walk-in
if (!customer_id || customer_id === '' || customer_id === '1') {
  return;
}

// Get all existing items in the table
var existingItems = [];
$(".items_table tbody tr").each(function() {
  var itemId = $(this).find('input[id^="tr_item_id_"]').val();
  var qty = $(this).find('input[id^="td_data_"][id$="_3"]').val();
  
  if (itemId && qty) {
    existingItems.push({
      item_id: itemId,
      qty: qty,
      row: $(this)
    });
  }
});

if (existingItems.length === 0) {
  return;
}

// Show loading indicator
$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');

// Process each item
var processedCount = 0;
var totalItems = existingItems.length;

existingItems.forEach(function(item) {
  $.post(base_url + "pos/get_item_details", {
    item_id: item.item_id,
    warehouse_id: warehouse_id,
    customer_id: customer_id
  }, function(result) {
    try {
      var itemData = jQuery.parseJSON(result);
      
      // Update the price in the existing row
      var priceInput = item.row.find('input[id^="td_data_"][id$="_10"]');
      var priceHiddenInput = item.row.find('input[id^="td_data_"][id$="_4"]');
      
      if (priceInput.length && priceHiddenInput.length) {
        var newPrice = parseFloat(itemData.sales_price);
        var formattedPrice = newPrice.toFixed(2);
        
        // Update the displayed price
        priceInput.val(formattedPrice);
        priceHiddenInput.val(newPrice);
        
        
        // Recalculate totals for this row
        var rowIndex = item.row.attr('data-row');
        if (rowIndex) {
          calculate_tax(rowIndex);
        }
      }
      
      processedCount++;
      
      // If all items processed, remove loading and recalculate totals
      if (processedCount === totalItems) {
        $(".overlay").remove();
        final_total();
      }
    } catch (e) {
      processedCount++;
      
      if (processedCount === totalItems) {
        $(".overlay").remove();
        final_total();
      }
    }
  }).fail(function() {
    processedCount++;
    
    if (processedCount === totalItems) {
      $(".overlay").remove();
      final_total();
    }
  });
});
}

/* *********************** ORDER INVOICE END****************************/

/**
* Check account for Pay All functionality
*/
function check_pay_all_account() {
var base_url = $("#base_url").val();

// Check if this is a local installation (localhost, 192.168.x.x, etc.)
var isLocalInstallation = window.location.hostname === 'localhost' || 
                         window.location.hostname === '127.0.0.1' || 
                         window.location.hostname.startsWith('192.168.') ||
                         window.location.hostname === '::1';

// If offline (user lost internet), try to save anyway - server might still be reachable
// Don't preemptively queue - let the AJAX call succeed or fail naturally
if (!navigator.onLine) {
  console.log('User offline - attempting to save to server anyway (server may be reachable)');
  // Don't show any toast here - let the save() function handle success/failure
  save(print=true, pay_all=true);
  return;
}

// Show loading state
$("#pay_all").prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Checking...');

$.ajax({
  url: base_url + 'pos/get_pay_all_account_info',
  type: 'POST',
  dataType: 'json',
  timeout: 5000, // 5 second timeout
  success: function(response) {
    $("#pay_all").prop('disabled', false).html('<i class="fa fa-money" aria-hidden="true"></i> Pay All');
    
    if (response.success) {
      // Account is valid, proceed with Pay All
      save(print=true, pay_all=true);
    } else if (response.needs_selection) {
      // Show account selection modal
      show_pay_all_account_modal(response);
    } else {
      // Show error message
      toastr["error"](response.message || "Unable to process Pay All. Please try again.");
    }
  },
  error: function(xhr, status, error) {
    $("#pay_all").prop('disabled', false).html('<i class="fa fa-money" aria-hidden="true"></i> Pay All');
    
    // If we're truly offline or timeout occurred, proceed with save anyway
    // The save function will handle offline queuing
    if (status === 'timeout' || status === 'error' || error === 'Network Error') {
      console.log('Server unreachable or timeout: Proceeding with save (will queue if offline)');
      toastr['warning']("Unable to verify account. Proceeding with transaction...");
      save(print=true, pay_all=true);
    } else {
      toastr["error"]("Unable to check account information. Please try again.");
    }
  }
});
}

/**
* Show account selection modal for Pay All
*/
function show_pay_all_account_modal(accountInfo) {
var modalHtml = '<div class="modal fade" id="pay_all_account_modal" tabindex="-1" role="dialog">';
modalHtml += '<div class="modal-dialog" role="document">';
modalHtml += '<div class="modal-content">';
modalHtml += '<div class="modal-header">';
modalHtml += '<h4 class="modal-title">Select Account for Pay All</h4>';
modalHtml += '</div>';
modalHtml += '<div class="modal-body">';
modalHtml += '<div class="alert alert-info">';
modalHtml += '<i class="fa fa-info-circle"></i> ' + accountInfo.message;
modalHtml += '</div>';
modalHtml += '<div class="form-group">';
modalHtml += '<label for="pay_all_account_select">Select Base Currency Account:</label>';
modalHtml += '<select class="form-control" id="pay_all_account_select">';
modalHtml += '<option value="">-- Select Account --</option>';

if (accountInfo.available_accounts && accountInfo.available_accounts.length > 0) {
  $.each(accountInfo.available_accounts, function(index, account) {
    modalHtml += '<option value="' + account.id + '">' + account.account_name + ' (' + account.currency_code + ')</option>';
  });
}

modalHtml += '</select>';
modalHtml += '</div>';
modalHtml += '</div>';
modalHtml += '<div class="modal-footer">';
modalHtml += '<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>';
modalHtml += '<button type="button" class="btn btn-primary" id="confirm_pay_all_account">Confirm & Pay All</button>';
modalHtml += '</div>';
modalHtml += '</div>';
modalHtml += '</div>';
modalHtml += '</div>';

// Remove existing modal if any
$("#pay_all_account_modal").remove();

// Add modal to body
$("body").append(modalHtml);

// Show modal
$("#pay_all_account_modal").modal('show');

// Handle confirm button click
$("#confirm_pay_all_account").on("click", function() {
  var selectedAccountId = $("#pay_all_account_select").val();
  
  if (!selectedAccountId) {
    toastr["warning"]("Please select an account.");
    return;
  }
  
  // Store selected account in session for this Pay All operation
  $.ajax({
    url: base_url + 'pos/set_pay_all_account',
    type: 'POST',
    data: { account_id: selectedAccountId },
    dataType: 'json',
    success: function(response) {
      if (response.success) {
        $("#pay_all_account_modal").modal('hide');
        // Proceed with Pay All
        save(print=true, pay_all=true);
      } else {
        toastr["error"](response.message || "Failed to set account. Please try again.");
      }
    },
    error: function() {
      toastr["error"]("Unable to set account. Please try again.");
    }
  });
});
}

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



$("#item_search").autocomplete({
minLength: 0,
  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:"sales",
          },
          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 +'--[Qty:'+el.stock+'] --'+ el.label,
                          value: '',
                          id: el.id,
                          item_name: el.value,
                          stock: el.stock,
                          service_bit: el.service_bit,
                         // 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) { 
          
          
         
          if(typeof ui.content!='undefined'){
            if(isNaN(ui.content[0].id)){
              return;
            }
            var stock=ui.content[0].stock;
            var item_id=ui.content[0].id;
            var service_bit=ui.content[0].service_bit;
          }
          else{
            var stock=ui.item.stock;
            var item_id=ui.item.id;
            var service_bit=ui.item.service_bit;
          }
          if(service_bit==0 && parseFloat(stock)<=0){
            toastr["warning"]("Out of Stock! Available: " + stock, "Stock Issue");
            failed.currentTime = 0; 
            failed.play();
            return false;
          }

         /* if(service_bit==1){
            return_row_with_data(item_id);  
          }
          else {
            if(restrict_quantity(item_id)){
              return_row_with_data(item_id);  
            }
          }*/
          //addrow(item_id);
          get_item_details(item_id);
          $("#item_search").val('');
          
          
      },   
      //loader end
});


function set_previous_due(previous_due,tot_advance){
$(".customer_previous_due").html(previous_due);
$(".customer_tot_advance").html(tot_advance);

// Check currency when customer is selected (use the same debounced function)
check_customer_currency_for_pos();
}



function get_coupon_details(){
var input_box = $("#coupon_code");
var coupon_code = $.trim(input_box.val());
var customer_id = $("#customer_id").val();
var base_url=$("#base_url").val();

var coupon_type='';
var coupon_value=0;
if(coupon_code!=''){
  input_box.addClass('ui-autocomplete-loading');
  $.post(base_url+'customer_coupon/get_coupon_details', {invoice_type:'sales',coupon_code: coupon_code,customer_id:customer_id}, function(data, textStatus, xhr) {
    var json = $.parseJSON(data);
    coupon_value=json.coupon_value;
    coupon_type=json.coupon_type;

    

    $(".coupon_value").html(to_Fixed(coupon_value));
    $(".coupon_type").html(coupon_type);  

    $(".div1,.div2").removeClass('hide');
    
    if(json.expire_status=='Valid'){
      $(".msg_color").removeClass('alert-warning').addClass('alert-success');
    }
    else{
     $(".msg_color").removeClass('alert-success').addClass('alert-warning');
     $(".div2").addClass('hide');
    }
    $("#coupon_code_msg").text(json.message);

    input_box.removeClass('ui-autocomplete-loading');

    final_total();
    adjust_payments();
  });
}else{
  $(".div1, .div2").addClass('hide');
  $(".coupon_value").html(to_Fixed(coupon_value));
  $(".coupon_type").html(coupon_type);  
  final_total();
  adjust_payments();
}  
}


$("#customer_id").on("change select2:select", function() {
// Add small delay to ensure Select2 has fully processed the selection
setTimeout(function() {
  check_customer_currency_for_pos();
  // Refresh existing items with customer-specific pricing
  refresh_existing_items_with_customer_pricing();
}, 100);
});

$("#coupon_code").on("change",function() {
get_coupon_details();
});
$('#coupon_code').keypress(function (e) {
var key = e.which;
// the enter key code
if(key == 13){
  get_coupon_details();  
}
}); 

// Track last checked customer to prevent duplicate messages
var last_checked_customer_id = null;
var currency_check_timeout = null;

// Check if customer has different currency than base currency for POS
function check_customer_currency_for_pos() {
var customer_id = $("#customer_id").val();
var base_url = $("#base_url").val();

// Skip if same customer was already checked
if (customer_id === last_checked_customer_id) {
  return;
}

// Clear any existing timeout
if (currency_check_timeout) {
  clearTimeout(currency_check_timeout);
}

// Add small delay to prevent rapid-fire checks
currency_check_timeout = setTimeout(function() {
  // Update last checked customer
  last_checked_customer_id = customer_id;
  
  // Hide currency info and customer type initially
  $("#customer_currency_info").hide();
  $("#walkin_currency_info").hide();
  $("#customer_type_info").hide();
  
  // Check if it's a walk-in customer (ID 1 or contains "walk-in" in text)
  var customerText = $("#customer_id option:selected").text();
  if (customer_id === '1' || customerText.toLowerCase().includes('walk-in')) {
    
    // Get base currency info from the page data
    var baseCurrency = window.baseCurrencyName || 'Base Currency';
    var baseCode = window.baseCurrencyCode || 'USD';
    var baseSymbol = window.baseCurrencySymbol || '$';
    
    $("#walkin_currency_display").text(baseCurrency + " (" + baseCode + ")");
    $("#walkin_currency_info").show();
    
    // Update currency symbols
    $(".currency_symbol").text(baseSymbol);
    
    return;
  }
  
  if (customer_id && customer_id !== '' && customer_id !== '1') {
    
    // Make AJAX call to get customer type
    $.ajax({
      url: base_url + 'pos/get_customer_type',
      type: 'POST',
      data: { customer_id: customer_id },
      dataType: 'json',
      success: function(type_response) {
        if (type_response.status) {
          // Show customer type info
          var customer_type_text = type_response.customer_type.charAt(0).toUpperCase() + type_response.customer_type.slice(1);
          $("#customer_type_text").text(customer_type_text);
          $("#customer_type_info").show();
          
          // Store customer type for price selection
          window.currentCustomerType = type_response.customer_type;
          window.currentPriceType = type_response.default_price_type;
        }
      }
    });
    
    // Make AJAX call to check customer currency
    $.ajax({
      url: base_url + 'customers/get_customer_currency',
      type: 'POST',
      data: { customer_id: customer_id },
      dataType: 'json',
      success: function(currency_response) {
        
        if (currency_response.status) {
          // Show customer currency info
          var customer_currency_text = '';
          if (currency_response.customer_currency_name && currency_response.customer_currency_code) {
            customer_currency_text = currency_response.customer_currency_name + ' (' + currency_response.customer_currency_code + ')';
          } else {
            customer_currency_text = currency_response.currency_name + ' (' + currency_response.currency_code + ')';
          }
          
          $("#customer_currency_display").text(customer_currency_text);
          $("#customer_currency_info").show();
          
          // Check if customer currency is different from base currency
          if (currency_response.customer_currency_id && 
              currency_response.customer_currency_id != currency_response.base_currency_id) {
            
            // Show concise error message
            var customer_currency_text = currency_response.customer_currency_name + ' (' + currency_response.customer_currency_code + ')';
            var base_currency_text = currency_response.base_currency_name + ' (' + currency_response.base_currency_code + ')';
            
            toastr["error"](
              "Multi-Currency Not Allowed in POS!<br>" +
              "Customer: " + customer_currency_text + "<br>" +
              "System: " + base_currency_text + "<br>" +
              "Use Direct Sales 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 customer loading
            setTimeout(function() {
              
              // Show loading message before reload
              toastr["info"]("Reloading POS to load default walk-in customer...", "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 {
            // Customer has same currency as base - no need to show success message every time
            // Just show currency info, no toast message
          }
        }
      },
      error: function(xhr, status, error) {
        toastr["warning"]("Unable to verify customer currency. Please try again.");
      }
    });
  } else {
    // Walk-in customer selected - hide currency info
    $("#customer_currency_info").hide();
  }
}, 300); // 300ms delay
} 

/*Calculate Coupon Discount Amount*/
const discount_coupon_tot = function(subtotal) {
   var coupon_value=parseFloat($(".coupon_value").html());
       coupon_value = isNaN(coupon_value) ? 0 : coupon_value;

   var coupon_type=$(".coupon_type").html();

   var discount_amt =0;
   if(coupon_type!='' && coupon_value>0){

       if(coupon_type=='Percentage'){
           discount_amt=(subtotal*coupon_value)/100;
       }
       else{//Fixed
           discount_amt=coupon_value;
       }
   }
   return discount_amt;
}

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

// Function to update mobile cart badge
function updateMobileCartBadge() {
  if (window.innerWidth < 992) {
      var itemCount = $('.items_table tbody tr').length;
      $('.cart-item-count').text(itemCount);
  }
}

// Update cart badge whenever items are added or removed
$(document).ready(function() {
  // Initial update
  updateMobileCartBadge();
  
  // Watch for changes in cart items
  var observer = new MutationObserver(function() {
      updateMobileCartBadge();
  });
  
  var cartTable = document.querySelector('.items_table tbody');
  if (cartTable) {
      observer.observe(cartTable, { childList: true, subtree: true });
  }
});


