<?php
session_start();
require_once 'config/database.php';
require_once __DIR__ . '/lib/EmailService.php';
require_once __DIR__ . '/lib/EmailTemplates.php';
use TrustBnk\Admin\Lib\EmailService;
use TrustBnk\Admin\Lib\EmailTemplates;

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $database = new Database();
    $conn = $database->getConnection();
    
    // Validate password
    if (empty($_POST['password'])) {
        $error_message = 'Password is required.';
    } elseif (strlen($_POST['password']) < 6) {
        $error_message = 'Password must be at least 6 characters long.';
    } elseif ($_POST['password'] !== $_POST['confirm_password']) {
        $error_message = 'Passwords do not match.';
    } else {
        try {
        // Generate unique account number if not provided
        $account_number = !empty($_POST['account_number']) ? $_POST['account_number'] : generateAccountNumber();
        
        // Handle file upload
        $profile_photo = '';
        if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = 'uploads/profiles/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
            $file_name = uniqid() . '.' . $file_extension;
            $upload_path = $upload_dir . $file_name;
            
            if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $upload_path)) {
                $profile_photo = $upload_path;
            }
        }
        
        // Hash the password
        $password = $_POST['password'];
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        $stmt = $conn->prepare("INSERT INTO users (
            firstname, middlename, lastname, username, email, password_hash, phone, address,
            date_of_birth, nationality, account_number, swift_code, imf_code,
            cot_code, transaction_pin, account_type, profile_photo, currency, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $_POST['firstname'],
            $_POST['middlename'],
            $_POST['lastname'],
            $_POST['username'],
            $_POST['email'],
            $password_hash,
            $_POST['phone'],
            $_POST['address'],
            $_POST['date_of_birth'],
            $_POST['nationality'],
            $account_number,
            $_POST['swift_code'],
            $_POST['imf_code'],
            $_POST['cot_code'],
            $_POST['transaction_pin'],
            $_POST['account_type'],
            $profile_photo,
            $_POST['currency'],
            'Pending'
        ]);
        
        // Fetch created user details for email
        $newUserId = $conn->lastInsertId();
        $userStmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
        $userStmt->execute([$newUserId]);
        $user = $userStmt->fetch();

        // Prepare and send welcome email
        $settingsGeneralStmt = $conn->query("SELECT * FROM general_settings WHERE id = 1");
        $general = $settingsGeneralStmt->fetch() ?: ['site_name' => 'TrustBank', 'logo_path' => null];
        [$subject, $html] = EmailTemplates::welcome($general, $user);
        $emailService = new EmailService($conn);
        $emailService->sendEmail($user['email'], trim($user['firstname'] . ' ' . $user['lastname']), $subject, $html, 'Welcome', (int)$newUserId, (int)$_SESSION['admin_id']);

        $success_message = 'User created successfully! Account number: ' . $account_number;
        
        // Clear form data
        $_POST = array();
        
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) { // Duplicate entry
            if (strpos($e->getMessage(), 'username')) {
                $error_message = 'Username already exists. Please choose a different one.';
            } elseif (strpos($e->getMessage(), 'email')) {
                $error_message = 'Email already exists. Please use a different email.';
            } elseif (strpos($e->getMessage(), 'account_number')) {
                $error_message = 'Account number already exists. Please use a different one.';
            } else {
                $error_message = 'A user with this information already exists.';
            }
        } else {
            $error_message = 'Error creating user: ' . $e->getMessage();
        }
    }
    
        $database->closeConnection();
    }
}

function generateAccountNumber() {
    return '03' . str_pad(mt_rand(1, 99999999), 8, '0', STR_PAD_LEFT);
}

function generateSwiftCode() {
    return strtoupper(substr(md5(uniqid()), 0, 6));
}

function generateIMFCode() {
    return strtoupper(substr(md5(uniqid()), 0, 6));
}

function generateCOTCode() {
    return strtoupper(substr(md5(uniqid()), 0, 6));
}

function generateTransactionPin() {
    return str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
}

