<?php
require_once 'includes/auth_check.php';
$page = 'users'; // To keep 'Manage Users' active in the sidebar
require_once '../config/database.php';
require_once '../includes/email_templates.php'; // Include email templates

// Define necessary functions directly in this file
function checkEmailExists($db, $email) {
    $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    return $stmt->fetch() !== false;
}

function checkUsernameExists($db, $username) {
    $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    return $stmt->fetch() !== false;
}

function generateAccountNumber($db) {
    do {
        $accountNumber = date('Y') . mt_rand(100000, 999999);
        $stmt = $db->prepare("SELECT id FROM users WHERE account_number = ?");
        $stmt->execute([$accountNumber]);
    } while ($stmt->fetch());
    
    return $accountNumber;
}

function generateSecurityCodes() {
    return [
        'cot' => strtoupper(bin2hex(random_bytes(3))),
        'imf' => strtoupper(bin2hex(random_bytes(3))),
        'tax' => strtoupper(bin2hex(random_bytes(3)))
    ];
}

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

// --- Handle Form Submission (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Check
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error_message'] = "Invalid security token. Please try again.";
    } else {
        // Sanitize and retrieve form data
        $firstName = trim($_POST['firstName']);
        $lastName = trim($_POST['lastName']);
        $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST['phone']);
        $dob = $_POST['dob'];
        $gender = $_POST['gender'];
        $country = $_POST['country'];
        $address = trim($_POST['address']);
        $city = trim($_POST['city'] ?? '');
        $state = trim($_POST['state'] ?? '');
        $zipCode = trim($_POST['zipCode'] ?? '');
        $ssn = trim($_POST['ssn'] ?? '');
        $mothersMaidenName = trim($_POST['mothersMaidenName'] ?? '');
        
        // Next of kin details
        $kinName = trim($_POST['kinName']);
        $kinRelationship = $_POST['kinRelationship'];
        $kinEmail = filter_var(trim($_POST['kinEmail']), FILTER_SANITIZE_EMAIL);
        $kinPhone = trim($_POST['kinPhone']);
        $kinAddress = trim($_POST['kinAddress']);
        
        // Account details
        $accountType = $_POST['accountType'];
        $currency = $_POST['currency'];
        $employmentStatus = $_POST['employmentStatus'];
        $incomeSource = $_POST['incomeSource'];
        $occupation = trim($_POST['occupation'] ?? '');
        $employer = trim($_POST['employer'] ?? '');
        $initial_balance = filter_input(INPUT_POST, 'initial_balance', FILTER_VALIDATE_FLOAT);
        $status = $_POST['status'];
        $requestDebitCard = $_POST['requestDebitCard'] ?? 'no';
        $onlineBanking = $_POST['onlineBanking'] ?? 'yes';
        
        // Security details
        $username = trim($_POST['username']);
        $password = $_POST['password'];
        $confirmPassword = $_POST['confirmPassword'];
        $pin = $_POST['pin'] ?? '0000'; // Default to 0000 if not provided
        $enableTwoFactor = isset($_POST['enableTwoFactor']) ? 1 : 0;

        // Validation
        if (empty($firstName) || empty($lastName) || empty($email) || empty($username) || empty($password)) {
            $_SESSION['error_message'] = "Please fill in all required fields.";
        } elseif ($password !== $confirmPassword) {
            $_SESSION['error_message'] = "Passwords do not match.";
        } elseif (strlen($password) < 8) {
            $_SESSION['error_message'] = "Password must be at least 8 characters long.";
        } elseif (checkEmailExists($db, $email)) {
            $_SESSION['error_message'] = "An account with this email address already exists.";
        } elseif (checkUsernameExists($db, $username)) {
            $_SESSION['error_message'] = "This username is already taken.";
        } else {
            // Handle profile picture upload
            $profilePicture = '';
            $targetPath = '';
            
            if (isset($_FILES['profilePicture']) && $_FILES['profilePicture']['error'] === 0) {
                $uploadDir = '../uploads/profiles/';
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $allowedTypes = ['image/jpeg', 'image/png'];
                $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
                $mimeType = finfo_file($fileInfo, $_FILES['profilePicture']['tmp_name']);
                finfo_close($fileInfo);

                if (!in_array($mimeType, $allowedTypes)) {
                    $_SESSION['error_message'] = 'Invalid file type. Only JPG and PNG files are allowed.';
                    header("Location: add_user.php");
                    exit;
                }

                if ($_FILES['profilePicture']['size'] > 5 * 1024 * 1024) {
                    $_SESSION['error_message'] = 'File size too large. Maximum size is 5MB.';
                    header("Location: add_user.php");
                    exit;
                }

                $extension = strtolower(pathinfo($_FILES['profilePicture']['name'], PATHINFO_EXTENSION));
                $fileName = uniqid() . '_' . time() . '.' . $extension;
                $targetPath = $uploadDir . $fileName;

                if (!move_uploaded_file($_FILES['profilePicture']['tmp_name'], $targetPath)) {
                    $_SESSION['error_message'] = 'Error uploading profile picture.';
                    header("Location: add_user.php");
                    exit;
                }

                $profilePicture = $fileName;
            }

            // All validation passed, proceed with creating the user
            try {
                $db->beginTransaction();
                error_log('Database transaction started for user creation');

                // 1. Prepare user data
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $hashed_pin = password_hash($pin, PASSWORD_DEFAULT);
                $account_number = generateAccountNumber($db);
                $security_codes = generateSecurityCodes();
                $verificationCode = bin2hex(random_bytes(16));
                $verificationExpiry = date('Y-m-d H:i:s', strtotime('+24 hours'));

                // 2. Create the user record
                $user_stmt = $db->prepare("
                    INSERT INTO users (
                        first_name, last_name, email, phone, date_of_birth, gender, country, address, 
                        city, state, zip_code, ssn, mothers_maiden_name,
                        account_type, currency, username, password, pin, account_number, profile_picture,
                        employment_status, income_source, occupation, employer, status, role, email_verified, 
                        request_debit_card, online_banking, two_factor_enabled,
                        verification_code, verification_expiry, created_at
                    ) VALUES (
                        :firstName, :lastName, :email, :phone, :dob, :gender, :country, :address, 
                        :city, :state, :zipCode, :ssn, :mothersMaidenName,
                        :accountType, :currency, :username, :password, :pin, :account_number, :profilePicture,
                        :employmentStatus, :incomeSource, :occupation, :employer, :status, 'user', 1, 
                        :requestDebitCard, :onlineBanking, :enableTwoFactor,
                        :verificationCode, :verificationExpiry, NOW()
                    )
                ");
                $user_stmt->execute([
                    ':firstName' => $firstName,
                    ':lastName' => $lastName,
                    ':email' => $email,
                    ':phone' => $phone,
                    ':dob' => $dob,
                    ':gender' => $gender,
                    ':country' => $country,
                    ':address' => $address,
                    ':city' => $city,
                    ':state' => $state,
                    ':zipCode' => $zipCode,
                    ':ssn' => $ssn,
                    ':mothersMaidenName' => $mothersMaidenName,
                    ':accountType' => $accountType,
                    ':currency' => $currency,
                    ':username' => $username,
                    ':password' => $hashed_password,
                    ':pin' => $hashed_pin,
                    ':account_number' => $account_number,
                    ':profilePicture' => $profilePicture,
                    ':employmentStatus' => $employmentStatus,
                    ':incomeSource' => $incomeSource,
                    ':occupation' => $occupation,
                    ':employer' => $employer,
                    ':status' => $status,
                    ':requestDebitCard' => $requestDebitCard,
                    ':onlineBanking' => $onlineBanking,
                    ':enableTwoFactor' => $enableTwoFactor,
                    ':verificationCode' => $verificationCode,
                    ':verificationExpiry' => $verificationExpiry
                ]);

                $new_user_id = $db->lastInsertId();
                error_log('User created with ID: ' . $new_user_id);

                // 3. Create the initial account balance record
                $balance_stmt = $db->prepare("INSERT INTO account_balances (user_id, account_number, currency, balance, last_updated) VALUES (?, ?, ?, ?, NOW())");
                $balance_stmt->execute([$new_user_id, $account_number, $currency, $initial_balance ?? 0.00]);
                error_log('Account balance record created');

                // 4. Create the security codes record
                $codes_stmt = $db->prepare("INSERT INTO security_codes (user_id, cot_code, imf_code, tax_code) VALUES (?, ?, ?, ?)");
                $codes_stmt->execute([$new_user_id, $security_codes['cot'], $security_codes['imf'], $security_codes['tax']]);
                error_log('Security codes created');
                
                // 5. Create next_of_kin record
                $kin_stmt = $db->prepare("INSERT INTO next_of_kin (user_id, full_name, relationship, email, phone, address, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                $kin_stmt->execute([$new_user_id, $kinName, $kinRelationship, $kinEmail, $kinPhone, $kinAddress]);
                error_log('Next of kin record created');

                // 6. Create security questions if provided
                if (!empty($_POST['securityQuestion1']) && !empty($_POST['securityAnswer1'])) {
                    $q1_stmt = $db->prepare("INSERT INTO security_questions (user_id, question_key, answer) VALUES (?, ?, ?)");
                    $q1_stmt->execute([$new_user_id, $_POST['securityQuestion1'], $_POST['securityAnswer1']]);
                }
                
                if (!empty($_POST['securityQuestion2']) && !empty($_POST['securityAnswer2'])) {
                    $q2_stmt = $db->prepare("INSERT INTO security_questions (user_id, question_key, answer) VALUES (?, ?, ?)");
                    $q2_stmt->execute([$new_user_id, $_POST['securityQuestion2'], $_POST['securityAnswer2']]);
                }

                // If all queries were successful, commit the transaction
                $db->commit();
                error_log('Database transaction committed successfully');
                
                // Send welcome email with PIN and security codes
                $fullName = $firstName . ' ' . $lastName;
                
                // Try to use the email_templates.php function if available
                $emailSent = false;
                if (function_exists('sendRegistrationEmail')) {
                    $emailSent = sendRegistrationEmail($email, $fullName, $account_number, $verificationCode);
                } else {
                    // Fallback to the local function
                    $emailSent = sendWelcomeEmail($email, $fullName, $username, $account_number, ucfirst($accountType), $security_codes);
                }
                
                $_SESSION['success_message'] = "User '" . htmlspecialchars($username) . "' was created successfully with Account Number: " . $account_number . 
                    ($emailSent ? " and a welcome email was sent." : " but the welcome email could not be sent.");
                
                header("Location: manage_users.php");
                exit;

            } catch (Exception $e) {
                // If any error occurs, roll back all database changes
                $db->rollBack();
                
                // Delete uploaded file if exists
                if (!empty($targetPath) && file_exists($targetPath)) {
                    unlink($targetPath);
                }
                
                error_log("Add User DB Error: " . $e->getMessage());
                $_SESSION['error_message'] = "Failed to create user due to a database error: " . $e->getMessage();
            }
        }
    }
    // Redirect back to the add user page if there was an error
    header("Location: add_user.php");
    exit;
}

