<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: login.php');
    exit();
}

require_once 'admin/config/database.php';

// Format currency display - currency field now contains the actual symbol
function formatCurrency($amount, $currencySymbol) {
    return $currencySymbol . number_format($amount, 2);
}

$database = new Database();
$conn = $database->getConnection();

// Get user data
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Check if user exists, if not redirect to login
if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit();
}

// Initialize variables
$transfer_success = false;
$transfer_error = '';
$form_data = [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount'] ?? 0);
    $beneficiary_account_name = trim($_POST['beneficiary_account_name'] ?? '');
    $beneficiary_account_number = trim($_POST['beneficiary_account_number'] ?? '');
    $bank_name = trim($_POST['bank_name'] ?? '');
    $bank_address = trim($_POST['bank_address'] ?? '');
    $account_type = $_POST['account_type'] ?? 'Savings';
    $swift_code = trim($_POST['swift_code'] ?? '');
    $iban = trim($_POST['iban'] ?? '');
    $transaction_pin = trim($_POST['transaction_pin'] ?? '');
    $note = trim($_POST['note'] ?? '');
    
    // Validation
    $errors = [];
    
    if (empty($beneficiary_account_name)) {
        $errors[] = "Beneficiary account name is required";
    }
    
    if (empty($beneficiary_account_number)) {
        $errors[] = "Beneficiary account number is required";
    }
    
    if (empty($bank_name)) {
        $errors[] = "Bank name is required";
    }
    
    if (empty($bank_address)) {
        $errors[] = "Bank address is required";
    }
    
    if (empty($swift_code)) {
        $errors[] = "SWIFT code is required";
    } else {
        // Clean the SWIFT code - remove any spaces and ensure uppercase
        $swift_code = strtoupper(trim($swift_code));
        
        // Check length first
        if (strlen($swift_code) !== 8 && strlen($swift_code) !== 11) {
            $errors[] = "SWIFT code must be exactly 8 or 11 characters (e.g., CHASUS33 or CHASUS33XXX). You entered: '" . $swift_code . "' (" . strlen($swift_code) . " characters)";
        } elseif (!preg_match('/^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/', $swift_code)) {
            $errors[] = "SWIFT code format is invalid. Must be 6 letters + 2 alphanumeric + optional 3 alphanumeric. You entered: '" . $swift_code . "'";
        }
    }
    
    if (empty($iban)) {
        $errors[] = "IBAN is required";
    } elseif (strlen($iban) < 15 || strlen($iban) > 34) {
        $errors[] = "IBAN must be between 15 and 34 characters";
    }
    
    if (empty($transaction_pin)) {
        $errors[] = "Transaction PIN is required";
    } elseif (!preg_match('/^[0-9]{4}$/', $transaction_pin)) {
        $errors[] = "Transaction PIN must be 4 digits";
    }
    
    if ($amount <= 0) {
        $errors[] = "Amount must be greater than 0";
    } elseif ($amount > $user['balance']) {
        $errors[] = "Insufficient balance";
    } elseif ($amount > 50000) {
        $errors[] = "Maximum transfer amount is " . formatCurrency(50000, $_SESSION['currency'] ?? '$');
    }
    
    if (empty($errors)) {
        try {
            // Start transaction
            $conn->beginTransaction();
            
            // Create transfer record
            $reference_number = 'TFR' . str_pad(mt_rand(1, 9999), 3, '0', STR_PAD_LEFT);
            $stmt = $conn->prepare("INSERT INTO transfers (
                user_id, amount, beneficiary_account_name, beneficiary_account_number,
                bank_name, bank_address, account_type, swift_code, iban,
                transaction_pin, note, reference_number, transfer_status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending')");
            
            $stmt->execute([
                $user_id, $amount, $beneficiary_account_name, $beneficiary_account_number,
                $bank_name, $bank_address, $account_type, $swift_code, $iban,
                $transaction_pin, $note, $reference_number
            ]);
            
            $transfer_id = $conn->lastInsertId();
            
            // Commit transaction
            $conn->commit();
            
            // Redirect to IMF verification
            $_SESSION['transfer_id'] = $transfer_id;
            header('Location: transfer-verify-imf.php');
            exit();
            
        } catch (Exception $e) {
            $conn->rollBack();
            $transfer_error = "Transfer request failed. Please try again.";
        }
    } else {
        $transfer_error = implode('<br>', $errors);
    }
    
    // Store form data for repopulation
    $form_data = [
        'amount' => $amount,
        'beneficiary_account_name' => $beneficiary_account_name,
        'beneficiary_account_number' => $beneficiary_account_number,
        'bank_name' => $bank_name,
        'bank_address' => $bank_address,
        'account_type' => $account_type,
        'swift_code' => $swift_code,
        'iban' => $iban,
        'transaction_pin' => $transaction_pin,
        'note' => $note
    ];
}

// Get recent transfers for this user
$stmt = $conn->prepare("SELECT * FROM transfers WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$stmt->execute([$user_id]);
$recent_transfers = $stmt->fetchAll();

// Get general settings for site name
$siteName = 'TrustBNK';
try {
    $stmt = $conn->prepare("SELECT site_name FROM general_settings WHERE id = 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings && $settings['site_name']) {
        $siteName = $settings['site_name'];
    }
} catch (Exception $e) {
    // Use default site name if database query fails
    $siteName = 'TrustBNK';
}

$database->closeConnection();

// Get current date and time
$current_date = date('l, F j, Y');
$current_time = date('H:i:s');
$greeting = 'Good Morning';
$hour = (int)date('H');
if ($hour >= 12 && $hour < 17) {
    $greeting = 'Good Afternoon';
} elseif ($hour >= 17) {
    $greeting = 'Good Evening';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transfer Funds - <?php echo htmlspecialchars($siteName); ?> Credit</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Google Translator -->
    <script type="text/javascript">
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({
                pageLanguage: 'en',
                includedLanguages: 'en,es,fr,de,it,pt,ru,ja,ko,zh-CN,zh-TW,ar,hi',
                layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
                autoDisplay: false
            }, 'google_translate_element');
        }
    </script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    <style>
        .transfer-container {
            max-width: 1000px;
            margin: 0 auto;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .page-header .header-content h1 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 2rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header .header-content h1 i {
            color: #667eea;
        }

        .page-header .header-content p {
            color: #5a6c7d;
            margin: 0;
            font-size: 1.1rem;
        }

        .transfer-form {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
            margin-bottom: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h3 {
            color: #2c3e50;
            margin: 0 0 20px 0;
            font-size: 1.3rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-section h3 i {
            color: #667eea;
        }

        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }

        .form-group label .required {
            color: #dc3545;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 12px 15px;
            border: 2px solid #e0e6ed;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
            font-family: inherit;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .transfer-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
        }

        .btn-transfer {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 40px;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.3s ease;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .btn-transfer:hover {
            transform: translateY(-2px);
        }

        .btn-cancel {
            background: #6c757d;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .btn-cancel:hover {
            background: #5a6268;
        }

        .balance-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            text-align: center;
        }

        .balance-info h3 {
            margin: 0 0 10px 0;
            font-size: 1.2rem;
            font-weight: 600;
        }

        .balance-amount {
            font-size: 2.5rem;
            font-weight: 700;
            margin: 0;
        }

        .recent-transfers {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .recent-transfers h3 {
            color: #2c3e50;
            margin: 0 0 20px 0;
            font-size: 1.3rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .recent-transfers h3 i {
            color: #667eea;
        }

        .transfer-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .transfer-item:last-child {
            border-bottom: none;
        }

        .transfer-details h4 {
            color: #2c3e50;
            margin: 0 0 5px 0;
            font-size: 1rem;
            font-weight: 600;
        }

        .transfer-details p {
            color: #6c757d;
            margin: 0;
            font-size: 0.9rem;
        }

        .transfer-amount {
            font-weight: 700;
            color: #dc3545;
            font-size: 1.1rem;
        }

        .transfer-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .transfer-status.pending {
            background: #fff3cd;
            color: #856404;
        }

        .transfer-status.completed {
            background: #d4edda;
            color: #155724;
        }

        .empty-transfers {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }

        .empty-transfers i {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #dee2e6;
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .transfer-actions {
                flex-direction: column;
                align-items: stretch;
            }
            
            .balance-amount {
                font-size: 2rem;
            }
        }
        
        /* Google Translator Styles - Fixed Position Bottom */
        .translator-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 50px;
            padding: 10px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;
        }
        
        .translator-container:hover {
            background: rgba(255, 255, 255, 1);
            box-shadow: 0 12px 35px rgba(0, 0, 0, 0.2);
            transform: scale(1.05);
        }
        
        .goog-te-gadget {
            font-family: 'Inter', sans-serif !important;
        }
        
        .goog-te-gadget-simple {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            border: none !important;
            border-radius: 25px !important;
            padding: 12px 20px !important;
            font-size: 0.9rem !important;
            color: white !important;
            cursor: pointer !important;
            transition: all 0.3s ease !important;
            font-weight: 600 !important;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
        }
        
        .goog-te-gadget-simple:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%) !important;
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
            transform: translateY(-2px) !important;
        }
        
        .goog-te-gadget-simple .goog-te-menu-value span:first-child {
            color: white !important;
        }
        
        .goog-te-gadget-simple .goog-te-menu-value span:first-child:after {
            content: " 🌐" !important;
        }
        
        .goog-te-banner-frame {
            display: none !important;
        }
        
        .goog-te-menu2 {
            background: white !important;
            border: 1px solid #ddd !important;
            border-radius: 12px !important;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2) !important;
            margin-top: 10px !important;
            overflow: hidden !important;
        }
        
        .goog-te-menu2-item {
            padding: 12px 20px !important;
            border-bottom: 1px solid #f0f0f0 !important;
            transition: all 0.3s ease !important;
        }
        
        .goog-te-menu2-item:hover {
            background: #f8f9fa !important;
            padding-left: 25px !important;
        }
        
        .goog-te-menu2-item:last-child {
            border-bottom: none !important;
        }
        
        @media (max-width: 768px) {
            .translator-container {
                bottom: 15px;
                right: 15px;
                padding: 8px;
            }
            
            .goog-te-gadget-simple {
                padding: 10px 16px !important;
                font-size: 0.8rem !important;
            }
        }
        
        @media (max-width: 480px) {
            .translator-container {
                bottom: 10px;
                right: 10px;
                padding: 6px;
            }
            
            .goog-te-gadget-simple {
                padding: 8px 12px !important;
                font-size: 0.75rem !important;
            }
        }
    </style>
</head>
<body class="dashboard-page">
    <!-- Top Header Bar -->
    <div class="dashboard-header">
        <div class="header-left">
            <div class="current-balance">
                <span class="balance-label">Current Balance</span>
                <span class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></span>
            </div>
        </div>
        <div class="header-center">
            <div class="current-date"><?php echo $current_date; ?></div>
        </div>
        <div class="header-right">
            <div class="header-actions">
                <button class="notification-btn">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge">3</span>
                </button>
                <div class="user-profile">
                    <div class="user-avatar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <span class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></span>
                        <span class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="kyc-badge">KYC Verified</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="fas fa-bars"></i>
        </button>
        
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        
        <!-- Sidebar -->
        <aside class="dashboard-sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-emblem">
                        <span class="logo-t">T</span>
                        <span class="logo-b">B</span>
                    </div>
                    <div class="logo-text">
                        <div class="logo-main"><?php echo htmlspecialchars($siteName); ?></div>
                        <div class="logo-sub">Credit</div>
                    </div>
                </div>
            </div>
            
            <div class="user-profile-sidebar">
                <div class="user-avatar-sidebar">
                    <?php if ($user['profile_photo']): ?>
                        <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                    <?php else: ?>
                        <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></div>
                    <span class="kyc-badge">KYC Verified</span>
                </div>
                <div class="profile-actions">
                    <a href="profile.php" class="btn-profile">
                        <i class="fas fa-user"></i> Profile
                    </a>
                    <a href="logout.php" class="btn-logout">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <h3>Main Menu</h3>
                    <ul>
                        <li><a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a></li>
                        <li><a href="transactions.php"><i class="fas fa-exchange-alt"></i> Transactions</a></li>
                        <li><a href="transfer.php" class="active"><i class="fas fa-paper-plane"></i> Transfer Funds</a></li>
                        <li><a href="cards.php"><i class="fas fa-credit-card"></i> Cards</a></li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>Services</h3>
                    <ul>
                        <li><a href="loan-request.php"><i class="fas fa-hand-holding-usd"></i> Loan Request</a></li>
                        <li><a href="loan-history.php"><i class="fas fa-history"></i> Loan History</a></li>
                        <li><a href="irs-refund.php"><i class="fas fa-file-invoice-dollar"></i> IRS Refund</a></li>
                        <li><a href="apply-card.php"><i class="fas fa-id-card"></i> Apply for Card</a></li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="support-info">
                    <h4>Need Help?</h4>
                    <p>Contact our 24/7 support team</p>
                    <a href="mailto:support@trustbeamcredit.com" class="support-link">
                        <i class="fas fa-envelope"></i> support@trustbeamcredit.com
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="dashboard-main">
            <div class="transfer-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div class="header-content">
                        <h1><i class="fas fa-paper-plane"></i> Transfer Funds</h1>
                        <p>Securely transfer funds to any bank account worldwide</p>
                    </div>
                </div>

                <?php if ($transfer_success): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        Transfer initiated successfully! Your funds will be processed within 24 hours.
                    </div>
                <?php endif; ?>

                <?php if ($transfer_error): ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo $transfer_error; ?>
                    </div>
                <?php endif; ?>

                <!-- Balance Info -->
                <div class="balance-info">
                    <h3>Available Balance</h3>
                    <div class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></div>
                </div>

                <!-- Transfer Form -->
                <form method="POST" class="transfer-form">
                    <div class="form-section">
                        <h3><i class="fas fa-user"></i> Beneficiary Information</h3>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="beneficiary_account_name">Beneficiary Account Name <span class="required">*</span></label>
                                <input type="text" id="beneficiary_account_name" name="beneficiary_account_name" required
                                       value="<?php echo htmlspecialchars($form_data['beneficiary_account_name'] ?? ''); ?>"
                                       placeholder="Enter beneficiary's full name">
                            </div>
                            <div class="form-group">
                                <label for="beneficiary_account_number">Account Number <span class="required">*</span></label>
                                <input type="text" id="beneficiary_account_number" name="beneficiary_account_number" required
                                       value="<?php echo htmlspecialchars($form_data['beneficiary_account_number'] ?? ''); ?>"
                                       placeholder="Enter account number">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="account_type">Account Type <span class="required">*</span></label>
                                <select id="account_type" name="account_type" required>
                                    <option value="Savings" <?php echo ($form_data['account_type'] ?? 'Savings') === 'Savings' ? 'selected' : ''; ?>>Savings</option>
                                    <option value="Current" <?php echo ($form_data['account_type'] ?? '') === 'Current' ? 'selected' : ''; ?>>Current</option>
                                    <option value="Business" <?php echo ($form_data['account_type'] ?? '') === 'Business' ? 'selected' : ''; ?>>Business</option>
                                    <option value="Premium" <?php echo ($form_data['account_type'] ?? '') === 'Premium' ? 'selected' : ''; ?>>Premium</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="transaction_pin">Transaction PIN <span class="required">*</span></label>
                                <input type="password" id="transaction_pin" name="transaction_pin" required maxlength="4"
                                       value="<?php echo htmlspecialchars($form_data['transaction_pin'] ?? ''); ?>"
                                       placeholder="Enter 4-digit PIN"
                                       pattern="[0-9]{4}">
                            </div>
                        </div>
                    </div>

                    <div class="form-section">
                        <h3><i class="fas fa-university"></i> Bank Information</h3>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="bank_name">Bank Name <span class="required">*</span></label>
                                <input type="text" id="bank_name" name="bank_name" required
                                       value="<?php echo htmlspecialchars($form_data['bank_name'] ?? ''); ?>"
                                       placeholder="Enter bank name">
                            </div>
                            <div class="form-group">
                                <label for="swift_code">SWIFT Code <span class="required">*</span></label>
                                <input type="text" id="swift_code" name="swift_code" required maxlength="11"
                                       value="<?php echo htmlspecialchars($form_data['swift_code'] ?? ''); ?>"
                                       placeholder="e.g., CHASUS33 or CHASUS33XXX"
                                       style="text-transform: uppercase;">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="iban">IBAN <span class="required">*</span></label>
                                <input type="text" id="iban" name="iban" required maxlength="34"
                                       value="<?php echo htmlspecialchars($form_data['iban'] ?? ''); ?>"
                                       placeholder="International Bank Account Number"
                                       style="text-transform: uppercase;">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="bank_address">Bank Address <span class="required">*</span></label>
                            <textarea id="bank_address" name="bank_address" required rows="3"
                                      placeholder="Enter complete bank address"><?php echo htmlspecialchars($form_data['bank_address'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="form-section">
                        <h3><i class="fas fa-dollar-sign"></i> Transfer Details</h3>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="amount">Amount <span class="required">*</span></label>
                                <input type="number" id="amount" name="amount" required min="1" max="50000" step="0.01"
                                       value="<?php echo htmlspecialchars($form_data['amount'] ?? ''); ?>"
                                       placeholder="Enter amount to transfer">
                                <small style="color: #6c757d; margin-top: 5px; display: block;">
                                    Maximum transfer: <?php echo formatCurrency(50000, $_SESSION['currency'] ?? '$'); ?>
                                </small>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="note">Transfer Note</label>
                            <textarea id="note" name="note" rows="3"
                                      placeholder="Optional note for this transfer"><?php echo htmlspecialchars($form_data['note'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="transfer-actions">
                        <button type="submit" class="btn-transfer">
                            <i class="fas fa-paper-plane"></i> Send Transfer
                        </button>
                        <a href="dashboard.php" class="btn-cancel">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>

                <!-- Recent Transfers -->
                <?php if (!empty($recent_transfers)): ?>
                    <div class="recent-transfers">
                        <h3><i class="fas fa-history"></i> Recent Transfers</h3>
                        <?php foreach ($recent_transfers as $transfer): ?>
                            <div class="transfer-item">
                                <div class="transfer-details">
                                    <h4><?php echo htmlspecialchars($transfer['beneficiary_account_name']); ?></h4>
                                    <p><?php echo htmlspecialchars($transfer['bank_name']); ?> - <?php echo htmlspecialchars($transfer['beneficiary_account_number']); ?></p>
                                    <small><?php echo date('M d, Y H:i A', strtotime($transfer['created_at'])); ?></small>
                                    <?php if ($transfer['note']): ?>
                                        <br><small style="color: #6c757d;"><em><?php echo htmlspecialchars($transfer['note']); ?></em></small>
                                    <?php endif; ?>
                                </div>
                                <div style="text-align: right;">
                                    <div class="transfer-amount">-<?php echo formatCurrency($transfer['amount'], $_SESSION['currency'] ?? '$'); ?></div>
                                    <div class="transfer-status <?php echo strtolower(str_replace('_', '-', $transfer['transfer_status'])); ?>">
                                        <?php echo htmlspecialchars(str_replace('_', ' ', $transfer['transfer_status'])); ?>
                                    </div>
                                    <small style="color: #6c757d; display: block; margin-top: 5px;">Ref: <?php echo htmlspecialchars($transfer['reference_number']); ?></small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <script>
        // Mobile menu toggle
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebar = document.querySelector('.dashboard-sidebar');
            const overlay = document.getElementById('sidebarOverlay');

            mobileMenuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('active');
                overlay.classList.toggle('active');
            });

            overlay.addEventListener('click', function() {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            });

            // Form validation
            const form = document.querySelector('.transfer-form');
            const amountInput = document.getElementById('amount');
            const swiftCodeInput = document.getElementById('swift_code');
            const ibanInput = document.getElementById('iban');
            const pinInput = document.getElementById('transaction_pin');
            const balance = <?php echo $user['balance']; ?>;
            const currency = '<?php echo $_SESSION['currency'] ?? '$'; ?>';

            // SWIFT code validation
            swiftCodeInput.addEventListener('input', function() {
                // Remove spaces and convert to uppercase
                this.value = this.value.replace(/\s+/g, '').toUpperCase();
            });

            // IBAN validation
            ibanInput.addEventListener('input', function() {
                this.value = this.value.toUpperCase();
            });

            // PIN validation
            pinInput.addEventListener('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '');
                if (this.value.length > 4) {
                    this.value = this.value.slice(0, 4);
                }
            });

            form.addEventListener('submit', function(e) {
                const amount = parseFloat(amountInput.value);
                const swiftCode = swiftCodeInput.value;
                const iban = ibanInput.value;
                const pin = pinInput.value;
                
                if (amount > balance) {
                    e.preventDefault();
                    alert('Insufficient balance. Available balance: ' + currency + balance.toFixed(2));
                    return false;
                }
                
                if (amount > 50000) {
                    e.preventDefault();
                    alert('Maximum transfer amount is ' + currency + '50,000.00');
                    return false;
                }

                // Clean the SWIFT code
                swiftCode = swiftCode.replace(/\s+/g, '').toUpperCase();
                
                if (swiftCode.length !== 8 && swiftCode.length !== 11) {
                    e.preventDefault();
                    alert('SWIFT code must be exactly 8 or 11 characters. You entered: "' + swiftCode + '" (' + swiftCode.length + ' characters)');
                    return false;
                }
                
                if (!/^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/.test(swiftCode)) {
                    e.preventDefault();
                    alert('SWIFT code format is invalid. Must be 6 letters + 2 alphanumeric + optional 3 alphanumeric. You entered: "' + swiftCode + '"');
                    return false;
                }

                if (iban.length < 15 || iban.length > 34) {
                    e.preventDefault();
                    alert('IBAN must be between 15 and 34 characters');
                    return false;
                }

                if (!/^[0-9]{4}$/.test(pin)) {
                    e.preventDefault();
                    alert('Transaction PIN must be exactly 4 digits');
                    return false;
                }
            });
        });
    </script>
    <script src="assets/js/logout-confirmation.js"></script>
    
    <!-- Fixed Google Translator -->
    <div id="google_translate_element" class="translator-container"></div>
</body>
</html>