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

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

}
var SCAN_LOCK_UI = false;
var USER_TYPING = false; // prevents focus stealing while user is typing
var LAST_INPUT_TIME = 0; // 🔥 track last typing time
// ✅ Track if user is actively focused on ANY input
var USER_FOCUSED_INPUT = false;
var FORCE_SCAN_FOCUS = true;

$(document).on('focus', 'input, textarea', function () {
  USER_FOCUSED_INPUT = true;
  FORCE_SCAN_FOCUS = false; // 🔥 STOP scanner override
});

$(document).on('blur', 'input, textarea', function () {
  setTimeout(function () {
    USER_FOCUSED_INPUT = false;

    // 🔥 Re-enable scanner ONLY if nothing else focused
    if (!USER_FOCUSED_INPUT) {
      FORCE_SCAN_FOCUS = true;
    }
  }, 200);
});
/*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();
});

/**
 * Build and print receipt from current cart (same format as online). Call before clearing the cart.
 * paidAmtOverride: use when saving offline with Pay All or known paid amount (so receipt shows correct Paid / Paid in full).
 */
function printOfflineReceipt(paidAmtOverride) {
  var items = [];
  $('#pos-form-tbody tr[id^="row_"]').each(function() {
    var id = this.id, i = id.replace('row_', '');
    if (i === '' || isNaN(parseInt(i, 10))) return;
    i = parseInt(i, 10);
    var nameEl = $("#td_data_"+i+"_0");
    var name = (nameEl.length ? nameEl.text().trim() : '').replace(/\s+/g, ' ').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    var qty = parseFormattedNumber($("#item_qty_"+i).val()) || 0;
    var price = parseFormattedNumber($("#sales_price_"+i).val()) || 0;
    var subtotal = parseFormattedNumber($("#td_data_"+i+"_4").val()) || 0;
    items.push({ name: name, qty: qty, price: (typeof to_Fixed === 'function' ? to_Fixed(price) : price), subtotal: (typeof to_Fixed === 'function' ? to_Fixed(subtotal) : subtotal) });
  });
  var footer = $('.pos-totals-footer');
  var tot_qty = parseFormattedNumber(footer.find('.tot_qty').text()) || 0;
  var tot_amt = parseFormattedNumber(footer.find('.tot_amt').text()) || 0;
  var tot_disc = parseFormattedNumber(footer.find('.tot_disc').text()) || 0;
  var tot_grand = parseFormattedNumber(footer.find('.tot_grand').text()) || 0;
  var customer_name = ($("#customer_id option:selected").text() || '').trim().replace(/</g,'&lt;').replace(/>/g,'&gt;');
  var paid_amount = 0;
  if (paidAmtOverride !== undefined && paidAmtOverride !== null && paidAmtOverride !== '') {
    paid_amount = parseFormattedNumber(String(paidAmtOverride)) || 0;
  }
  if (paid_amount <= 0) {
    var fromDisplay = parseFormattedNumber($(".sales_div_tot_paid").text());
    if (fromDisplay > 0) paid_amount = fromDisplay;
  }
  if (paid_amount <= 0) {
    var payments_row = parseInt($("#payment_row_count").val(), 10) || 0;
    for (var p = 1; p <= payments_row; p++) {
      if (document.getElementById("amount_"+p)) {
        var amt = parseFormattedNumber($("#amount_"+p).val()) || 0;
        if (amt > 0) paid_amount += amt;
      }
    }
  }
  if (paid_amount <= 0 && tot_grand > 0) paid_amount = tot_grand;
  var sym = (typeof window.baseCurrencySymbol !== 'undefined') ? window.baseCurrencySymbol : '';
  var balance = tot_grand - paid_amount;
  var changeReturn = balance < 0 ? Math.abs(balance) : 0;
  if (changeReturn > 0) balance = 0;
  var esc = function(s) { return (s && String(s).replace(/</g,'&lt;').replace(/>/g,'&gt;')) || ''; };
  var storeName = esc(typeof window.posStoreName !== 'undefined' ? window.posStoreName : '') || 'Store';
  var addr = esc(typeof window.posStoreAddress !== 'undefined' ? window.posStoreAddress : '');
  var city = esc(typeof window.posStoreCity !== 'undefined' ? window.posStoreCity : '');
  var postcode = esc(typeof window.posStorePostcode !== 'undefined' ? window.posStorePostcode : '');
  var mobile = esc(typeof window.posStoreMobile !== 'undefined' ? window.posStoreMobile : '');
  var phone = esc(typeof window.posStorePhone !== 'undefined' ? window.posStorePhone : '');
  var email = esc(typeof window.posStoreEmail !== 'undefined' ? window.posStoreEmail : '');
  var gstNo = esc(typeof window.posStoreGstNo !== 'undefined' ? window.posStoreGstNo : '');
  var vatNo = esc(typeof window.posStoreVatNo !== 'undefined' ? window.posStoreVatNo : '');
  var website = esc(typeof window.posStoreWebsite !== 'undefined' ? window.posStoreWebsite : '');
  var d = new Date();
  var dateStr = d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
  var timeStr = d.getHours() + ':' + (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
  var fmt = function(n) { return (typeof to_Fixed === 'function' ? to_Fixed(n) : n); };
  var css = 'body{font-family:arial;font-size:12px;font-weight:bold;margin:0;padding:10px;} table{width:100%;border-collapse:collapse;} tr{line-height:1.2;} td,th{padding:2px 3px !important;} .table-container{width:95%;margin:0 auto;} .invoice-header{page-break-after:avoid;} .invoice-items-table tbody tr{page-break-inside:avoid;} .invoice-footer tr{page-break-inside:avoid;} .no-print{display:none;} @media print{body{margin:0;padding:5px;font-size:10px;} .table-container{width:100%;} table{font-size:9px;} td,th{padding:2px !important;}}';
  var html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Invoice (Offline)</title><style type="text/css">' + css + '</style></head><body onload="setTimeout(function(){window.print();},300)">';
  html += '<div class="table-container"><table width="100%"><tbody class="invoice-header">';
  html += '<tr><td align="center"><span><strong>' + storeName + '</strong><br>';
  if (addr) html += addr + '<br>';
  if (city) html += city + (postcode ? ' - ' + postcode : '') + '<br>';
  if (mobile || phone) html += (mobile ? mobile : '') + (mobile && phone ? ', ' : '') + (phone ? phone : '') + '<br>';
  if (gstNo) html += gstNo + '<br>';
  if (vatNo) html += vatNo + '<br>';
  if (email) html += email + (website ? ', ' : '');
  if (website) html += website + '<br>';
  html += '</span></td></tr>';
  html += '<tr><td align="center"><strong>-----------------Invoice-----------------</strong></td></tr>';
  html += '<tr><td><table width="100%"><tr><td width="40%">Invoice</td><td><b>(Offline)</b></td></tr>';
  html += '<tr><td>Name</td><td>' + (customer_name || '-') + '</td></tr>';
  html += '<tr><td>Date: ' + dateStr + '</td><td style="text-align:right;">Time: ' + timeStr + '</td></tr></table></td></tr></tbody>';
  html += '<tbody class="invoice-items"><tr><td><table width="100%" cellpadding="0" cellspacing="0" class="invoice-items-table"><thead><tr style="border-top-style:dashed;border-bottom-style:dashed;">';
  html += '<th style="font-size:11px;text-align:left;padding-left:2px;">#</th><th style="font-size:11px;text-align:left;">Description</th>';
  html += '<th style="font-size:11px;text-align:center;">Qty</th><th style="font-size:11px;text-align:right;">Rate</th><th style="font-size:11px;text-align:right;">Total</th></tr></thead><tbody>';
  for (var j = 0; j < items.length; j++) {
    html += '<tr><td style="padding-left:2px;">' + (j + 1) + '</td><td>' + items[j].name + '</td><td style="text-align:center;">' + items[j].qty + '</td><td style="text-align:right;">' + sym + items[j].price + '</td><td style="text-align:right;">' + sym + items[j].subtotal + '</td></tr>';
  }
  html += '</tbody><tfoot class="invoice-footer">';
  html += '<tr><td colspan="4" align="right">Subtotal</td><td align="right">' + sym + fmt(tot_amt) + '</td></tr>';
  if (tot_disc > 0) html += '<tr><td colspan="4" align="right">Discount</td><td align="right">' + sym + fmt(tot_disc) + '</td></tr>';
  html += '<tr><td colspan="4" align="right">Total</td><td align="right">' + sym + fmt(tot_grand) + '</td></tr>';
  html += '<tr><td colspan="4" align="right">Paid Amount</td><td align="right">' + sym + fmt(paid_amount) + '</td></tr>';
  if (changeReturn > 0) html += '<tr><td colspan="4" align="right">Change / Refund</td><td align="right">' + sym + fmt(changeReturn) + '</td></tr>';
  if (balance > 0) html += '<tr><td colspan="4" align="right">Balance Due</td><td align="right">' + sym + fmt(balance) + '</td></tr>';
  if (balance <= 0 && changeReturn <= 0) html += '<tr><td colspan="4" align="right">Payment Status</td><td align="right"><strong>Paid in full</strong></td></tr>';
  html += '</tfoot></table></td></tr></tbody></table></div>';
  html += '<p class="no-print" style="margin-top:10px;font-size:10px;">Saved offline. Will sync when connection is restored.</p></body></html>';
  try {
    var w = window.open('', '_blank', 'width=450,height=600,scrollbars=1,resizable=1');
    if (w) { w.document.write(html); w.document.close(); w.focus(); w.print(); w.close(); }
  } catch (e) { console.error('Offline print failed', e); }
}

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;
  }

  /* Batch required: toast only, no browser alert */
  if (typeof validateBatchSelection === 'function' && !validateBatchSelection()) {
    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,
    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();

// 🔥 FORCE WALK-IN CUSTOMER (ID = 1)
$("#customer_id").val(1).trigger('change');

// 🔥 CLEAR OLD FINANCIAL DATA
$(".customer_previous_due").html('0');
$(".customer_tot_advance").html('0');
$(".sales_div_tot_paid").text('0');
$(".sales_div_tot_balance").text('0');;
              



              $("#search_it").val('');
              
              /*if warehouse enabled (guard: may be undefined if inline script failed to parse) */
              if(typeof warehouse_module !== 'undefined' && 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
        {
          var msg = (typeof result === 'string' ? result : result[0]) || '';
          if (msg.indexOf('Payble amount') !== -1 || msg.indexOf('payable') !== -1) {
            if (typeof toastr !== 'undefined') toastr.error(msg.replace(/\n/g, ' '), 'Payment', { timeOut: 6000, closeButton: true });
          } else if (typeof toastr !== 'undefined') {
            toastr.error(msg || 'Something went wrong.');
          } else {
            alert(msg);
          }
        }
      
      $("#"+this_btn).attr('disabled',false);  //Enable Save or Update button
      $(".overlay").remove();
     }
   })
   .fail(function(xhr, status, err) {
      $("#"+this_btn).attr('disabled', false);
      $(".overlay").remove();
      var isOfflineOrNetwork = (status === 'error' || xhr.status === 0 || (err && (String(err.message || err).toLowerCase().indexOf('network') !== -1)));
      if (isOfflineOrNetwork && typeof window.OfflineSyncManager !== 'undefined' && command === 'save') {
        var saveUrl = base_url+'pos/pos_save_update?command='+command+'&tot_qty='+encodeURIComponent(tot_qty)+'&tot_amt='+encodeURIComponent(tot_amt)+'&tot_disc='+encodeURIComponent(tot_disc)+'&tot_grand='+encodeURIComponent(tot_grand)+'&paid_amt='+encodeURIComponent(paid_amt)+'&balance='+encodeURIComponent(balance)+'&pay_all='+encodeURIComponent(pay_all);
        var dataObj = {};
        try {
          data.forEach(function(v, k) {
            if (v instanceof File || (typeof Blob !== 'undefined' && v instanceof Blob)) return;
            dataObj[k] = (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') ? v : String(v);
          });
          window.OfflineSyncManager.queueFailedTransaction({ type: 'sale', data: dataObj, url: saveUrl });
          if (print) { printOfflineReceipt(paid_amt); }
          toastr['success']('Transaction saved locally. It will sync when connection is restored.', 'Working offline', { timeOut: 5000, closeButton: true });
          if (typeof success !== 'undefined' && success) { success.currentTime = 0; success.play(); }
          var warehouse_id = $("#warehouse_id").val();
          $(".items_table > tbody").empty();
          $(".discount_input").val(0);
          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();

// 🔥 FORCE WALK-IN CUSTOMER (ID = 1)
$("#customer_id").val(1).trigger('change');

// 🔥 CLEAR OLD FINANCIAL DATA
$(".customer_previous_due").html('0');
$(".customer_tot_advance").html('0');
$(".sales_div_tot_paid").text('0');
$(".sales_div_tot_balance").text('0');
          $("#search_it").val('');
          if (typeof warehouse_module !== 'undefined' && warehouse_module) { $("#warehouse_id").val(warehouse_id).select2(); }
          final_total();
          get_details(null, true);
          hold_invoice_list();
          get_coupon_details();
        } catch (e) {
          console.error('Offline queue failed', e);
          toastr['error']('No internet connection. Transaction not saved. Please try again when online.', 'Connection lost', { timeOut: 5000, closeButton: true });
        }
      } else if (isOfflineOrNetwork) {
        toastr['error']('No internet connection. Please check your connection and try again.', 'Connection lost', { timeOut: 5000, closeButton: true });
      } else {
        toastr['error']('Could not save. Please try again.', 'Error', { timeOut: 4000 });
      }
   });
//} //confirmation sure
  //}); //confirmation end

//e.preventDefault


//});
}



