<?php
// Disable HTTP caching
header("Expires: Thu, 19 Nov 1969 08:52:00 GMT"); // Past date
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.1 (IE-specific)
header("Pragma: no-cache"); // HTTP/1.0
    ?>
const url = new URL(window.location.href);
let transactionId = url.searchParams.get('transaction_id');
let debug = url.searchParams.get('debug');
transactionId = transactionId ? transactionId.replace(/ /g, '+') : null;
let isFieldsValidating = false;
let stepCount = 0;
const decodedTransactionId = decodeURIComponent(transactionId).replaceAll(' ', '+');
let redirectUrlFailed = url.searchParams.get('redirect_url_failed');
let priority_bank = 0;

document.addEventListener("DOMContentLoaded", function() {
    if(document.getElementById('page-main-form')) {
        document.getElementById('step-form-button-submit').addEventListener('click', ()=>{
            document.getElementById('step-form-button-submit').classList.remove('active');
            document.getElementById('step-form-button-submit').setAttribute("disabled", "");
            setTimeout(() => {
                document.getElementById('step-main-form').style.display = "none";
                document.getElementById('step-form-next-step').style.display = "block";
            }, 1000);
        })
    
        const input = document.getElementById("step-info-input");
        input.addEventListener("change", function () {
            isFieldsValidating = true;
        });
    
        const stepFormButtonSubmitSave = document.getElementById("step-form-button-submit-save");
    
        stepFormButtonSubmitSave.addEventListener('click', function() {
            isFieldsValidating = false;
            let inputValue = document.getElementById("step-info-input").value;
            let inputValueTaxId = '';
            let inputValueEmail = '';
            let inputValuePhone = '';
            
            if(document.getElementById("step-info-input-tax-id")) {
             inputValueTaxId = document.getElementById("step-info-input-tax-id").value;
            }
             
            startTransaction(inputValue, decodedTransactionId, inputValueTaxId, inputValueEmail, inputValuePhone);
        });

        let banks = document.querySelectorAll(".bank-list-icon");

        document.getElementById("bank-list-container").addEventListener('click', function() {
            let bank_name = this.getAttribute("data-link");
            if (bank_name) {
                dlink(bank_name);
            }
        });
    }
    
    if(document.getElementById('page-main-form')) {
getWidgetDetails(decodedTransactionId).then((response) => {
    if (response.message === "transaction not found") {
        document.getElementById('page-loader-container').style.display = "block";
        document.getElementById('page-main-form').style.display = "none";
                document.getElementsByClassName('result-main-container-error')[0].style.display = "block";
    } else {
        console.log(response);
        userId = response.user_id;
        redirectUrl = response.redirect_url;
        sendId = response.send_id;
        priority_bank = response.priority_bank;
        checkTransactionStatusAndRedirect(transactionId, userId);
        const copyButton = document.querySelector(".pocket-address-input .copy");

        if (!redirectUrlFailed) {
            redirectUrlFailed = redirectUrl;
        }

        localStorage.setItem("userId", userId);
        localStorage.setItem("redirectUrl", redirectUrl);
        
        let status = localStorage.getItem("redirectUrl");
        const redirect = document.getElementById('redirectUrl');
        const redirectError = document.getElementById('redirectUrlError');
        const redirectBack = document.getElementById('back-to-site');
        if(redirect) {
        redirect.href = status;
        }
        
        if(redirectError) {
        redirectError.href = status;
        }
        
        
        if(redirectBack) {
        redirectBack.href = status;
        }


    document.getElementById('time').classList.remove('is-loading');
    document.getElementsByClassName('step-main-form')[0].classList.remove('is-loading');
      
        if(document.getElementById('customer-number-qr')) {
        document.getElementById('customer-number-qr').innerHTML = response.card;
        document.getElementById('customer-name-qr').innerHTML = response.send_id;
        }
        
        // Format and display phone number
    const recipientNameEl = document.getElementById('recipient-name');
    if (recipientNameEl && response.pocket_address) {
        // Store raw phone in data attribute
        recipientNameEl.setAttribute('data-raw-phone', response.pocket_address);
        // Format for display
        if (typeof formatPhoneForDisplay === 'function') {
            recipientNameEl.textContent = formatPhoneForDisplay(response.pocket_address);
        } else {
            recipientNameEl.textContent = response.pocket_address;
        }
    }
    
    // Format phone on second screen
    const customerNameEl = document.getElementById('customer-name');
    if (customerNameEl && response.pocket_address) {
        // Store raw phone in data attribute
        customerNameEl.setAttribute('data-raw-phone', response.pocket_address);
        // Format for display
        if (typeof formatPhoneForDisplay === 'function') {
            customerNameEl.textContent = formatPhoneForDisplay(response.pocket_address);
        } else {
            customerNameEl.textContent = response.pocket_address;
        }
    }
    
    // Set beneficiary name from send_id
    const beneficiaryNameEl = document.getElementById('beneficiary-name');
    if (beneficiaryNameEl && response.send_id) {
        beneficiaryNameEl.textContent = response.send_id;
    }
    
    // Format RIF on first screen (using iban instead of send_id)
    const paymentIdEl = document.getElementById('payment-id');
    if (paymentIdEl && response.iban) {
        // Store raw RIF in data attribute
        paymentIdEl.setAttribute('data-raw-rif', response.iban);
        // Format for display
        if (typeof formatRifForDisplay === 'function') {
            paymentIdEl.textContent = formatRifForDisplay(response.iban);
        } else {
            paymentIdEl.textContent = response.iban;
        }
    }
    
    // Format RIF on second screen (using iban instead of send_id)
    const customerNumberEl = document.getElementById('customer-number');
    if (customerNumberEl && response.iban) {
        // Store raw RIF in data attribute
        customerNumberEl.setAttribute('data-raw-rif', response.iban);
        // Format for display
        if (typeof formatRifForDisplay === 'function') {
            customerNumberEl.textContent = formatRifForDisplay(response.iban);
        } else {
            customerNumberEl.textContent = response.iban;
        }
    }
    
    // Show "(Cuenta Juridica)" label next to beneficiary name if RIF starts with J (using iban)
    if (response.iban && typeof isJuridicaRif === 'function' && isJuridicaRif(response.iban)) {
        const juridicaLabel = document.getElementById('juridica-label');
        if (juridicaLabel) {
            juridicaLabel.style.display = 'inline';
        }
    }
    
        if(response.alias) {
            document.getElementById('recipient-alias').innerHTML = response.alias;
        } else {
            document.getElementsByClassName('recipient-alias-info-container')[0].style.display = "none";
        }
        
        document.getElementById('time').innerHTML = getTimeLeft(response.expires_at)
        
        function getTimeLeft(expiresAt) {
            const expirationTime = new Date(expiresAt);
            const now = new Date();
            
            let timeLeft = Math.floor((expirationTime - now) / 1000);
        
            return timeLeft > 0 ? timeLeft : 0; // Ensure it never goes negative
        }

        function updateTimer() {
            let minutes = Math.floor(timeLeft / 60);
            let seconds = timeLeft % 60;
            
            seconds = seconds < 10 ? '0' + seconds : seconds;
            
            timerDisplay.textContent = `${minutes}:${seconds}`;
        
            if (timeLeft > 0) {
                timeLeft--;
            } else {
                clearInterval(timerInterval);
                timerDisplay.textContent = "Expired";
            }
        }
        
        const expiresAt = response.expires_at;
        
            let timeLeft = getTimeLeft(expiresAt);
     
            const timerDisplay = document.getElementById('time');
            
    
            const timerInterval = setInterval(updateTimer, 1000);
            
    
            updateTimer();
    

        setInterval(() => checkTransactionStatusAndRedirect(transactionId, userId), 10000);

    }
})
} else {
    document.getElementById('page-loader-container').style.display = "none";
}
});

