// Transfer Page JavaScript - Clean Version
// This handles all transfer functionality without conflicts

document.addEventListener('DOMContentLoaded', function() {
    console.log('Transfer page loaded - initializing...');
    initTransferPage();
});

function initTransferPage() {
    console.log('Initializing transfer page...');
    
    // Initialize form validation
    initFormValidation();
    
    // Initialize amount formatting
    initAmountFormatting();
    
    // Initialize transaction PIN toggle
    initTransactionPinToggle();
    
    // Initialize real-time validation
    initRealTimeValidation();
    
    console.log('Transfer page initialization complete');
}

function initFormValidation() {
    const transferForm = document.querySelector('.transfer-form-content');
    if (!transferForm) {
        console.log('Transfer form not found');
        return;
    }
    
    console.log('Setting up form validation...');
    
    transferForm.addEventListener('submit', function(e) {
        console.log('Form submission detected');
        
        // Always prevent default to handle manually
        e.preventDefault();
        
        if (!validateTransferForm()) {
            console.log('Form validation failed - preventing submission');
            return false;
        }
        
        console.log('Form validation passed - showing loading state');
        showLoadingState();
        
        // Submit form data via AJAX
        submitTransferForm(transferForm);
    });
}

function submitTransferForm(form) {
    console.log('Submitting transfer form via AJAX...');
    
    // Get form data
    const formData = new FormData(form);
    
    // Create AJAX request
    fetch('transfer.php', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        console.log('Response received:', response);
        
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return response.json();
        } else {
            // If not JSON, treat as HTML response (likely an error page)
            throw new Error('Invalid response format');
        }
    })
    .then(data => {
        console.log('AJAX response data:', data);
        
        if (data.success) {
            console.log('Transfer initiated successfully - redirecting to IMF step...');
            showSuccessMessage(data.message);
            
            // Redirect to show the IMF verification step
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            console.log('Transfer failed:', data.error);
            showErrorMessage(data.error || 'Transfer failed. Please try again.');
            hideLoadingState();
        }
    })
    .catch(error => {
        console.error('AJAX error:', error);
        
        // Handle different types of errors
        if (error.message === 'Invalid response format') {
            showErrorMessage('Server error. Please try again.');
        } else {
            showErrorMessage('Network error. Please check your connection and try again.');
        }
        
        hideLoadingState();
    });
}

function validateTransferForm() {
    console.log('Validating transfer form...');
    
    const amount = document.getElementById('amount');
    const beneficiaryName = document.getElementById('beneficiary_account_name');
    const beneficiaryAccount = document.getElementById('beneficiary_account_number');
    const bankName = document.getElementById('bank_name');
    const bankAddress = document.getElementById('bank_address');
    const accountType = document.getElementById('account_type');
    const swiftCode = document.getElementById('swift_code');
    const iban = document.getElementById('iban');
    const transactionPin = document.getElementById('transaction_pin');
    
    // Clear previous error messages
    clearErrorMessages();
    
    let isValid = true;
    
    // Validate amount
    if (!amount || !amount.value || parseFloat(amount.value) <= 0) {
        showFieldError('amount', 'Please enter a valid amount');
        isValid = false;
    }
    
    // Validate beneficiary name
    if (!beneficiaryName || !beneficiaryName.value.trim()) {
        showFieldError('beneficiary_account_name', 'Please enter beneficiary name');
        isValid = false;
    }
    
    // Validate beneficiary account number
    if (!beneficiaryAccount || !beneficiaryAccount.value.trim()) {
        showFieldError('beneficiary_account_number', 'Please enter beneficiary account number');
        isValid = false;
    }
    
    // Validate bank name
    if (!bankName || !bankName.value.trim()) {
        showFieldError('bank_name', 'Please enter bank name');
        isValid = false;
    }
    
    // Validate bank address
    if (!bankAddress || !bankAddress.value.trim()) {
        showFieldError('bank_address', 'Please enter bank address');
        isValid = false;
    }
    
    // Validate account type
    if (!accountType || !accountType.value) {
        showFieldError('account_type', 'Please select account type');
        isValid = false;
    }
    
    // Validate SWIFT code
    if (!swiftCode || !swiftCode.value.trim()) {
        showFieldError('swift_code', 'Please enter SWIFT code');
        isValid = false;
    }
    
    // Validate IBAN
    if (!iban || !iban.value.trim()) {
        showFieldError('iban', 'Please enter IBAN');
        isValid = false;
    }
    
    // Validate transaction PIN
    if (!transactionPin || !transactionPin.value || transactionPin.value.length !== 4) {
        showFieldError('transaction_pin', 'Please enter a valid 4-digit PIN');
        isValid = false;
    }
    
    console.log('Form validation result:', isValid);
    return isValid;
}