/* *********************** 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
            {
              alert(result);
            }
          
          $("#"+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){
  try {
    if (typeof result === 'string' && result.trim().indexOf('<') === 0) throw new Error('HTML response');
    var data = jQuery.parseJSON(result);
    $("#hold_invoice_list").html('').html(data['result']);
    $(".hold_invoice_list_count").html('').html(data['tot_count']);
  } catch (e) {
    if (typeof toastr !== 'undefined') toastr.error('Could not load hold list.');
  }
});
}
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(resp){
    if(!resp || typeof resp!=='string'){
      $(".overlay").remove();
      if(typeof toastr!=='undefined') toastr.error('Could not load hold invoice.');
      return;
    }
    if(resp.indexOf('<<<###>>>')===-1){
      $(".overlay").remove();
      if(typeof toastr!=='undefined') toastr.error('Invalid response from server. Please try again.');
      return;
    }
    var qtyList='';
    var mainPart=resp;
    if(resp.indexOf('<<<QTY>>>')>=0){
      var parts=resp.split('<<<QTY>>>');
      mainPart=parts[0];
      qtyList=(parts[1]||'').toString().trim();
    }
    var segs=mainPart.split('<<<###>>>');
    var tableHtml=segs[0];
    var qtyFromHtml={};
    var reVal=/id="item_qty_(\d+)"[^>]*value="([^"]*)"|value="([^"]*)"[^>]*id="item_qty_(\d+)"/g;
    var m;
    while((m=reVal.exec(tableHtml))!==null){
      var idx=m[1]!==undefined?m[1]:m[4];
      var val=m[2]!==undefined?m[2]:m[3];
      if(idx!==undefined&&val!==undefined) qtyFromHtml[parseInt(idx,10)]=val;
    }
    var reData=/id="item_qty_(\d+)"[^>]*data-qty="([^"]*)"|data-qty="([^"]*)"[^>]*id="item_qty_(\d+)"/g;
    while((m=reData.exec(tableHtml))!==null){
      var idx=parseInt(m[1]!==undefined?m[1]:m[4],10);
      var val=m[2]!==undefined?m[2]:m[3];
      var num=parseFloat(String(val).replace(/,/g,''));
      if(!isNaN(num)&&(qtyFromHtml[idx]===undefined||parseFloat(String(qtyFromHtml[idx]).replace(/,/g,''))===0)) qtyFromHtml[idx]=val;
    }
    $('#pos-form-tbody').empty().append(tableHtml);
    $('#discount_input').val(segs[1]||'');
    $('#discount_type').val(segs[2]||'');
    $('#store_id').val(segs[4]||'');
    if(warehouse_module){
      $('#warehouse_id').val(segs[5]||'').select2();
    } else {
      $('#warehouse_id').val(segs[5]||'');
    }
    autoLoadFirstCustomer(segs[3]);
    $("#hidden_invoice_id").val(segs[7]||'');
    var rowCount=Math.max(0,parseInt($(".items_table tr").length,10)-1);
    $("#hidden_rowcount").val(rowCount);
    var fmtQty=(typeof format_qty==='function')?format_qty:function(v){ return v; };
    var setHoldQtys=function(){
      var applied=false;
      for(var idx in qtyFromHtml){
        if(!qtyFromHtml.hasOwnProperty(idx)) continue;
        var v=qtyFromHtml[idx];
        var num=parseFloat(String(v).replace(/,/g,''))||0;
        var $input=$("#item_qty_"+idx);
        if($input.length){ $input.val(fmtQty(num)); applied=true; }
      }
      if(!applied&&qtyList.length>0){
        var qtyArr=qtyList.split(',');
        for(var i=0;i<qtyArr.length;i++){
          var qv=parseFloat(qtyArr[i])||0;
          if($("#item_qty_"+i).length) $("#item_qty_"+i).val(fmtQty(qv));
        }
      }
      for(var r=0;r<rowCount;r++){
        var $q=$("#item_qty_"+r);
        if($q.length&&(parseFloat($q.val())||0)===0){
          var $row=$("#row_"+r);
          var rq=parseFloat($row.attr('data-row-qty'));
          if(!isNaN(rq)&&rq>0) $q.val(fmtQty(rq));
        }
      }
      // Recalculate each row subtotal from qty/price/tax/discount so totals are correct (fix wrong stored total_cost)
      if(typeof make_subtotal==='function'){
        for(var r=0;r<rowCount;r++){
          var itemId=$("#tr_item_id_"+r).val();
          if(itemId) make_subtotal(itemId,r);
        }
      } else {
        final_total();
      }
    };
    setHoldQtys();
    setTimeout(setHoldQtys,50);
    get_details(null,true);
    $(".overlay").remove();
    if(segs[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');
    // Default Walk-in customer to Cash payment
    var cid = $("#customer_id").val();
    if (cid == 1 || cid == '1') {
      $("#multiple-payments-modal select[id^='payment_type_']").each(function(){
        if ($(this).find("option[value='Cash']").length) $(this).val('Cash').trigger('change');
      });
    }
  }
}); //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();
    // By Cash & Save: force payment type to Cash so backend accepts it (especially for walk-in)
    if ($("#payment_type_1").find("option[value='Cash']").length) {
      $("#payment_type_1").val('Cash').trigger('change');
    }
    // Auto-fill payment amount with full total
    var paybleText = $('.sales_div_tot_payble').text();
    var payble = (typeof parseFormattedNumber === 'function') ? parseFormattedNumber(paybleText) : parseFloat(String(paybleText).replace(/[^0-9.-]/g, '')) || 0;
    var formatted = (typeof to_Fixed === 'function') ? to_Fixed(payble) : payble.toFixed(2);
    $('#amount_1').val(formatted).trigger('keyup');
    $("#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();
}

// Quick amount buttons: Full, 50%, 25%, 75%, Clear (set first payment amount from Total Payable)
$(document).off('click.posquick', '.pos-quick-amt').on('click.posquick', '.pos-quick-amt', function() {
  var pct = parseInt($(this).data('pct'), 10) || 0;
  var paybleText = $('.sales_div_tot_payble').text();
  var payble = (typeof parseFormattedNumber === 'function') ? parseFormattedNumber(paybleText) : parseFloat(String(paybleText).replace(/[^0-9.-]/g, '')) || 0;
  var val = (pct === 0) ? 0 : (payble * pct / 100);
  var formatted = (typeof to_Fixed === 'function') ? to_Fixed(val) : val.toFixed(2);
  var amount1 = $('#amount_1');
  if (amount1.length) {
    amount1.val(pct === 0 ? '' : formatted);
    amount1.trigger('keyup');
  }
});

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;
  try {
    item = jQuery.parseJSON(result);
  } catch (e) {
    $(".overlay").remove();
    if (typeof toastr !== 'undefined') toastr.error('Invalid response. Please try again.');
    return;
  }
  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'] !== undefined) ? item['batch_tracking_enabled'] : '0';
  obj['tracking_type']  = item['tracking_type'] || 'none';
  addrow(null,obj);
  if (obj['batch_tracking_enabled'] === '1' || obj['batch_tracking_enabled'] === 1) {
    if (typeof toastr !== 'undefined') {
      toastr.info('Select a batch for this item: click the tag icon next to the item in the cart.', 'Batch required', { timeOut: 5000, closeButton: true });
    }
  }
  $(".overlay").remove();
  // 🔥 FORCE CURSOR BACK TO SCANNER INPUT
$("#item_search").val('');
setTimeout(function () {
  $("#item_search").focus();
}, 10);
});

}

// 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 {
      if (typeof result === 'string' && result.trim().indexOf('<') === 0) throw new Error('HTML response');
      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();

// 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',
  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, err) {
    $("#pay_all").prop('disabled', false).html('<i class="fa fa-money" aria-hidden="true"></i> Pay All');
    var isOffline = !navigator.onLine || (window.OfflineSyncManager && !window.OfflineSyncManager.isOnline);
    var isNetworkError = !xhr || xhr.status === 0 || (err && (err.message || '').toLowerCase().indexOf('network') !== -1);
    if (isOffline || isNetworkError) {
      // When offline or network failed, skip account check and complete transaction; backend uses default cash account, sync when back online
      save(true, 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){

  if (SCAN_LOCK_UI) {
    cb([]); // 🔥 THIS is critical
    return;
  }

  var 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,
    };
  });

  cb(result);
}
      });
  },
   response:function(e,ui){
       // 🔥 BLOCK DROPDOWN COMPLETELY WHEN LOCKED
  if (SCAN_LOCK_UI) {
    ui.content = [];
    $(this).autocomplete("close");
      $(".ui-autocomplete").hide(); // 🔥 ADD
    return;
  }
        if(ui.content.length==1){
          $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
          $(this).autocomplete("close");
            $(".ui-autocomplete").hide(); // 🔥 ADD
        }
        //console.log(ui.content[0].id);
      },
      //loader start
      search: function () {
  if (SCAN_LOCK_UI) {
    return false; // 🔥 stops autocomplete completely
  }
},
   select: function (e, ui) { 
       
USER_TYPING = false;
  // 🔥 LOCK UI
  SCAN_LOCK_UI = true;

  $("#item_search").autocomplete("close");
  $(".ui-autocomplete").hide();

  var stock, item_id, service_bit;

  if(typeof ui.content!='undefined'){
    if(isNaN(ui.content[0].id)){
      SCAN_LOCK_UI = false;
      return false;
    }
    stock = ui.content[0].stock;
    item_id = ui.content[0].id;
    service_bit = ui.content[0].service_bit;
  }
  else{
    stock = ui.item.stock;
    item_id = ui.item.id;
    service_bit = ui.item.service_bit;
  }

  var qty = 1;

  // 🚫 STOCK CHECK (skip services)
if (service_bit == 0 && parseFloat(stock) <= 0) {
  toastr["error"]("Item is out of stock!");
  failed.currentTime = 0;
  failed.play();
  SCAN_LOCK_UI = false;
  return false;
}

  // 🔁 CHECK EXISTING QTY
  var existingQty = 0;
  $("input[id^='tr_item_id_']").each(function () {
    if ($(this).val() == item_id) {
      var row = $(this).closest('tr');
      existingQty += parseFloat(row.find("input[id^='item_qty_']").val()) || 0;
    }
  });

  if ((existingQty + qty) > parseFloat(stock)) {
    toastr["warning"](
      "Stock limit exceeded!\nAvailable: " + stock + 
      "\nAlready added: " + existingQty
    );

    failed.currentTime = 0;
    failed.play();

    SCAN_LOCK_UI = false;
    return false;
  }

  // OPTIONAL RULE
  if(service_bit==0 && parseFloat(stock)<=0){
    toastr["warning"](stock+" Items in Stock!!");
    failed.currentTime = 0; 
    failed.play();
    SCAN_LOCK_UI = false;
    return false;
  }

  // ✅ ADD ITEM ONLY ONCE
  get_item_details(item_id);

  // CLEAR INPUT
  $("#item_search").val('');

  // 🔓 UNLOCK
  setTimeout(function () {
    SCAN_LOCK_UI = false;
  }, 200);

  return false;
},
      //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;
    try {
      if (typeof data === 'string' && data.trim().indexOf('<') === 0) throw new Error('HTML response');
      json = $.parseJSON(data);
      if (!json || typeof json !== 'object') {
  toastr.error("Invalid coupon response");
  return;
}
    } catch (e) {
      input_box.removeClass('ui-autocomplete-loading');
      if (typeof toastr !== 'undefined') toastr.error('Invalid coupon response.');
      return;
    }
    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');
}
}); 
// 🔥 ALWAYS KEEP CURSOR ON SCANNER
var AUTO_FOCUS_SCAN = true;
$('#multiple-payments-modal').on('shown.bs.modal', function () {
  AUTO_FOCUS_SCAN = false;
});

$('#multiple-payments-modal').on('hidden.bs.modal', function () {
  AUTO_FOCUS_SCAN = true;

  setTimeout(function () {
    $("#item_search").focus();
  }, 150);
});

// Track manual typing to prevent forced refocus
$("#item_search").on('input keydown', function () {
  USER_TYPING = true;
  FORCE_SCAN_FOCUS = false; // 🔥 prevent bounce
  LAST_INPUT_TIME = Date.now();
});

$("#item_search").on('blur', function () {
  setTimeout(function () {
    USER_TYPING = false;
  }, 300);
});

$(document).on('click', function(e){
  var now = Date.now();

  // 🔥 If clicking inside ANY input → never steal focus
  if ($(e.target).closest('input, textarea, select').length) {
    FORCE_SCAN_FOCUS = false;
    return;
  }

  if (
    !AUTO_FOCUS_SCAN ||
    !FORCE_SCAN_FOCUS ||   // 🔥 NEW
    USER_TYPING ||
    USER_FOCUSED_INPUT ||
    (now - LAST_INPUT_TIME < 1500)
  ) return;

  $("#item_search").focus();
});

// 🔥 ALSO force focus after scan
$(document).ajaxComplete(function () {
  var now = Date.now();

  if (
    !AUTO_FOCUS_SCAN ||
    !FORCE_SCAN_FOCUS ||        // 🔥 NEW HARD BLOCK
    USER_TYPING ||
    USER_FOCUSED_INPUT ||
    (now - LAST_INPUT_TIME < 1500) || // 🔥 increase buffer
    $('#multiple-payments-modal').hasClass('show')
  ) {
    return;
  }

  $("#item_search").focus();
});

