// Script for handling form submission and payment status
document.getElementById('submitButton').addEventListener('click', function() {
// Get the form data
var utr_number = document.getElementById('utr_number').value;
var encodedData = document.getElementById('encodedData').value;

// Make sure the UTR number is not empty
if (utr_number.trim() === '') {
alert('Please enter the UTR number.');
return;
}

// Prepare the data to be sent via POST
var formData = new FormData();
formData.append('utr_number', utr_number);
formData.append('data', encodedData);

// Create the request
var xhr = new XMLHttpRequest();
xhr.open('POST', 'payment-status/<?php echo strtolower($merchant_name); ?>-status.php', true);

// Handle the response
xhr.onload = function() {
if (xhr.status === 200) {
// Parse the response
var response = JSON.parse(xhr.responseText);

// Check if status_code is 200 and status is "Success"
if (response.status_code === 200 && response.status === 'Success') {
// If successful, show success message
alert('Payment successfully submitted!');

// Optionally, display transaction details (if needed)
if (response.data && response.data.txn_id) {
console.log('Transaction ID:', response.data.txn_id);
}

// Get the orderid (Ensure the PHP variable is echoed correctly)
var orderid = "<?php echo $orderid; ?>";  // Fetch the PHP order ID

// Prepare the redirect URL (this is the URL you want to post to)
var redirectUrl = "<?php echo $redirect_url; ?>";  // Fetch the redirect URL

// Create a new form to send via POST
var postForm = document.createElement('form');
postForm.method = 'POST';
postForm.action = redirectUrl;

// Append the orderid to the form
var orderidField = document.createElement('input');
orderidField.type = 'hidden';
orderidField.name = 'order_id';
orderidField.value = orderid;
postForm.appendChild(orderidField);

// Append any other necessary data to the form (e.g., utr_number and encodedData)
var utrNumberField = document.createElement('input');
utrNumberField.type = 'hidden';
utrNumberField.name = 'utr_number';
utrNumberField.value = utr_number;
postForm.appendChild(utrNumberField);

var encodedDataField = document.createElement('input');
encodedDataField.type = 'hidden';
encodedDataField.name = 'encodedData';
encodedDataField.value = encodedData;
postForm.appendChild(encodedDataField);

// Append the form to the body and submit it
document.body.appendChild(postForm);
postForm.submit();
} 
else if (response.status_code === 202) {
// If status code is 202, the payment is still pending
alert('Payment is pending. Please wait for confirmation.');
}
else if (response.status_code === 201 && response.status === 'Success') {
// If status code is 201, the payment has already been successfully processed
alert('Transaction is already successful!');

// Get the orderid (Ensure the PHP variable is echoed correctly)
var orderid = "<?php echo $orderid; ?>";  // Fetch the PHP order ID

// Prepare the redirect URL (this is the URL you want to post to)
var redirectUrl = "<?php echo $redirect_url; ?>";  // Fetch the redirect URL

// Create a new form to send via POST
var postForm = document.createElement('form');
postForm.method = 'POST';
postForm.action = redirectUrl;

// Append the orderid to the form
var orderidField = document.createElement('input');
orderidField.type = 'hidden';
orderidField.name = 'order_id';
orderidField.value = orderid;
postForm.appendChild(orderidField);

// Optionally, you can also append transaction-specific data like txn_id if needed
if (response.message) {
var txnIdField = document.createElement('input');
txnIdField.type = 'hidden';
txnIdField.name = 'txn_id';
txnIdField.value = response.message;  // Assuming the message contains the txn ID
postForm.appendChild(txnIdField);
}

// Append the form to the body and submit it
document.body.appendChild(postForm);
postForm.submit();
}
else {
// Handle other error responses
alert('Error: ' + response.message);
}
} else {
// If there was an issue with the HTTP request (non-200 status)
alert('Error: ' + xhr.statusText);
}
};

// Handle network errors
xhr.onerror = function() {
alert('Request failed. Please check your network connection.');
};

// Send the request with the data
xhr.send(formData);
});

// Script for handling countdown timer
const expirationTimeString = "<?= htmlspecialchars($res['expiration_time']); ?>";
const expirationTimestamp = Date.parse(expirationTimeString) / 1000; // Convert expiration time to timestamp (in seconds)

// Check if expiration time is valid
if (isNaN(expirationTimestamp)) {
console.error("Invalid expiration time:", expirationTimeString);
document.querySelector('#timer').textContent = "Invalid Time";
} else {
// Function to update countdown timer
function updateCountdown() {
const currentTime = Math.floor(Date.now() / 1000); // Get the current time in seconds
const timeRemaining = expirationTimestamp - currentTime; // Calculate remaining time in seconds

if (timeRemaining <= 0) {
document.querySelector('#timer').textContent = "Expired";
clearInterval(countdownInterval); // Stop the countdown once expired
} else {
const hours = Math.floor(timeRemaining / 3600);
const minutes = Math.floor((timeRemaining % 3600) / 60);
const seconds = timeRemaining % 60;
document.querySelector('#timer').textContent = `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
}

// Start the countdown immediately
updateCountdown();

// Call the countdown function every second
const countdownInterval = setInterval(updateCountdown, 1000);
}

// Script for handling QR Code sharing
document.getElementById('shareQrButton').addEventListener('click', function () {
const qrImage = document.getElementById('qrImage').src;

// Check if the Web Share API is supported
if (navigator.share) {
// Try using the Web Share API to share the QR code image
fetch(qrImage)
.then(response => response.blob())
.then(blob => {
const file = new File([blob], "qr_code.png", { type: "image/png" });

navigator.share({
title: 'QR Code for Payment',
text: 'Scan this QR code to make a payment.',
files: [file]
})
.then(() => console.log('QR Code shared successfully'))
.catch(error => console.log('Error sharing QR Code:', error));
})
.catch(error => console.log('Error fetching image:', error));
} else {
// Fallback if Web Share API is not supported
alert('Sharing is not supported on this device or browser. You can copy the QR code URL or open it in a new tab.');
}
});