// Function to copy UPI ID
function copyUpiId() {
    const upiId = document.getElementById('upiId');
    upiId.select();
    document.execCommand('copy');
    
    // Show alert
    const alertBox = document.getElementById('alertBox');
    alertBox.style.display = 'block';
    setTimeout(() => {
        alertBox.style.display = 'none';
    }, 2000);
}

// Modal functions
function openModal() {
    document.getElementById('guideModal').style.display = 'block';
}

function closeModal() {
    document.getElementById('guideModal').style.display = 'none';
}

// Form submission handler
document.getElementById('submitButton').addEventListener('click', function() {
    const utr_number = document.getElementById('utr_number').value;
    const encodedData = document.getElementById('encodedData').value;

    if (utr_number.trim() === '') {
        showAlert('Please enter the UTR number.');
        return;
    }

    const formData = new FormData();
    formData.append('utr_number', utr_number);
    formData.append('data', encodedData);

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

    xhr.onload = function() {
        if (xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);

            if (response.status_code === 200 && response.status === 'Success') {
                showAlert('Payment successfully submitted!');
                
                const orderid = "<?php echo $orderid; ?>";
                const redirectUrl = "<?php echo $redirect_url; ?>";

                const postForm = document.createElement('form');
                postForm.method = 'POST';
                postForm.action = redirectUrl;

                const orderidField = document.createElement('input');
                orderidField.type = 'hidden';
                orderidField.name = 'order_id';
                orderidField.value = orderid;
                postForm.appendChild(orderidField);

                const utrNumberField = document.createElement('input');
                utrNumberField.type = 'hidden';
                utrNumberField.name = 'utr_number';
                utrNumberField.value = utr_number;
                postForm.appendChild(utrNumberField);

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

                document.body.appendChild(postForm);
                postForm.submit();
            } 
            else if (response.status_code === 202) {
                showAlert('Payment is Pending. Please wait for confirmation.');
            }
            else if (response.status_code === 201 && response.status === 'Success') {
                showAlert('Transaction is already successful!');

                const orderid = "<?php echo $orderid; ?>";
                const redirectUrl = "<?php echo $redirect_url; ?>";

                const postForm = document.createElement('form');
                postForm.method = 'POST';
                postForm.action = redirectUrl;

                const orderidField = document.createElement('input');
                orderidField.type = 'hidden';
                orderidField.name = 'order_id';
                orderidField.value = orderid;
                postForm.appendChild(orderidField);

                if (response.message) {
                    const txnIdField = document.createElement('input');
                    txnIdField.type = 'hidden';
                    txnIdField.name = 'txn_id';
                    txnIdField.value = response.message;
                    postForm.appendChild(txnIdField);
                }

                document.body.appendChild(postForm);
                postForm.submit();
            }
            else {
                showAlert('Error: ' + response.message);
            }
        } else {
            showAlert('Error: ' + xhr.statusText);
        }
    };

    xhr.onerror = function() {
        showAlert('Request failed. Please check your network connection.');
    };

    xhr.send(formData);
});

// Function to show alert
function showAlert(message) {
    const alertUtr = document.getElementById('alertUtr');
    const alertMessage = document.getElementById('alertMessage');
    alertMessage.textContent = message;
    alertUtr.style.display = 'block';

    setTimeout(function() {
        alertUtr.style.display = 'none';
    }, 2000);
}

// Countdown timer
const expirationTimeString = "<?= htmlspecialchars($res['expiration_time']); ?>";
const expirationTimestamp = Date.parse(expirationTimeString) / 1000;

if (isNaN(expirationTimestamp)) {
    console.error("Invalid expiration time:", expirationTimeString);
    document.querySelector('#timer').textContent = "Invalid Time";
} else {
    function updateCountdown() {
        const currentTime = Math.floor(Date.now() / 1000);
        const timeRemaining = expirationTimestamp - currentTime;

        if (timeRemaining <= 0) {
            document.querySelector('#timer').textContent = "Expired";
            clearInterval(countdownInterval);
        } 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')}`;
        }
    }

    updateCountdown();
    const countdownInterval = setInterval(updateCountdown, 1000);
}

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

    if (navigator.share) {
        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 {
        alert('Sharing is not supported on this device or browser. You can copy the QR code URL or open it in a new tab.');
    }
});

// Order status check
const encodedData = "<?php echo addslashes($encodedData); ?>";
const redirectUrl = "<?php echo $redirect_url; ?>";
const merchantName = "<?php echo $merchant_name; ?>";

function getApiUrl(merchantName) {
    const baseUrl = '';
    switch (merchantName.toLowerCase()) {
        case 'paytm':
            return baseUrl + 'payment-status/paytm-status-txid.php';
        case 'amazon':
            return baseUrl + 'payment-status/amazon-status-txid.php';
        case 'sbi':
            return baseUrl + 'payment-status/sbi-status-txid.php';
        case 'freecharge':
            return baseUrl + 'payment-status/freecharge-status-txid.php';
        default:
            console.error('Unsupported merchant:', merchantName);
            return null;
    }
}

function checkOrderStatus() {
    const apiUrl = getApiUrl(merchantName);

    if (!apiUrl) {
        console.error('Unsupported merchant:', merchantName);
        return;
    }

    const interval = setInterval(function() {
        fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: "data=" + encodedData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.status_code === 400 && data.status === 'Failed') {
                if (data.message === 'Invalid Amount Received') {
                    alert('Payment failed: Invalid amount received. Please check the amount and try again.');
                } else {
                    alert('Payment failed: ' + data.message);
                }
                clearInterval(interval);
            } else if (data.status_code === 200 && data.status === 'Success') {
                alert('Payment successful!');
                clearInterval(interval);

                const orderid = "<?php echo $orderid; ?>";
                console.log("Order ID from PHP: " + orderid);

                if (!orderid) {
                    alert("Order ID is missing!");
                    return;
                }

                const form = document.createElement('form');
                form.method = 'POST';
                form.action = redirectUrl;

                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'order_id';
                input.value = orderid;

                form.appendChild(input);
                document.body.appendChild(form);
                form.submit();
            } else {
                console.error('Unexpected status:', data.status);
            }
        })
        .catch(error => {
            console.error('Error fetching order status:', error);
        });
    }, 2000);
}

// Start checking order status
checkOrderStatus();