// Generate a CSRF token for the form for GET requests
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

include 'includes/header.php';
?>

<style>
:root {
    --primary-color: #4f46e5;
    --primary-light: rgba(79, 70, 229, 0.1);
    --primary-dark: #4338ca;
    --success-color: #10b981;
    --success-light: rgba(16, 185, 129, 0.1);
    --danger-color: #ef4444;
    --danger-light: rgba(239, 68, 68, 0.1);
    --warning-color: #f59e0b;
    --warning-light: rgba(245, 158, 11, 0.1);
    --info-color: #0ea5e9;
    --info-light: rgba(14, 165, 233, 0.1);
    --secondary-color: #6b7280;
    --secondary-light: rgba(107, 114, 128, 0.1);
    --border-color: #e2e8f0;
    --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    --transition-base: all 0.3s ease;
}

/* Main Container Styles */
.content-wrapper {
    padding: 2rem;
    background-color: #f9fafb;
    min-height: calc(100vh - 60px);
}

/* Page Header */
.page-header {
    margin-bottom: 2rem;
}

.page-title {
    font-size: 1.75rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
}

.page-title i {
    margin-right: 0.75rem;
    font-size: 2rem;
    color: var(--primary-color);
}

.page-subtitle {
    color: #64748b;
    font-size: 1rem;
    margin-bottom: 0;
}

/* Card Styles */
.app-card {
    background: white;
    border-radius: 1rem;
    box-shadow: var(--card-shadow);
    border: none;
    overflow: hidden;
    margin-bottom: 2rem;
}

.app-card-header {
    padding: 1.5rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.app-card-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
}

.app-card-title i {
    font-size: 1.5rem;
    margin-right: 0.75rem;
    color: var(--primary-color);
}

.app-card-body {
    padding: 1.5rem;
}