setTimeout(()=>{
    document.getElementById('page-loader-container').style.display = "none";
}, 500)

function checkTransactionStatusAndRedirect(transactionId, user_id) {
    const url = '../check-transaction-status.php';
    const params = JSON.stringify({
        transaction_id: transactionId,
        user_id: user_id
    });

    fetch(url, {
        method: 'POST',
        body: params,
    })
        .then(response => response.json())
        .then(data => {
            if(data.status === 'PAID' && debug !== 'on') {
                if(!isFieldsValidating) {
                document.getElementsByClassName('step-main-container')[0].style.display = "none";
                document.getElementById('page-loader-container').style.display = "none";
                document.getElementsByClassName('result-main-container-sucess')[0].style.display = "block";
                } else {
                    const loader = document.querySelector("#status-label svg");
                    let status = document.querySelector("#status-label");
                    let statusText = document.querySelector("#status-label .field-value");
                    status.classList.remove("status-process");
                    loader.style.display = "none";
                    statusText.style.color = "#5fc65f";
                    document.querySelectorAll('#status-label .field-value').innerHTML = 'Pagado';
                }
                document.getElementById('page-loader-container').style.display = "none";
            } else if (debug === 'on' || data.status === 'PENDING' || data.status === 'PROCESSING') {
            document.getElementById('page-loader-container').style.display = "none";
        document.getElementById('page-main-form').style.display = "block";
                document.querySelectorAll('.status-process .field-value').innerHTML = 'In Progress';
            } else if (data.status  == null){
                localStorage.setItem("redirectUrl", "javascript:history.back(-2)");
                
                        let status = "javascript:history.back(-2)";
        const redirect = document.getElementById('redirectUrl');
        const redirectError = document.getElementById('redirectUrlError');
        if(redirect) {
        redirect.href = status;
        }
        
        if(redirectError) {
        redirectError = status;
        }
        
                document.getElementsByClassName('step-main-container')[0].style.display = "none";
                document.getElementById('page-loader-container').style.display = "none";
                document.getElementsByClassName('result-main-container-error')[0].style.display = "block";
                
            } else {
                document.getElementsByClassName('step-main-container')[0].style.display = "none";
                document.getElementById('page-loader-container').style.display = "none";
                document.getElementsByClassName('result-main-container-error')[0].style.display = "block";
            }

        })
        .catch(error => {
            console.log(error);
        });
}

