<?php
// Disable HTTP caching
header("Expires: Thu, 19 Nov 1969 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

/**
 * Copy to clipboard with fallback for old Android/WebView
 * @param {string} text - Text to copy
 * @returns {Promise<boolean>} - Success status
 */
function copyToClipboardWithFallback(text) {
    return new Promise((resolve) => {
        // Try modern Clipboard API first
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(() => {
                resolve(true);
            }).catch(() => {
                // Fallback to execCommand
                resolve(fallbackCopyToClipboard(text));
            });
        } else {
            // Use fallback immediately
            resolve(fallbackCopyToClipboard(text));
        }
    });
}

/**
 * Fallback copy using execCommand (for old Android/WebView)
 * @param {string} text - Text to copy
 * @returns {boolean} - Success status
 */
function fallbackCopyToClipboard(text) {
    try {
        if (!text || typeof text !== 'string') {
            if (console && console.error) {
                console.error('Invalid text for copying');
            }
            return false;
        }
        
        var textArea = document.createElement('textarea');
        textArea.value = text;
        // Position off-screen but visible to browser
        // Use absolute positioning for better compatibility with old Android
        textArea.style.position = 'absolute';
        textArea.style.left = '-9999px';
        textArea.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';
        textArea.style.opacity = '0';
        textArea.style.width = '1px';
        textArea.style.height = '1px';
        textArea.style.zIndex = '-1';
        // Set readonly for better compatibility
        textArea.setAttribute('readonly', 'readonly');
        textArea.setAttribute('aria-hidden', 'true');
        textArea.setAttribute('tabindex', '-1');
        
        // Append to body
        var body = document.body || document.getElementsByTagName('body')[0];
        if (!body) {
            return false;
        }
        body.appendChild(textArea);
        
        // Focus and select - try multiple methods for compatibility
        try {
            textArea.focus();
        } catch (focusErr) {
            // Ignore focus errors
        }
        
        try {
            textArea.select();
        } catch (selectErr) {
            // Try alternative selection method
            try {
                if (textArea.setSelectionRange) {
                    textArea.setSelectionRange(0, text.length);
                } else if (textArea.createTextRange) {
                    // IE8 fallback
                    var range = textArea.createTextRange();
                    range.collapse(true);
                    range.moveEnd('character', text.length);
                    range.moveStart('character', 0);
                    range.select();
                }
            } catch (rangeErr) {
                // Last resort - just select all
                try {
                    textArea.select();
                } catch (e) {
                    // Give up
                }
            }
        }
        
        var successful = false;
        try {
            // Try execCommand with different approaches
            if (document.execCommand) {
                successful = document.execCommand('copy');
            }
        } catch (execErr) {
            if (console && console.error) {
                console.error('execCommand failed:', execErr);
            }
        }
        
        // Clean up - use setTimeout for better compatibility
        setTimeout(function() {
            try {
                if (textArea && textArea.parentNode) {
                    textArea.parentNode.removeChild(textArea);
                }
            } catch (cleanupErr) {
                // Ignore cleanup errors
            }
        }, 100);
        
        return successful;
    } catch (err) {
        if (console && console.error) {
            console.error('Fallback copy failed:', err);
        }
        return false;
    }
}

/**
 * Show toast notification
 * @param {string} message - Message to display
 * @param {string} type - 'success' or 'error'
 */
function showToast(message, type = 'success') {
    try {
        if (!message || typeof message !== 'string') {
            console.warn('Invalid toast message');
            return;
        }
        
        // Remove existing toasts
        const existingToasts = document.querySelectorAll('.pago-toast');
        existingToasts.forEach(toast => {
            try {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            } catch (e) {
                // Ignore removal errors
            }
        });
        
        const toast = document.createElement('div');
        toast.className = 'pago-toast pago-toast-' + type;
        toast.textContent = message;
        
        // Mobile-first styles with better cross-browser support
        const bgColor = type === 'success' ? 'rgba(21, 180, 7, 0.95)' : 'rgba(220, 53, 69, 0.95)';
        const isLongMessage = message.length > 50;
        const fontSize = type === 'error' && isLongMessage ? '15px' : (type === 'error' ? '15px' : '14px');
        const padding = isLongMessage ? '16px 20px' : '12px 24px';
        const displayDuration = isLongMessage ? 4000 : 2000;
        
        toast.style.position = 'fixed';
        toast.style.top = '20px';
        toast.style.left = '50%';
        toast.style.transform = 'translateX(-50%)';
        toast.style.backgroundColor = bgColor;
        toast.style.color = 'white';
        toast.style.padding = padding;
        toast.style.borderRadius = '8px';
        toast.style.zIndex = '10000';
        toast.style.fontSize = fontSize;
        toast.style.fontWeight = '500';
        toast.style.maxWidth = '90%';
        toast.style.minWidth = '280px';
        toast.style.textAlign = 'center';
        toast.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease-in-out';
        toast.style.wordWrap = 'break-word';
        toast.style.wordBreak = 'break-word';
        toast.style.lineHeight = '1.4';
        toast.style.webkitFontSmoothing = 'antialiased';
        toast.style.mozOsxFontSmoothing = 'grayscale';
        toast.style.pointerEvents = 'none';
        
        if (!document.body) {
            console.error('Document body not available');
            return;
        }
        
        document.body.appendChild(toast);
        
        // Trigger animation with fallback for old browsers
        try {
            var raf = window.requestAnimationFrame || 
                      window.webkitRequestAnimationFrame || 
                      window.mozRequestAnimationFrame || 
                      window.oRequestAnimationFrame || 
                      window.msRequestAnimationFrame;
            
            if (raf) {
                raf(function() {
                    if (toast && toast.parentNode) {
                        toast.style.opacity = '1';
                    }
                });
            } else {
                // Fallback for browsers without requestAnimationFrame
                setTimeout(function() {
                    if (toast && toast.parentNode) {
                        toast.style.opacity = '1';
                    }
                }, 10);
            }
        } catch (animErr) {
            // Fallback for browsers without requestAnimationFrame
            setTimeout(function() {
                if (toast && toast.parentNode) {
                    toast.style.opacity = '1';
                }
            }, 10);
        }
        
        // Remove after delay (longer for error messages)
        setTimeout(function() {
            if (toast && toast.parentNode) {
                toast.style.opacity = '0';
                setTimeout(function() {
                    try {
                        if (toast && toast.parentNode) {
                            toast.parentNode.removeChild(toast);
                        }
                    } catch (removeErr) {
                        // Ignore removal errors
                    }
                }, 300);
            }
        }, displayDuration);
    } catch (err) {
        console.error('Toast display failed:', err);
    }
}