.app-card-footer {
    padding: 1.25rem 1.5rem;
    background-color: #f8fafc;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* Form Wizard Navigation */
.form-wizard-nav {
    display: flex;
    justify-content: space-between;
    position: relative;
    margin-bottom: 2.5rem;
    padding: 0 1rem;
}

.form-wizard-nav::before {
    content: '';
    position: absolute;
    top: 1.25rem;
    left: 0;
    right: 0;
    height: 2px;
    background-color: var(--border-color);
    z-index: 1;
}

.wizard-step {
    position: relative;
    z-index: 2;
    text-align: center;
    width: 25%;
}

.step-icon {
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 50%;
    background-color: white;
    border: 2px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 0.5rem;
    font-weight: 600;
    color: var(--secondary-color);
    transition: var(--transition-base);
}

.wizard-step.active .step-icon {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
    box-shadow: 0 0 0 4px var(--primary-light);
}

.wizard-step.completed .step-icon {
    background-color: var(--success-color);
    border-color: var(--success-color);
    color: white;
}

.step-title {
    font-size: 0.875rem;
    color: var(--secondary-color);
    margin-top: 0.5rem;
    font-weight: 500;
}

.wizard-step.active .step-title {
    color: var(--primary-color);
    font-weight: 600;
}

.wizard-step.completed .step-title {
    color: var(--success-color);
}

/* Form Sections */
.form-section {
    display: none;
}

.form-section.active {
    display: block;
    animation: fadeIn 0.5s ease forwards;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* Form Controls */
.form-group {
    margin-bottom: 1.5rem;
}

.form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #334155;
}

.form-control {
    display: block;
    width: 100%;
    padding: 0.75rem 1rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #1e293b;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
    border-color: var(--primary-color);
    outline: 0;
    box-shadow: 0 0 0 3px var(--primary-light);
}

.form-select {
    display: block;
    width: 100%;
    padding: 0.75rem 2.5rem 0.75rem 1rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #1e293b;
    background-color: #fff;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 1rem center;
    background-size: 16px 12px;
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
    appearance: none;
}

.form-select:focus {
    border-color: var(--primary-color);
    outline: 0;
    box-shadow: 0 0 0 3px var(--primary-light);
}

.form-text {
    margin-top: 0.25rem;
    font-size: 0.875rem;
    color: #64748b;
}

/* Input Group */
.input-group {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
    width: 100%;
}

.input-group > .form-control,
.input-group > .form-select {
    position: relative;
    flex: 1 1 auto;
    width: 1%;
    min-width: 0;
}

.input-group-text {
    display: flex;
    align-items: center;
    padding: 0.75rem 1rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #64748b;
    text-align: center;
    white-space: nowrap;
    background-color: #f1f5f9;
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
}

.input-group > :not(:first-child):not(.dropdown-menu):not(.valid-tooltip):not(.valid-feedback):not(.invalid-tooltip):not(.invalid-feedback) {
    margin-left: -1px;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.input-group > :first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

/* Custom Radio Cards */
.radio-card-group {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1rem;
}

.radio-card {
    flex: 1;
    min-width: 160px;
}

.radio-card input[type="radio"] {
    display: none;
}

.radio-card label {
    display: block;
    padding: 1.25rem;
    text-align: center;
    border: 1px solid var(--border-color);
    border-radius: 0.75rem;
    cursor: pointer;
    transition: all 0.3s ease;
    height: 100%;
}

.radio-card label:hover {
    border-color: var(--primary-color);
    background-color: var(--primary-light);
}

.radio-card input[type="radio"]:checked + label {
    background-color: var(--primary-light);
    border-color: var(--primary-color);
    box-shadow: 0 0 0 1px var(--primary-color);
}

.radio-card-icon {
    font-size: 2rem;
    margin-bottom: 0.75rem;
    color: var(--primary-color);
}

.radio-card-title {
    font-weight: 600;
    margin-bottom: 0.25rem;
    color: #334155;
}

.radio-card-description {
    font-size: 0.875rem;
    color: #64748b;
}

/* Profile Upload */
.profile-upload-container {
    display: flex;
    align-items: center;
    gap: 1.5rem;
    margin-bottom: 1.5rem;
}

.profile-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    border: 3px solid var(--border-color);
    position: relative;
    background-color: #f8fafc;
}

.profile-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.profile-upload-info h6 {
    font-weight: 600;
    margin-bottom: 0.5rem;
    color: #334155;
}

.profile-upload-info p {
    color: #64748b;
    margin-bottom: 0.75rem;
}

/* Section Divider */
.section-divider {
    display: flex;
    align-items: center;
    margin: 2rem 0;
}

.divider-line {
    flex-grow: 1;
    height: 1px;
    background-color: var(--border-color);
}

.divider-text {
    padding: 0 1rem;
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 500;
}

/* Buttons */
.btn {
    display: inline-block;
    font-weight: 500;
    line-height: 1.5;
    color: #1e293b;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: 0.75rem 1.5rem;
    font-size: 1rem;
    border-radius: 0.5rem;
    transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, 
                border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.btn-primary {
    color: #fff;
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.btn-primary:hover {
    background-color: var(--primary-dark);
    border-color: var(--primary-dark);
}

.btn-success {
    color: #fff;
    background-color: var(--success-color);
    border-color: var(--success-color);
}

.btn-success:hover {
    background-color: #0d9488;
    border-color: #0d9488;
}

.btn-outline-secondary {
    color: #64748b;
    border-color: #cbd5e1;
}

.btn-outline-secondary:hover {
    color: #1e293b;
    background-color: #f1f5f9;
    border-color: #94a3b8;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.875rem;
    border-radius: 0.375rem;
}

/* Info Cards */
.info-card {
    background-color: #f0f9ff;
    border-left: 4px solid var(--info-color);
    border-radius: 0.5rem;
    padding: 1.25rem;
    margin-bottom: 1.5rem;
}

.info-card-icon {
    font-size: 1.5rem;
    color: var(--info-color);
    margin-bottom: 0.75rem;
}

.info-card-title {
    font-weight: 600;
    color: #0c4a6e;
    margin-bottom: 0.5rem;
}

.info-card-text {
    color: #0369a1;
    margin-bottom: 0;
}

/* Alerts */
.alert {
    position: relative;
    padding: 1rem 1.5rem;
    margin-bottom: 1.5rem;
    border: 1px solid transparent;
    border-radius: 0.5rem;
}

.alert-danger {
    color: #991b1b;
    background-color: #fee2e2;
    border-color: #fecaca;
}

.alert-success {
    color: #065f46;
    background-color: #d1fae5;
    border-color: #a7f3d0;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .content-wrapper {
        padding: 1.5rem;
    }
    
    .form-wizard-nav {
        overflow-x: auto;
        padding-bottom: 1rem;
    }
    
    .wizard-step {
        min-width: 100px;
    }
    
    .radio-card {
        min-width: 140px;
    }
}
</style>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">
                <i class='bx bx-user-plus'></i>
                Add New User
            </h1>
            <p class="page-subtitle">Create a new user account with complete profile and security settings</p>
        </div>

        <!-- Display Success/Error Messages -->
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger" role="alert">
                <div class="d-flex">
                    <div class="me-3">
                        <i class='bx bx-error-circle fs-4'></i>
                    </div>
                    <div>
                        <h6 class="alert-heading mb-1">Error</h6>
                        <div><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?></div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Main Form Card -->
        <div class="app-card">
            <div class="app-card-header">
                <h5 class="app-card-title">
                    <i class='bx bx-user-circle'></i>
                    User Registration Form
                </h5>
                              <a href="manage_users.php" class="btn btn-outline-secondary btn-sm">
                    <i class='bx bx-arrow-back me-1'></i> Back to Users
                </a>
            </div>
            <div class="app-card-body">
                <form action="add_user.php" method="POST" id="addUserForm" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                    
                    <!-- Form Wizard Navigation -->
                    <div class="form-wizard-nav">
                        <div class="wizard-step active" data-step="1">
                            <div class="step-icon">1</div>
                            <div class="step-title">Personal</div>
                        </div>
                        <div class="wizard-step" data-step="2">
                            <div class="step-icon">2</div>
                            <div class="step-title">Profile</div>
                        </div>
                        <div class="wizard-step" data-step="3">
                            <div class="step-icon">3</div>
                            <div class="step-title">Account</div>
                        </div>
                        <div class="wizard-step" data-step="4">
                            <div class="step-icon">4</div>
                            <div class="step-title">Security</div>
                        </div>
                    </div>
                    
                    <!-- Form Sections -->
                    <div class="form-sections">
                        <!-- Step 1: Personal Information -->
                        <div class="form-section active" id="step1">
                            <div class="app-card mb-4">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-user'></i>
                                        Basic Information
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="firstName">First Name</label>
                                                <input type="text" class="form-control" id="firstName" name="firstName" placeholder="Enter first name" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="lastName">Last Name</label>
                                                <input type="text" class="form-control" id="lastName" name="lastName" placeholder="Enter last name" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="email">Email Address</label>
                                                <input type="email" class="form-control" id="email" name="email" placeholder="Enter email address" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="phone">Phone Number</label>
                                                <input type="tel" class="form-control" id="phone" name="phone" placeholder="(123) 456-7890" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="dob">Date of Birth</label>
                                                <input type="date" class="form-control" id="dob" name="dob" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="gender">Gender</label>
                                                <select class="form-select" id="gender" name="gender" required>
                                                    <option value="">Select Gender</option>
                                                    <option value="male">Male</option>
                                                    <option value="female">Female</option>
                                                    <option value="other">Other</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="ssn">Social Security Number</label>
                                                <input type="text" class="form-control" id="ssn" name="ssn" placeholder="XXX-XX-XXXX">
                                                <div class="form-text">Format: XXX-XX-XXXX</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="mothersMaidenName">Mother's Maiden Name</label>
                                                <input type="text" class="form-control" id="mothersMaidenName" name="mothersMaidenName" placeholder="Enter mother's maiden name">
                                                <div class="form-text">Used for security verification</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="app-card">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-map'></i>
                                        Address Information
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label class="form-label" for="address">Street Address</label>
                                                <input type="text" class="form-control" id="address" name="address" placeholder="Enter street address" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="form-label" for="city">City</label>
                                                <input type="text" class="form-control" id="city" name="city" placeholder="Enter city">
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="form-label" for="state">State/Province</label>
                                                <input type="text" class="form-control" id="state" name="state" placeholder="Enter state/province">
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="form-label" for="zipCode">Zip/Postal Code</label>
                                                <input type="text" class="form-control" id="zipCode" name="zipCode" placeholder="Enter zip/postal code">
                                            </div>
                                        </div>
                                        <div class="col-md-12">
                                            <div class="form-group mb-0">
                                                <label class="form-label" for="country">Country</label>
                                                <select class="form-select" id="country" name="country" required>
                                                    <option value="">Select Country</option>
                                                    <option value="AF">Afghanistan</option>
  <option value="AL">Albania</option>
  <option value="DZ">Algeria</option>
  <option value="AD">Andorra</option>
  <option value="AO">Angola</option>
  <option value="AG">Antigua and Barbuda</option>
  <option value="AR">Argentina</option>
  <option value="AM">Armenia</option>
  <option value="AU">Australia</option>
  <option value="AT">Austria</option>
  <option value="AZ">Azerbaijan</option>
  <option value="BS">Bahamas</option>
  <option value="BH">Bahrain</option>
  <option value="BD">Bangladesh</option>
  <option value="BB">Barbados</option>
  <option value="BY">Belarus</option>
  <option value="BE">Belgium</option>
  <option value="BZ">Belize</option>
  <option value="BJ">Benin</option>
  <option value="BT">Bhutan</option>
  <option value="BO">Bolivia</option>
  <option value="BA">Bosnia and Herzegovina</option>
  <option value="BW">Botswana</option>
  <option value="BR">Brazil</option>
  <option value="BN">Brunei</option>
  <option value="BG">Bulgaria</option>
  <option value="BF">Burkina Faso</option>
  <option value="BI">Burundi</option>
  <option value="CV">Cabo Verde</option>
  <option value="KH">Cambodia</option>
  <option value="CM">Cameroon</option>
  <option value="CA">Canada</option>
  <option value="CF">Central African Republic</option>
  <option value="TD">Chad</option>
  <option value="CL">Chile</option>
  <option value="CN">China</option>
  <option value="CO">Colombia</option>
  <option value="KM">Comoros</option>
  <option value="CG">Congo</option>
  <option value="CD">Congo (Democratic Republic)</option>
  <option value="CR">Costa Rica</option>
  <option value="HR">Croatia</option>
  <option value="CU">Cuba</option>
  <option value="CY">Cyprus</option>
  <option value="CZ">Czechia</option>
  <option value="DK">Denmark</option>
  <option value="DJ">Djibouti</option>
  <option value="DM">Dominica</option>
  <option value="DO">Dominican Republic</option>
  <option value="EC">Ecuador</option>
  <option value="EG">Egypt</option>
  <option value="SV">El Salvador</option>
  <option value="GQ">Equatorial Guinea</option>
  <option value="ER">Eritrea</option>
  <option value="EE">Estonia</option>
  <option value="SZ">Eswatini</option>
  <option value="ET">Ethiopia</option>
  <option value="FJ">Fiji</option>
  <option value="FI">Finland</option>
  <option value="FR">France</option>
  <option value="GA">Gabon</option>
  <option value="GM">Gambia</option>
  <option value="GE">Georgia</option>
  <option value="DE">Germany</option>
  <option value="GH">Ghana</option>
  <option value="GR">Greece</option>
  <option value="GD">Grenada</option>
  <option value="GT">Guatemala</option>
  <option value="GN">Guinea</option>
  <option value="GW">Guinea-Bissau</option>
  <option value="GY">Guyana</option>
  <option value="HT">Haiti</option>
  <option value="HN">Honduras</option>
  <option value="HU">Hungary</option>
  <option value="IS">Iceland</option>
  <option value="IN">India</option>
  <option value="ID">Indonesia</option>
  <option value="IR">Iran</option>
  <option value="IQ">Iraq</option>
  <option value="IE">Ireland</option>
  <option value="IL">Israel</option>
  <option value="IT">Italy</option>
  <option value="JM">Jamaica</option>
  <option value="JP">Japan</option>
  <option value="JO">Jordan</option>
  <option value="KZ">Kazakhstan</option>
  <option value="KE">Kenya</option>
  <option value="KI">Kiribati</option>
  <option value="KW">Kuwait</option>
  <option value="KG">Kyrgyzstan</option>
  <option value="LA">Laos</option>
  <option value="LV">Latvia</option>
  <option value="LB">Lebanon</option>
  <option value="LS">Lesotho</option>
  <option value="LR">Liberia</option>
  <option value="LY">Libya</option>
  <option value="LI">Liechtenstein</option>
  <option value="LT">Lithuania</option>
  <option value="LU">Luxembourg</option>
  <option value="MG">Madagascar</option>
  <option value="MW">Malawi</option>
  <option value="MY">Malaysia</option>
  <option value="MV">Maldives</option>
  <option value="ML">Mali</option>
  <option value="MT">Malta</option>
  <option value="MH">Marshall Islands</option>
  <option value="MR">Mauritania</option>
  <option value="MU">Mauritius</option>
  <option value="MX">Mexico</option>
  <option value="FM">Micronesia</option>
  <option value="MD">Moldova</option>
  <option value="MC">Monaco</option>
  <option value="MN">Mongolia</option>
  <option value="ME">Montenegro</option>
  <option value="MA">Morocco</option>
  <option value="MZ">Mozambique</option>
  <option value="MM">Myanmar</option>
  <option value="NA">Namibia</option>
  <option value="NR">Nauru</option>
  <option value="NP">Nepal</option>
  <option value="NL">Netherlands</option>
  <option value="NZ">New Zealand</option>
  <option value="NI">Nicaragua</option>
  <option value="NE">Niger</option>
  <option value="NG">Nigeria</option>
  <option value="KP">North Korea</option>
  <option value="MK">North Macedonia</option>
  <option value="NO">Norway</option>
  <option value="OM">Oman</option>
  <option value="PK">Pakistan</option>
  <option value="PW">Palau</option>
  <option value="PS">Palestine</option>
  <option value="PA">Panama</option>
  <option value="PG">Papua New Guinea</option>
  <option value="PY">Paraguay</option>
  <option value="PE">Peru</option>
  <option value="PH">Philippines</option>
  <option value="PL">Poland</option>
  <option value="PT">Portugal</option>
  <option value="QA">Qatar</option>
  <option value="RO">Romania</option>
  <option value="RU">Russia</option>
  <option value="RW">Rwanda</option>
  <option value="KN">Saint Kitts and Nevis</option>
  <option value="LC">Saint Lucia</option>
  <option value="VC">Saint Vincent and the Grenadines</option>
  <option value="WS">Samoa</option>
  <option value="SM">San Marino</option>
  <option value="ST">Sao Tome and Principe</option>
  <option value="SA">Saudi Arabia</option>
  <option value="SN">Senegal</option>
  <option value="RS">Serbia</option>
  <option value="SC">Seychelles</option>
  <option value="SL">Sierra Leone</option>
  <option value="SG">Singapore</option>
  <option value="SK">Slovakia</option>
  <option value="SI">Slovenia</option>
  <option value="SB">Solomon Islands</option>
  <option value="SO">Somalia</option>
  <option value="ZA">South Africa</option>
  <option value="KR">South Korea</option>
  <option value="SS">South Sudan</option>
  <option value="ES">Spain</option>
  <option value="LK">Sri Lanka</option>
  <option value="SD">Sudan</option>
  <option value="SR">Suriname</option>
  <option value="SE">Sweden</option>
  <option value="CH">Switzerland</option>
  <option value="SY">Syria</option>
  <option value="TW">Taiwan</option>
  <option value="TJ">Tajikistan</option>
  <option value="TZ">Tanzania</option>
  <option value="TH">Thailand</option>
  <option value="TL">Timor-Leste</option>
  <option value="TG">Togo</option>
  <option value="TO">Tonga</option>
  <option value="TT">Trinidad and Tobago</option>
  <option value="TN">Tunisia</option>
  <option value="TR">Turkey</option>
  <option value="TM">Turkmenistan</option>
  <option value="TV">Tuvalu</option>
  <option value="UG">Uganda</option>
  <option value="UA">Ukraine</option>
  <option value="AE">United Arab Emirates</option>
  <option value="GB">United Kingdom</option>
  <option value="US">United States</option>
  <option value="UY">Uruguay</option>
  <option value="UZ">Uzbekistan</option>
  <option value="VU">Vanuatu</option>
  <option value="VA">Vatican City</option>
  <option value="VE">Venezuela</option>
  <option value="VN">Vietnam</option>
  <option value="YE">Yemen</option>
  <option value="ZM">Zambia</option>
  <option value="ZW">Zimbabwe</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-end mt-4">
                                <button type="button" class="btn btn-primary" onclick="nextStep(1)">
                                    Continue <i class='bx bx-right-arrow-alt ms-1'></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 2: Profile & Documents -->
                        <div class="form-section" id="step2">
                            <div class="app-card mb-4">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-user-pin'></i>
                                        Profile Setup
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <!-- Profile Picture Upload -->
                                    <div class="profile-upload-container">
                                        <div class="profile-preview">
                                            <img src="../assets/images/default-avatar.png" id="profilePreview" alt="Profile Preview">
                                        </div>
                                        <div class="profile-upload-info">
                                            <h6>Profile Picture</h6>
                                            <p>Upload a clear photo of the user</p>
                                            <input type="file" id="profilePicture" name="profilePicture" class="form-control" accept="image/*">
                                            <div class="form-text">Max file size: 5MB (JPG or PNG)</div>
                                        </div>
                                    </div>
                                    
                                    <!-- Employment Information -->
                                    <div class="section-divider">
                                        <div class="divider-line"></div>
                                        <div class="divider-text">Employment Information</div>
                                        <div class="divider-line"></div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="employmentStatus">Employment Status</label>
                                                <select class="form-select" id="employmentStatus" name="employmentStatus" required>
                                                    <option value="">Select Status</option>
                                                    <option value="employed">Employed</option>
                                                    <option value="self-employed">Self-Employed</option>
                                                    <option value="student">Student</option>
                                                    <option value="retired">Retired</option>
                                                    <option value="unemployed">Unemployed</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="incomeSource">Source of Income</label>
                                                <select class="form-select" id="incomeSource" name="incomeSource" required>
                                                    <option value="">Select Source</option>
                                                    <option value="salary">Salary</option>
                                                    <option value="business">Business Income</option>
                                                    <option value="investments">Investments</option>
                                                    <option value="other">Other</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="occupation">Occupation</label>
                                                <input type="text" class="form-control" id="occupation" name="occupation" placeholder="Enter occupation">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="employer">Employer Name</label>
                                                <input type="text" class="form-control" id="employer" name="employer" placeholder="Enter employer name">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="app-card">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-user-voice'></i>
                                        Next of Kin Details
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="kinName">Full Name</label>
                                                <input type="text" class="form-control" id="kinName" name="kinName" placeholder="Enter full name" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="kinRelationship">Relationship</label>
                                                <select class="form-select" id="kinRelationship" name="kinRelationship" required>
                                                    <option value="">Select Relationship</option>
                                                    <option value="spouse">Spouse</option>
                                                    <option value="parent">Parent</option>
                                                    <option value="child">Child</option>
                                                    <option value="sibling">Sibling</option>
                                                    <option value="other">Other</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="kinEmail">Email Address</label>
                                                <input type="email" class="form-control" id="kinEmail" name="kinEmail" placeholder="Enter email address" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="kinPhone">Phone Number</label>
                                                <input type="tel" class="form-control" id="kinPhone" name="kinPhone" placeholder="(123) 456-7890" required>
                                            </div>
                                        </div>
                                        <div class="col-md-12">
                                            <div class="form-group mb-0">
                                                <label class="form-label" for="kinAddress">Address</label>
                                                <textarea class="form-control" id="kinAddress" name="kinAddress" rows="3" placeholder="Enter address" required></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="prevStep(2)">
                                    <i class='bx bx-left-arrow-alt me-1'></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" onclick="nextStep(2)">
                                    Continue <i class='bx bx-right-arrow-alt ms-1'></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 3: Account Details -->
                        <div class="form-section" id="step3">
                            <div class="app-card mb-4">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-bank'></i>
                                        Account Type
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="radio-card-group">
                                        <div class="radio-card">
                                            <input type="radio" id="accountTypeSavings" name="accountType" value="savings" required>
                                            <label for="accountTypeSavings">
                                                <div class="radio-card-icon">
                                                    <i class='bx bx-wallet'></i>
                                                </div>
                                                <div class="radio-card-title">Savings Account</div>
                                                <div class="radio-card-description">For personal savings and growth</div>
                                            </label>
                                        </div>
                                        <div class="radio-card">
                                            <input type="radio" id="accountTypeChecking" name="accountType" value="checking" required>
                                            <label for="accountTypeChecking">
                                                <div class="radio-card-icon">
                                                    <i class='bx bx-credit-card'></i>
                                                </div>
                                                <div class="radio-card-title">Checking Account</div>
                                                <div class="radio-card-description">For daily transactions</div>
                                            </label>
                                        </div>
                                        <div class="radio-card">
                                            <input type="radio" id="accountTypeBusiness" name="accountType" value="business" required>
                                            <label for="accountTypeBusiness">
                                                <div class="radio-card-icon">
                                                    <i class='bx bx-briefcase'></i>
                                                </div>
                                                <div class="radio-card-title">Business Account</div>
                                                <div class="radio-card-description">For business operations</div>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="app-card">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-cog'></i>
                                        Account Settings
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="currency">Currency</label>
                                                <select class="form-select" id="currency" name="currency" required>
                                                    <option value="">Select Currency</option>
                                                    <option value="USD">US Dollar (USD)</option>
                                                    <option value="EUR">Euro (EUR)</option>
                                                    <option value="GBP">British Pound (GBP)</option>
                                                    <option value="AUD">Australian Dollar (AUD)</option>
                                                    <option value="CAD">Canadian Dollar (CAD)</option>
                                                    <option value="JPY">Japanese Yen (JPY)</option>
                                                    <option value="CHF">Swiss Franc (CHF)</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="initial_balance">Initial Balance</label>
                                                <div class="input-group">
                                                    <span class="input-group-text">$</span>
                                                    <input type="number" class="form-control" id="initial_balance" name="initial_balance" step="0.01" value="0.00" placeholder="0.00">
                                                </div>
                                                <div class="form-text">Initial deposit amount</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="status">Account Status</label>
                                                <select class="form-select" id="status" name="status" required>
                                                    <option value="pending">Pending</option>
                                                    <option value="active" selected>Active</option>
                                                    <option value="suspended">Suspended</option>
                                                    <option value="closed">Closed</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Debit Card</label>
                                                <div class="d-flex gap-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="radio" name="requestDebitCard" id="requestDebitCardYes" value="yes">
                                                        <label class="form-check-label" for="requestDebitCardYes">
                                                            Issue Debit Card
                                                        </label>
                                                    </div>
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="radio" name="requestDebitCard" id="requestDebitCardNo" value="no" checked>
                                                        <label class="form-check-label" for="requestDebitCardNo">
                                                            No Debit Card
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Online Banking</label>
                                                <div class="d-flex gap-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="radio" name="onlineBanking" id="onlineBankingYes" value="yes" checked>
                                                        <label class="form-check-label" for="onlineBankingYes">
                                                            Enable Online Banking
                                                        </label>
                                                    </div>
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="radio" name="onlineBanking" id="onlineBankingNo" value="no">
                                                        <label class="form-check-label" for="onlineBankingNo">
                                                            Disable Online Banking
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="info-card mt-4">
                                        <div class="info-card-icon">
                                            <i class='bx bx-info-circle'></i>
                                        </div>
                                        <h6 class="info-card-title">Account Information</h6>
                                        <p class="info-card-text">The system will automatically generate a unique account number for this user. The account will be created with the status and settings specified above.</p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="prevStep(3)">
                                    <i class='bx bx-left-arrow-alt me-1'></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" onclick="nextStep(3)">
                                    Continue <i class='bx bx-right-arrow-alt ms-1'></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 4: Security -->
                        <div class="form-section" id="step4">
                            <div class="app-card mb-4">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-lock-alt'></i>
                                        Login Credentials
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="username">Username</label>
                                                <input type="text" class="form-control" id="username" name="username" placeholder="Choose a username" required pattern="^[a-zA-Z0-9_]{4,20}$">
                                                <div class="form-text">4-20 characters, letters, numbers and underscore only</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="password">Password</label>
                                                <div class="input-group">
                                                    <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" required pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$">
                                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('password')">
                                                        <i class='bx bx-show'></i>
                                                    </button>
                                                </div>
                                                <div class="form-text">Minimum 8 characters, at least one letter and one number</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="confirmPassword">Confirm Password</label>
                                                <div class="input-group">
                                                    <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="Confirm password" required>
                                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirmPassword')">
                                                        <i class='bx bx-show'></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="pin">PIN (4 digits)</label>
                                                <input type="password" class="form-control" id="pin" name="pin" placeholder="Enter 4-digit PIN" pattern="\d{4}" maxlength="4" value="0000">
                                                <div class="form-text">Default: 0000 (User will be prompted to change)</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="app-card mb-4">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-question-mark'></i>
                                        Security Questions
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="securityQuestion1">Security Question 1</label>
                                                <select class="form-select" id="securityQuestion1" name="securityQuestion1">
                                                    <option value="">Select a question</option>
                                                    <option value="first_pet">What was the name of your first pet?</option>
                                                    <option value="birth_city">In what city were you born?</option>
                                                    <option value="mother_maiden">What is your mother's maiden name?</option>
                                                    <option value="high_school">What high school did you attend?</option>
                                                    <option value="first_car">What was the make of your first car?</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="securityAnswer1">Answer</label>
                                                <input type="text" class="form-control" id="securityAnswer1" name="securityAnswer1" placeholder="Your answer">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="securityQuestion2">Security Question 2</label>
                                                <select class="form-select" id="securityQuestion2" name="securityQuestion2">
                                                    <option value="">Select a question</option>
                                                    <option value="favorite_teacher">Who was your favorite teacher?</option>
                                                    <option value="first_job">What was your first job?</option>
                                                    <option value="childhood_friend">What is the name of your childhood best friend?</option>
                                                    <option value="favorite_food">What is your favorite food?</option>
                                                    <option value="childhood_hero">Who was your childhood hero?</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="securityAnswer2">Answer</label>
                                                <input type="text" class="form-control" id="securityAnswer2" name="securityAnswer2" placeholder="Your answer">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="app-card">
                                <div class="app-card-header">
                                    <h5 class="app-card-title">
                                        <i class='bx bx-shield-quarter'></i>
                                        Additional Security
                                    </h5>
                                </div>
                                <div class="app-card-body">
                                    <div class="form-check mb-3">
                                        <input class="form-check-input" type="checkbox" id="enableTwoFactor" name="enableTwoFactor">
                                        <label class="form-check-label" for="enableTwoFactor">
                                            Enable Two-Factor Authentication
                                        </label>
                                        <div class="form-text">Recommended for enhanced security. User will receive a verification code via email when logging in.</div>
                                    </div>
                                    
                                    <div class="info-card">
                                        <div class="info-card-icon">
                                            <i class='bx bx-info-circle'></i>
                                        </div>
                                        <h6 class="info-card-title">Security Codes</h6>
                                                                                <p class="info-card-text">The system will automatically generate security codes (COT, IMF, TAX) for this user. These codes will be sent to the user via email and are required for certain transactions.</p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="prevStep(4)">
                                    <i class='bx bx-left-arrow-alt me-1'></i> Back
                                </button>
                                <button type="submit" class="btn btn-success">
                                    <i class='bx bx-user-plus me-1'></i> Create User Account
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Current step tracking
let currentStep = 1;
const totalSteps = 4;

// Step navigation functions
function nextStep(step) {
    // Validate current step
    if (!validateStep(step)) return;
    
    // Hide current step
    document.getElementById(`step${step}`).classList.remove('active');
    
    // Show next step
    document.getElementById(`step${step + 1}`).classList.add('active');
    
    // Update step indicators
    updateStepIndicators(step + 1);
    
    // Update current step
    currentStep = step + 1;
    
    // Scroll to top
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function prevStep(step) {
    // Hide current step
    document.getElementById(`step${step}`).classList.remove('active');
    
    // Show previous step
    document.getElementById(`step${step - 1}`).classList.add('active');
    
    // Update step indicators
    updateStepIndicators(step - 1);
    
    // Update current step
    currentStep = step - 1;
    
    // Scroll to top
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function updateStepIndicators(activeStep) {
    // Get all step indicators
    const stepIndicators = document.querySelectorAll('.wizard-step');
    
    // Update classes based on active step
    stepIndicators.forEach((indicator, index) => {
        const step = index + 1;
        
        // Remove all classes first
        indicator.classList.remove('active', 'completed');
        
        // Add appropriate class
        if (step === activeStep) {
            indicator.classList.add('active');
        } else if (step < activeStep) {
            indicator.classList.add('completed');
        }
    });
}

// Form validation functions
function validateStep(step) {
    const currentStepElement = document.getElementById(`step${step}`);
    const requiredFields = currentStepElement.querySelectorAll('[required]:not(:disabled)');
    let isValid = true;
    
    // Check all required fields
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            highlightInvalidField(field);
        } else {
            removeInvalidHighlight(field);
        }
    });
    
    // Show error message if validation fails
    if (!isValid) {
        showErrorMessage('Please fill in all required fields');
        return false;
    }
    
    // Additional validation based on step
    switch(step) {
        case 1:
            return validatePersonalInfo();
        case 2:
            return validateProfileInfo();
        case 3:
            return validateAccountInfo();
        case 4:
            return validateSecurityInfo();
    }
    
    return true;
}

function validatePersonalInfo() {
    // Email validation
    const email = document.getElementById('email');
    if (email && !isValidEmail(email.value)) {
        highlightInvalidField(email);
        showErrorMessage('Please enter a valid email address');
        return false;
    }
    
    // Phone validation
    const phone = document.getElementById('phone');
    if (phone && !isValidPhone(phone.value)) {
        highlightInvalidField(phone);
        showErrorMessage('Please enter a valid phone number');
        return false;
    }
    
    // Date of birth validation
    const dob = document.getElementById('dob');
    if (dob && !isAdult(dob.value)) {
        highlightInvalidField(dob);
        showErrorMessage('User must be at least 18 years old');
        return false;
    }
    
    return true;
}

function validateProfileInfo() {
    // Basic validation for next of kin
    const kinEmail = document.getElementById('kinEmail');
    if (kinEmail && !isValidEmail(kinEmail.value)) {
        highlightInvalidField(kinEmail);
        showErrorMessage('Please enter a valid email address for next of kin');
        return false;
    }
    
    const kinPhone = document.getElementById('kinPhone');
    if (kinPhone && !isValidPhone(kinPhone.value)) {
        highlightInvalidField(kinPhone);
        showErrorMessage('Please enter a valid phone number for next of kin');
        return false;
    }
    
    return true;
}

function validateAccountInfo() {
    // Check if account type is selected
    const accountTypes = document.querySelectorAll('input[name="accountType"]');
    let accountTypeSelected = false;
    
    accountTypes.forEach(radio => {
        if (radio.checked) {
            accountTypeSelected = true;
        }
    });
    
    if (!accountTypeSelected) {
        showErrorMessage('Please select an account type');
        return false;
    }
    
    return true;
}

function validateSecurityInfo() {
    // Password validation
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirmPassword');
    
    if (password && !isValidPassword(password.value)) {
        highlightInvalidField(password);
        showErrorMessage('Password must be at least 8 characters with at least one letter and one number');
        return false;
    }
    
    if (password && confirmPassword && password.value !== confirmPassword.value) {
        highlightInvalidField(confirmPassword);
        showErrorMessage('Passwords do not match');
        return false;
    }
    
    // Username validation
    const username = document.getElementById('username');
    if (username && !isValidUsername(username.value)) {
        highlightInvalidField(username);
        showErrorMessage('Username must be 4-20 characters and contain only letters, numbers, and underscores');
        return false;
    }
    
    // PIN validation
    const pin = document.getElementById('pin');
    if (pin && !isValidPin(pin.value)) {
        highlightInvalidField(pin);
        showErrorMessage('PIN must be exactly 4 digits');
        return false;
    }
    
    return true;
}

// Helper validation functions
function isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function isValidPhone(phone) {
    const cleaned = phone.replace(/\D/g, '');
    return cleaned.length >= 10;
}

function isAdult(dateString) {
    const today = new Date();
    const birthDate = new Date(dateString);
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    
    return age >= 18;
}

function isValidPassword(password) {
    return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password);
}