function showFieldError(fieldId, message) {
    const field = document.getElementById(fieldId);
    if (!field) return;
    
    // Remove existing error
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    
    // Add error message
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.style.color = '#dc3545';
    errorDiv.style.fontSize = '0.875rem';
    errorDiv.style.marginTop = '5px';
    errorDiv.textContent = message;
    
    field.parentNode.appendChild(errorDiv);
    field.style.borderColor = '#dc3545';
}

function clearErrorMessages() {
    // Remove all error messages
    const errorMessages = document.querySelectorAll('.field-error');
    errorMessages.forEach(error => error.remove());
    
    // Reset border colors
    const inputs = document.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        input.style.borderColor = '';
    });
}

function initAmountFormatting() {
    const amountInput = document.getElementById('amount');
    if (!amountInput) return;
    
    amountInput.addEventListener('input', function(e) {
        let value = e.target.value;
        
        // Remove non-numeric characters except decimal point
        value = value.replace(/[^0-9.]/g, '');
        
        // Ensure only one decimal point
        const parts = value.split('.');
        if (parts.length > 2) {
            value = parts[0] + '.' + parts.slice(1).join('');
        }
        
        // Limit to 2 decimal places
        if (parts.length === 2 && parts[1].length > 2) {
            value = parts[0] + '.' + parts[1].substring(0, 2);
        }
        
        e.target.value = value;
    });
}

function initTransactionPinToggle() {
    const pinInput = document.getElementById('transaction_pin');
    if (!pinInput) return;
    
    // Create toggle button
    const toggleBtn = document.createElement('button');
    toggleBtn.type = 'button';
    toggleBtn.className = 'pin-toggle';
    toggleBtn.innerHTML = '<i class="fas fa-eye"></i>';
    toggleBtn.style.position = 'absolute';
    toggleBtn.style.right = '10px';
    toggleBtn.style.top = '50%';
    toggleBtn.style.transform = 'translateY(-50%)';
    toggleBtn.style.background = 'none';
    toggleBtn.style.border = 'none';
    toggleBtn.style.cursor = 'pointer';
    toggleBtn.style.color = '#6c757d';
    
    // Position the input container
    const pinContainer = pinInput.parentNode;
    pinContainer.style.position = 'relative';
    
    // Add toggle button
    pinContainer.appendChild(toggleBtn);
    
    // Toggle functionality
    toggleBtn.addEventListener('click', function() {
        if (pinInput.type === 'password') {
            pinInput.type = 'text';
            toggleBtn.innerHTML = '<i class="fas fa-eye-slash"></i>';
        } else {
            pinInput.type = 'password';
            toggleBtn.innerHTML = '<i class="fas fa-eye"></i>';
        }
    });
}

function initRealTimeValidation() {
    const inputs = document.querySelectorAll('input, select, textarea');
    
    inputs.forEach(input => {
        input.addEventListener('blur', function() {
            validateField(this);
        });
        
        input.addEventListener('input', function() {
            // Clear error when user starts typing
            const error = this.parentNode.querySelector('.field-error');
            if (error) {
                error.remove();
                this.style.borderColor = '';
            }
        });
    });
}

