function panValidation(txt)
{
	txt = txt.toUpperCase();
	var regex = /[a-zA-Z]{3}[PCHFATBLJG]{1}[a-zA-Z]{1}[0-9]{4}[a-zA-Z]{1}$/;
    var pan = {C:"Company", P:"Personal", H:"Hindu Undivided Family (HUF)", F:"Firm", A:"Association of Persons (AOP)", T:"AOP (Trust)", B:"Body of Individuals (BOI)", L:"Local Authority", J:"Artificial Juridical Person", G:"Govt"};
    pan=pan[txt[3]];
	if(regex.test(txt)){
    if(pan!="undefined"){
    document.getElementById("pan_no").value = txt;
    }else{
	  document.getElementById("pan_no").value = '';
	  alert("PAN Number is not Valid");
	}
    }else{
	  document.getElementById("pan_no").value = '';
	  alert("PAN Number is not Valid");
	}
}

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function funLocation(elm) {
var x = document.getElementById(elm);
getLocation();
function getLocation() {
  if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    alert("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
var obj = {latitude: position.coords.latitude, longitude:position.coords.longitude};
var myJSON = JSON.stringify(obj);
x.value = myJSON;  
}
}

function upiCountdown(elm,minute,second,url) {
document.getElementById(elm).innerHTML =minute + ":" + second; startTimer();

function startTimer() {
  var presentTime = document.getElementById(elm).innerHTML;
  var timeArray = presentTime.split(/[:]+/);
  var m = timeArray[0];
  var s = checkSecond((timeArray[1] - 1));
  if(s==59){m=m-1}
  if(m==0 && s<1){
      
    //  swal ( "Oops" ,  "Transaction Timeout!" ,  "error" );
      timeOut();
    //  window.location.href = url;
      
  }
  document.getElementById(elm).innerHTML =
    m + ":" + s;
  //console.log(m)
  setTimeout(startTimer, 1000);
}

function checkSecond(sec) {
  if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
  if (sec < 0) {sec = "59"};
  return sec;
}
}

function GenerateQR(upi_id, payer_name, amount, txnid, note) {
    // Clean and simple UPI URL format that works with all apps
    var cleanPayerName = payer_name.replace(/[^a-zA-Z0-9\s]/g, '').trim();
    var cleanNote = note.replace(/[^a-zA-Z0-9\s]/g, '').trim();
    
    // Standard UPI URL format - simplified for maximum compatibility
    var upiURL = 'upi://pay?pa=' + upi_id + 
                 '&pn=' + cleanPayerName + 
                 '&am=' + amount + 
                 '&cu=INR' + 
                 '&tr=' + txnid;
    
    // Only add note if it exists and is not empty
    if (cleanNote && cleanNote.length > 0) {
        upiURL += '&tn=' + cleanNote;
    }
    
    // Generate QR with optimal settings for mobile scanning
    var sampleQR = new QRCode('qrcode', { 
        text: upiURL,
        width: 256,
        height: 256,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.L  // Low error correction for better scanning
    });
    
    // Show buttons after QR is generated
    setTimeout(function() {
        // Hide loading overlay
        var loadingOverlay = document.getElementById('qrLoadingOverlay');
        if (loadingOverlay) {
            loadingOverlay.style.display = 'none';
        }
        
        // Show action buttons
        var downloadBtn = document.getElementById('downloadBtn');
        var copyUpiBtn = document.getElementById('copyUpiBtn');
        if (downloadBtn) {
            downloadBtn.style.display = 'inline-block';
        }
        if (copyUpiBtn) {
            copyUpiBtn.style.display = 'inline-block';
        }
        console.log('Generated UPI URL:', upiURL); // For debugging
        
        // Store UPI URL and UPI ID globally
        window.currentUPIURL = upiURL;
        window.currentUPIID = upi_id;
        
        // Store in hidden input for form submission
        var upiInput = document.getElementById('upilink');
        if (upiInput) {
            upiInput.value = upiURL;
        }
        
        // Add subtle success animation
        var qrContainer = document.querySelector('.qr-container');
        if (qrContainer) {
            qrContainer.style.animation = 'pulse 0.5s ease-in-out';
        }
    }, 1000);
    
    updateQR = (upi_id, payer_name, amount, note) => { 
        var cleanPayerName = payer_name.replace(/[^a-zA-Z0-9\s]/g, '').trim();
        var cleanNote = note.replace(/[^a-zA-Z0-9\s]/g, '').trim();
        var upiURL = 'upi://pay?pa=' + upi_id + 
                     '&pn=' + cleanPayerName + 
                     '&am=' + amount + 
                     '&cu=INR' + 
                     '&tr=' + txnid;
        if (cleanNote && cleanNote.length > 0) {
            upiURL += '&tn=' + cleanNote;
        }
        sampleQR.makeCode(upiURL);
        window.currentUPIURL = upiURL;
    };
}


function SendOtpCode(){
    
   var lid = $(".lid").val();
   var lpwd = $(".lpwd").val();
   if(lid===""){
   swal("Alert!", "Enter Your Login Username!", "error");       
   }else{
   if(lpwd===""){
   swal("Alert!", "Enter Your Login Password!", "error");       
   }else{
       
   var base_url = window.location.origin;    
   document.getElementById("load").innerHTML = "<button type='button' class='btn btn-primary btn-sm'><img src='"+base_url+"/assets/img/animated_spinner.webp' width='20' width=''20></button>";        
    
   $.ajax({ 
            url: "../system/sendotpcode",
			type: "POST", 
			data:{lid:lid,lpwd:lpwd},
            success: function(result) {
			var obj = JSON.parse(result);
			if(obj.status===true){
			swal("Registered Email & Mobile Number!", obj.msg, "success"); 
			document.getElementById("load").innerHTML = "<button type='button' class='btn btn-primary btn-sm'>Wait 10 Second</button>";
			setTimeout(function(){ 
			document.getElementById("load").innerHTML = "<button type='button' class='btn btn-primary btn-sm' onclick='SendOtpCode();'>Resend OTP Code</button>";     
			}, 10000);
			}else{
			swal("Alert!", obj.msg, "error");  
			document.getElementById("load").innerHTML = "<button type='button' class='btn btn-primary btn-sm' onclick='SendOtpCode();'>Send OTP Code</button>";       
			}
         
			  
            }
    });
   }
}
}

// Download QR Code Function with Border
function downloadQR() {
    try {
        var qrElement = document.getElementById('qrcode');
        var canvas = qrElement.querySelector('canvas');
        
        if (!canvas) {
            swal("Alert!", "QR Code not generated yet. Please wait for the QR code to load.", "warning");
            return;
        }
        
        // Create a new canvas with border and padding
        var newCanvas = document.createElement('canvas');
        var ctx = newCanvas.getContext('2d');
        
        // Set new canvas size with padding
        var padding = 40;
        var borderWidth = 4;
        newCanvas.width = canvas.width + (padding * 2) + (borderWidth * 2);
        newCanvas.height = canvas.height + (padding * 2) + (borderWidth * 2);
        
        // Fill background white
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);
        
        // Draw border
        ctx.strokeStyle = '#085bac';
        ctx.lineWidth = borderWidth;
        ctx.strokeRect(borderWidth/2, borderWidth/2, newCanvas.width - borderWidth, newCanvas.height - borderWidth);
        
        // Draw QR code in center
        ctx.drawImage(canvas, padding + borderWidth, padding + borderWidth);
        
        // Create download link
        var link = document.createElement('a');
        link.download = 'UPI_QR_Code_' + new Date().getTime() + '.png';
        link.href = newCanvas.toDataURL('image/png');
        
        // Trigger download
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        swal("Success!", "QR Code downloaded successfully!", "success");
    } catch (error) {
        swal("Error!", "Failed to download QR Code. Please try again.", "error");
        console.error('Download error:', error);
    }
}

// Copy UPI ID Function
function copyUpiId() {
    try {
        if (window.currentUPIID) {
            // Modern browsers
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(window.currentUPIID).then(function() {
                    swal("Success!", "UPI ID copied to clipboard!\n" + window.currentUPIID, "success");
                });
            } else {
                // Fallback for older browsers
                var textArea = document.createElement("textarea");
                textArea.value = window.currentUPIID;
                textArea.style.position = 'fixed';
                textArea.style.left = '-999999px';
                textArea.style.top = '-999999px';
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                try {
                    document.execCommand('copy');
                    swal("Success!", "UPI ID copied to clipboard!\n" + window.currentUPIID, "success");
                } catch (err) {
                    swal("UPI ID", window.currentUPIID, "info");
                }
                document.body.removeChild(textArea);
            }
        } else {
            swal("Alert!", "UPI ID not available yet. Please wait for QR code to load.", "warning");
        }
    } catch (error) {
        swal("Error!", "Failed to copy UPI ID. Please try again.", "error");
        console.error('Copy UPI ID error:', error);
    }
}