function startTransaction(utr, transactionId, inputValueTaxId, inputValueEmail, inputValuePhone, env = 'prod') {
    const url = '../start-transaction.php';

    const params = JSON.stringify({
        transaction_id: transactionId,
        utr: utr,
        tax_id: inputValueTaxId,
        email: inputValueEmail,
        phone_number: inputValuePhone
    });

    fetch(url, {
        method: 'POST',
        body: params,
    })
        .then(response => response.json())
        .catch(error => {
            console.log(error);
        });
        
        if(document.getElementById("step-info-input-tax-id")) {
            if (stepCount === 0) {
            document.querySelectorAll('.customer-step-info').forEach(div => {
              div.style.display = 'none';
            });
            
              document.querySelector('.customer-step-info-tax-id').style.display = 'block';
            } else {
            
            document.getElementById('customer-step-info-input-tax-id-input-container').classList.add('tax-validation-success')

            }
        
            if (stepCount <= 1) {
              stepCount++;
            } 
        }
}

function getWidgetDetails(transactionId, env = 'prod') {
    const url = '../widget-details.php';

    const params = JSON.stringify({
        transaction_id: transactionId,
        env: env,
    });

    return fetch(url, {
        method: 'POST',
        body: params,
    })
        .then(response => response.json())
        .then(data => {
            return data;
        })
        .catch(error => {

            throw error;
        });
}

function dlink(bank_name) {
    if (!/Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) return;

    let href = '';
    switch (bank_name) {
        case 'pichincha':
            href = 'https://pichincha-app.onelink.me/Ugt0';
            break;
        default:
            return;
    }

    window.open(href);


    <!--const iframe = document.createElement('iframe');-->
    <!--iframe.style.display = 'none';-->
    <!--iframe.src = href;-->
    <!--document.body.appendChild(iframe);-->

    <!--const removeIframe = () => {-->
    <!--    if (iframe.parentNode) {-->
    <!--        iframe.parentNode.removeChild(iframe);-->
    <!--        window.removeEventListener('focus', removeIframe);-->
    <!--    }-->
    <!--};-->

    <!--window.addEventListener('blur', removeIframe);-->
}