// Get countries list
$countries = [
    'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria',
    'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan',
    'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cabo Verde', 'Cambodia',
    'Cameroon', 'Canada', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Costa Rica', 'Croatia',
    'Cuba', 'Cyprus', 'Czech Republic', 'Democratic Republic of the Congo', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Ecuador', 'Egypt',
    'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon',
    'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana',
    'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel',
    'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Kuwait', 'Kyrgyzstan', 'Laos',
    'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Madagascar', 'Malawi',
    'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova',
    'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands',
    'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'North Korea', 'North Macedonia', 'Norway', 'Oman', 'Pakistan', 'Palau',
    'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia',
    'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia',
    'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Korea', 'South Sudan',
    'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania',
    'Thailand', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda',
    'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam',
    'Yemen', 'Zambia', 'Zimbabwe'
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrustBeam Credit - Create New User</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">
</head>
<body>
    <div class="admin-container">
        <!-- Header -->
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo">TrustBeam Credit</h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search-bar">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Manage users">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar -->
        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li class="active">
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="applications.php">
                            <i class="fas fa-user-friends"></i>
                            <span>New User Application(s)</span>
                        </a>
                    </li>
                    <li>
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Loan Applications</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                            <li><a href="loans.php?status=approved">Approved</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-credit-card"></i>
                            <span>Virtual Cards</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="cards.php">Manage Cards</a></li>
                            <li><a href="cards.php?status=active">Active</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>IRS Refunds</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-user-shield"></i>
                            <span>Administrator(s)</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="admins.php">View All</a></li>
                            <li><a href="create-admin.php">Add New</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="settings.php">General</a></li>
                            <li><a href="security.php">Security</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <div class="page-header">
                <h2>Create A New User</h2>
                <nav class="breadcrumb">
                    <a href="index.php">Dashboard</a> / Create User
                </nav>
            </div>

            <?php if ($success_message): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($success_message); ?>
                </div>
            <?php endif; ?>

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

            <div class="form-container">
                <form method="POST" enctype="multipart/form-data" class="create-user-form" id="createUserForm">
                    <div class="form-row">
                        <!-- Left Column -->
                        <div class="form-column">
                            <div class="form-group">
                                <label for="firstname">Firstname</label>
                                <input type="text" id="firstname" name="firstname" 
                                       value="<?php echo isset($_POST['firstname']) ? htmlspecialchars($_POST['firstname']) : ''; ?>"
                                       placeholder="Enter First Name" required>
                            </div>

                            <div class="form-group">
                                <label for="lastname">Last Name</label>
                                <input type="text" id="lastname" name="lastname" 
                                       value="<?php echo isset($_POST['lastname']) ? htmlspecialchars($_POST['lastname']) : ''; ?>"
                                       placeholder="Enter Last Name" required>
                            </div>

                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" id="email" name="email" 
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>"
                                       placeholder="Enter Email" required>
                            </div>

                            <div class="form-group">
                                <label for="password">Password</label>
                                <div class="password-input">
                                    <input type="password" id="password" name="password" 
                                           placeholder="Enter Password" required>
                                    <button type="button" class="password-toggle" id="passwordToggle">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <small class="form-help">Password will be securely hashed before storage</small>
                                <div class="password-strength" id="passwordStrength" style="display: none;">
                                    <div class="strength-bar">
                                        <div class="strength-fill" id="strengthFill"></div>
                                    </div>
                                    <span class="strength-text" id="strengthText">Weak</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="confirm_password">Confirm Password</label>
                                <div class="password-input">
                                    <input type="password" id="confirm_password" name="confirm_password" 
                                           placeholder="Confirm Password" required>
                                    <button type="button" class="password-toggle" id="confirmPasswordToggle">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <small class="form-help" id="passwordMatch">Passwords must match</small>
                            </div>

                            <div class="form-group">
                                <label for="date_of_birth">Date of birth</label>
                                <div class="date-input">
                                    <input type="text" id="date_of_birth" name="date_of_birth" 
                                           value="<?php echo isset($_POST['date_of_birth']) ? htmlspecialchars($_POST['date_of_birth']) : ''; ?>"
                                           placeholder="mm/dd/yyyy" required>
                                    <i class="fas fa-calendar"></i>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="nationality">Nationality</label>
                                <select id="nationality" name="nationality" required>
                                    <option value="">Select Nationality</option>
                                    <?php foreach ($countries as $country): ?>
                                        <option value="<?php echo htmlspecialchars($country); ?>" 
                                                <?php echo (isset($_POST['nationality']) && $_POST['nationality'] === $country) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($country); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="account_number">Account Number</label>
                                <input type="text" id="account_number" name="account_number" 
                                       value="<?php echo isset($_POST['account_number']) ? htmlspecialchars($_POST['account_number']) : generateAccountNumber(); ?>"
                                       placeholder="Account Number" required>
                            </div>

                            <div class="form-group">
                                <label for="swift_code">SWIFT</label>
                                <input type="text" id="swift_code" name="swift_code" 
                                       value="<?php echo isset($_POST['swift_code']) ? htmlspecialchars($_POST['swift_code']) : generateSwiftCode(); ?>"
                                       placeholder="SWIFT Code" required>
                            </div>

                            <div class="form-group">
                                <label for="transaction_pin">4 Digit Transaction pin</label>
                                <input type="text" id="transaction_pin" name="transaction_pin" 
                                       value="<?php echo isset($_POST['transaction_pin']) ? htmlspecialchars($_POST['transaction_pin']) : generateTransactionPin(); ?>"
                                       placeholder="Transaction PIN" maxlength="4" required>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="form-column">
                            <div class="form-group">
                                <label for="middlename">Middle Name</label>
                                <input type="text" id="middlename" name="middlename" 
                                       value="<?php echo isset($_POST['middlename']) ? htmlspecialchars($_POST['middlename']) : ''; ?>"
                                       placeholder="Enter Middle Name">
                            </div>

                            <div class="form-group">
                                <label for="username">Username</label>
                                <input type="text" id="username" name="username" 
                                       value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                                       placeholder="Enter Username" required>
                            </div>

                            <div class="form-group">
                                <label for="phone">Phone Number</label>
                                <input type="tel" id="phone" name="phone" 
                                       value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>"
                                       placeholder="Enter Phone Number" required>
                            </div>

                            <div class="form-group">
                                <label for="address">Address</label>
                                <textarea id="address" name="address" 
                                          placeholder="Enter Address" required><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
                            </div>

                            <div class="form-group">
                                <label for="account_type">Account Type</label>
                                <select id="account_type" name="account_type" required>
                                    <option value="">Please select Account Type</option>
                                    <option value="Savings" <?php echo (isset($_POST['account_type']) && $_POST['account_type'] === 'Savings') ? 'selected' : ''; ?>>Savings</option>
                                    <option value="Current" <?php echo (isset($_POST['account_type']) && $_POST['account_type'] === 'Current') ? 'selected' : ''; ?>>Current</option>
                                    <option value="Business" <?php echo (isset($_POST['account_type']) && $_POST['account_type'] === 'Business') ? 'selected' : ''; ?>>Business</option>
                                    <option value="Premium" <?php echo (isset($_POST['account_type']) && $_POST['account_type'] === 'Premium') ? 'selected' : ''; ?>>Premium</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="currency">Currency Symbol</label>
                                <input type="text" id="currency" name="currency" 
                                       value="<?php echo isset($_POST['currency']) ? htmlspecialchars($_POST['currency']) : '$'; ?>" 
                                       placeholder="Enter currency symbol (e.g., $, €, £, ¥)" 
                                       maxlength="10" required>
                                <small class="form-help">Enter the currency symbol that will be displayed with the balance (e.g., $, €, £, ¥, R$, HK$)</small>
                            </div>

                            <div class="form-group">
                                <label for="imf_code">IMF</label>
                                <input type="text" id="imf_code" name="imf_code" 
                                       value="<?php echo isset($_POST['imf_code']) ? htmlspecialchars($_POST['imf_code']) : generateIMFCode(); ?>"
                                       placeholder="IMF Code" required>
                            </div>

                            <div class="form-group">
                                <label for="cot_code">COT</label>
                                <input type="text" id="cot_code" name="cot_code" 
                                       value="<?php echo isset($_POST['cot_code']) ? htmlspecialchars($_POST['cot_code']) : generateCOTCode(); ?>"
                                       placeholder="COT Code" required>
                            </div>

                            <div class="form-group">
                                <label for="profile_photo">Upload Profile photo</label>
                                <div class="file-upload">
                                    <input type="file" id="profile_photo" name="profile_photo" accept="image/*">
                                    <label for="profile_photo" class="file-upload-label">
                                        <i class="fas fa-upload"></i>
                                        Choose File
                                    </label>
                                    <span class="file-name">No file chosen</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn-primary">
                            <i class="fas fa-save"></i>
                            Create User
                        </button>
                        <button type="reset" class="btn-secondary">
                            <i class="fas fa-undo"></i>
                            Reset Form
                        </button>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        // File upload display
        document.getElementById('profile_photo').addEventListener('change', function() {
            const fileName = this.files[0] ? this.files[0].name : 'No file chosen';
            document.querySelector('.file-name').textContent = fileName;
        });

        // Date picker functionality
        document.getElementById('date_of_birth').addEventListener('focus', function() {
            this.type = 'date';
        });

        // Password strength checker
        document.getElementById('password').addEventListener('input', function() {
            const password = this.value;
            const strengthDiv = document.getElementById('passwordStrength');
            const strengthFill = document.getElementById('strengthFill');
            const strengthText = document.getElementById('strengthText');
            
            if (password.length === 0) {
                strengthDiv.style.display = 'none';
                return;
            }
            
            strengthDiv.style.display = 'block';
            
            let strength = 0;
            let text = 'Weak';
            let className = 'weak';
            
            if (password.length >= 6) strength += 1;
            if (password.length >= 8) strength += 1;
            if (/[a-z]/.test(password)) strength += 1;
            if (/[A-Z]/.test(password)) strength += 1;
            if (/[0-9]/.test(password)) strength += 1;
            if (/[^A-Za-z0-9]/.test(password)) strength += 1;
            
            if (strength <= 2) {
                text = 'Weak';
                className = 'weak';
            } else if (strength <= 3) {
                text = 'Fair';
                className = 'fair';
            } else if (strength <= 4) {
                text = 'Good';
                className = 'good';
            } else {
                text = 'Strong';
                className = 'strong';
            }
            
            strengthFill.className = 'strength-fill ' + className;
            strengthText.textContent = text;
            
            // Check password match
            checkPasswordMatch();
        });

        // Confirm password checker
        document.getElementById('confirm_password').addEventListener('input', function() {
            checkPasswordMatch();
        });

        function checkPasswordMatch() {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            const passwordMatch = document.getElementById('passwordMatch');
            
            if (confirmPassword.length === 0) {
                passwordMatch.textContent = 'Passwords must match';
                passwordMatch.style.color = '#666';
                return;
            }
            
            if (password === confirmPassword) {
                passwordMatch.textContent = 'Passwords match ✓';
                passwordMatch.style.color = '#2ed573';
            } else {
                passwordMatch.textContent = 'Passwords do not match ✗';
                passwordMatch.style.color = '#ff4757';
            }
        }

        // Password toggle functionality
        function togglePasswordVisibility(inputId, toggleId) {
            const input = document.getElementById(inputId);
            const toggle = document.getElementById(toggleId);
            const icon = toggle.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.className = 'fas fa-eye-slash';
            } else {
                input.type = 'password';
                icon.className = 'fas fa-eye';
            }
        }
        
        document.getElementById('passwordToggle').addEventListener('click', function() {
            togglePasswordVisibility('password', 'passwordToggle');
        });
        
        document.getElementById('confirmPasswordToggle').addEventListener('click', function() {
            togglePasswordVisibility('confirm_password', 'confirmPasswordToggle');
        });

        // Form validation
        document.getElementById('createUserForm').addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password !== confirmPassword) {
                e.preventDefault();
                alert('Passwords do not match. Please correct this before submitting.');
                return false;
            }
            
            if (password.length < 6) {
                e.preventDefault();
                alert('Password must be at least 6 characters long.');
                return false;
            }
        });

        // Auto-generate codes
        document.addEventListener('DOMContentLoaded', function() {
            // Generate random codes if fields are empty
            const swiftCode = document.getElementById('swift_code');
            const imfCode = document.getElementById('imf_code');
            const cotCode = document.getElementById('cot_code');
            const transactionPin = document.getElementById('transaction_pin');
            const accountNumber = document.getElementById('account_number');

            if (!swiftCode.value) swiftCode.value = '<?php echo generateSwiftCode(); ?>';
            if (!imfCode.value) imfCode.value = '<?php echo generateIMFCode(); ?>';
            if (!cotCode.value) cotCode.value = '<?php echo generateCOTCode(); ?>';
            if (!transactionPin.value) transactionPin.value = '<?php echo generateTransactionPin(); ?>';
            if (!accountNumber.value) accountNumber.value = '<?php echo generateAccountNumber(); ?>';
        });
    </script>
</body>
</html>