function validateField(field) {
    const value = field.value.trim();
    
    switch (field.id) {
        case 'amount':
            if (value && parseFloat(value) <= 0) {
                showFieldError('amount', 'Amount must be greater than 0');
            }
            break;
            
        case 'beneficiary_account_name':
            if (value && value.length < 2) {
                showFieldError('beneficiary_account_name', 'Beneficiary name must be at least 2 characters');
            }
            break;
            
        case 'transaction_pin':
            if (value && value.length !== 4) {
                showFieldError('transaction_pin', 'PIN must be exactly 4 digits');
            }
            break;
    }
}

function showLoadingState() {
    const submitBtn = document.querySelector('button[name="initiate_transfer"]');
    if (!submitBtn) return;
    
    const originalText = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    submitBtn.disabled = true;
    
    // Store original text for restoration
    submitBtn.dataset.originalText = originalText;
}

function hideLoadingState() {
    const submitBtn = document.querySelector('button[name="initiate_transfer"]');
    if (!submitBtn) return;
    
    const originalText = submitBtn.dataset.originalText || 'Continue to Transfer';
    
    submitBtn.innerHTML = originalText;
    submitBtn.disabled = false;
}

function showSuccessMessage(message) {
    const successDiv = document.createElement('div');
    successDiv.className = 'alert alert-success';
    successDiv.innerHTML = `
        <i class="fas fa-check-circle"></i>
        ${message}
    `;
    
    const form = document.querySelector('.transfer-form');
    if (form) {
        form.parentNode.insertBefore(successDiv, form);
        
        // Remove after 5 seconds
        setTimeout(() => {
            successDiv.remove();
        }, 5000);
    }
}

function showErrorMessage(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'alert alert-error';
    errorDiv.innerHTML = `
        <i class="fas fa-exclamation-circle"></i>
        ${message}
    `;
    
    const form = document.querySelector('.transfer-form');
    if (form) {
        form.parentNode.insertBefore(errorDiv, form);
        
        // Remove after 5 seconds
        setTimeout(() => {
            errorDiv.remove();
        }, 5000);
    }
}

// Utility functions
function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

function formatDate(date) {
    return new Date(date).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });
}

// Initialize verification forms
function initVerificationForms() {
    console.log('Initializing verification forms...');
    
    // IMF verification form
    const imfForm = document.querySelector('form[action=""][method="POST"]');
    if (imfForm && imfForm.querySelector('input[name="verify_imf"]')) {
        imfForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleVerificationStep('imf');
        });
    }
    
    // SWIFT verification form
    const swiftForm = document.querySelector('form[action=""][method="POST"]');
    if (swiftForm && swiftForm.querySelector('input[name="verify_swift"]')) {
        swiftForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleVerificationStep('swift');
        });
    }
    
    // COT verification form
    const cotForm = document.querySelector('form[action=""][method="POST"]');
    if (cotForm && cotForm.querySelector('input[name="verify_cot"]')) {
        cotForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleVerificationStep('cot');
        });
    }
}

function handleVerificationStep(step) {
    console.log('Handling verification step:', step);
    
    const form = document.querySelector('.verification-form-content');
    if (!form) return;
    
    const formData = new FormData(form);
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    // Show loading state
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying...';
    submitBtn.disabled = true;
    
    // Submit via AJAX
    fetch('transfer.php', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return response.json();
        } else {
            throw new Error('Invalid response format');
        }
    })
    .then(data => {
        console.log('Verification response:', data);
        
        if (data.success) {
            showSuccessMessage(data.message);
            
            // Redirect to next step or completion
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            showErrorMessage(data.error || 'Verification failed. Please try again.');
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Verification error:', error);
        showErrorMessage('Network error. Please try again.');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

// Update initialization to include verification forms
function initTransferPage() {
    console.log('Initializing transfer page...');
    
    // Initialize form validation
    initFormValidation();
    
    // Initialize amount formatting
    initAmountFormatting();
    
    // Initialize transaction PIN toggle
    initTransactionPinToggle();
    
    // Initialize real-time validation
    initRealTimeValidation();
    
    // Initialize verification forms
    initVerificationForms();
    
    console.log('Transfer page initialization complete');
}

// Debug logging
console.log('Transfer.js loaded successfully');
console.log('Available functions:', Object.keys(window).filter(key => typeof window[key] === 'function' && key.startsWith('init')));