function isValidUsername(username) {
    return /^[a-zA-Z0-9_]{4,20}$/.test(username);
}

function isValidPin(pin) {
    return /^\d{4}$/.test(pin);
}

// UI feedback functions
function highlightInvalidField(field) {
    field.classList.add('is-invalid');
    
    // Add event listener to remove invalid class on input
    field.addEventListener('input', function() {
        this.classList.remove('is-invalid');
    }, { once: true });
}

function removeInvalidHighlight(field) {
    field.classList.remove('is-invalid');
}

function showErrorMessage(message) {
    // Use SweetAlert2 if available
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            icon: 'error',
            title: 'Validation Error',
            text: message,
            confirmButtonColor: '#4f46e5'
        });
    } else {
        // Fallback to alert
        alert(message);
    }
}

// Toggle password visibility
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = input.nextElementSibling.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.replace('bx-show', 'bx-hide');
    } else {
        input.type = 'password';
        icon.classList.replace('bx-hide', 'bx-show');
    }
}

// Profile picture preview
document.getElementById('profilePicture').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        if (file.size > 5 * 1024 * 1024) {
            showErrorMessage('File size too large. Maximum size is 5MB.');
            this.value = '';
            return;
        }

        if (!file.type.startsWith('image/')) {
            showErrorMessage('Please select an image file.');
            this.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('profilePreview').src = e.target.result;
        }
        reader.readAsDataURL(file);
    }
});