/**
 * Format phone number for display: (0422) 480-66-60
 * @param {string} phone - Phone number in any format
 * @returns {string} - Formatted phone number
 */
function formatPhoneForDisplay(phone) {
    if (!phone) return '';
    // Extract only digits
    const cleaned = phone.replace(/\D/g, '');
    // Format as (0422) 480-66-60 for 10 or 11 digits
    if (cleaned.length === 10) {
        // 10 digits: (0422) 480-66-6
        return `(${cleaned.substring(0, 4)}) ${cleaned.substring(4, 7)}-${cleaned.substring(7, 9)}-${cleaned.substring(9, 10)}`;
    } else if (cleaned.length === 11) {
        // 11 digits: (0422) 480-66-60
        return `(${cleaned.substring(0, 4)}) ${cleaned.substring(4, 7)}-${cleaned.substring(7, 9)}-${cleaned.substring(9, 11)}`;
    }
    // If not 10 or 11 digits, return original (might be already formatted or different format)
    return phone;
}

/**
 * Get phone number for copying (only digits)
 * @param {string} phone - Phone number in any format
 * @returns {string} - Phone number with only digits
 */
function getPhoneForCopy(phone) {
    if (!phone) return '';
    // Return only digits
    return phone.replace(/\D/g, '');
}

/**
 * Format RIF for display: J406163864 -> J-406163864
 * @param {string} rif - RIF in any format
 * @returns {string} - Formatted RIF (without label, label is shown separately)
 */
function formatRifForDisplay(rif) {
    if (!rif) return '';
    // Extract letter and digits (remove all non-alphanumeric)
    const cleaned = rif.replace(/[^a-zA-Z0-9]/g, '');
    // Match: optional letter (J, V, E, G, etc.) followed by digits
    const match = cleaned.match(/^([A-Za-z])?(\d+)$/);
    if (match) {
        const prefix = match[1] ? match[1].toUpperCase() : '';
        const numbers = match[2];
        return prefix ? `${prefix}-${numbers}` : numbers;
    }
    // If doesn't match pattern, return original
    return rif;
}

/**
 * Get RIF for copying (only digits, no letter)
 * @param {string} rif - RIF in any format
 * @returns {string} - RIF with only digits
 */
function getRifForCopy(rif) {
    if (!rif) return '';
    // Return only digits (remove letter and any formatting)
    return rif.replace(/[^0-9]/g, '');
}

/**
 * Check if RIF is for Juridica (starts with J)
 * @param {string} rif - RIF in any format
 * @returns {boolean} - True if RIF starts with J
 */
function isJuridicaRif(rif) {
    if (!rif) return false;
    // Extract letter and digits (remove all non-alphanumeric)
    const cleaned = rif.replace(/[^a-zA-Z0-9]/g, '');
    // Match: optional letter followed by digits
    const match = cleaned.match(/^([A-Za-z])/);
    return match && match[1].toUpperCase() === 'J';
}

/**
 * Copy text with toast feedback
 * @param {string} text - Text to copy
 * @param {string} successMessage - Success message (default: 'Copiado')
 * @param {string} errorMessage - Error message
 */
async function copyWithToast(text, successMessage = 'Copiado', errorMessage = 'No se pudo copiar. Copia este dato manualmente, por favor.') {
    try {
        const success = await copyToClipboardWithFallback(text);
        if (success) {
            showToast(successMessage, 'success');
            return true;
        } else {
            showToast(errorMessage, 'error');
            return false;
        }
    } catch (err) {
        console.error('Copy operation failed:', err);
        showToast(errorMessage, 'error');
        return false;
    }
}