// Format phone number input
document.querySelectorAll('input[type="tel"]').forEach(input => {
    input.addEventListener('input', function() {
        let cleaned = this.value.replace(/\D/g, '');
        let formatted = cleaned;
        
        if (cleaned.length > 0) {
            if (cleaned.length <= 3) {
                formatted = cleaned;
            } else if (cleaned.length <= 6) {
                formatted = `(${cleaned.slice(0,3)}) ${cleaned.slice(3)}`;
            } else {
                formatted = `(${cleaned.slice(0,3)}) ${cleaned.slice(3,6)}-${cleaned.slice(6,10)}`;
            }
        }
        
        this.value = formatted;
    });
});

// Format SSN input
const ssnInput = document.querySelector('input[name="ssn"]');
if (ssnInput) {
    ssnInput.addEventListener('input', function() {
        let cleaned = this.value.replace(/\D/g, '');
        let formatted = cleaned;
        
        if (cleaned.length > 0) {
            if (cleaned.length <= 3) {
                formatted = cleaned;
            } else if (cleaned.length <= 5) {
                formatted = `${cleaned.slice(0,3)}-${cleaned.slice(3)}`;
            } else {
                formatted = `${cleaned.slice(0,3)}-${cleaned.slice(3,5)}-${cleaned.slice(5,9)}`;
            }
        }
        
        this.value = formatted;
    });
}

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

// Form submission
document.getElementById('addUserForm').addEventListener('submit', function(event) {
    // Validate the current step
    if (!validateStep(currentStep)) {
        event.preventDefault();
        return;
    }
    
    // Show loading state
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Creating User Account',
            html: 'Please wait while we process your request...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    }
});

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize tooltips if Bootstrap is available
    if (typeof bootstrap !== 'undefined' && typeof bootstrap.Tooltip !== 'undefined') {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
</script>

<?php
// Include the footer
include 'includes/footer.php';
?>

