<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'User';

// Check if user has permission to create users
if ($user_role !== 'Administrator') {
    header('Location: index.php');
    exit();
}

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Handle form submission
if ($_POST && isset($_POST['action']) && $_POST['action'] === 'create_user') {
    header('Content-Type: application/json');
    
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $full_name = trim($_POST['full_name']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $role_id = intval($_POST['role_id']);
    $phone = trim($_POST['phone']);
    $status = $_POST['status'];
    
    // Validation
    $errors = [];
    
    if (empty($username)) {
        $errors[] = "Username is required";
    } elseif (strlen($username) < 3) {
        $errors[] = "Username must be at least 3 characters long";
    }
    
    if (empty($email)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    if (empty($full_name)) {
        $errors[] = "Full name is required";
    }
    
    if (empty($password)) {
        $errors[] = "Password is required";
    } elseif (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long";
    } elseif ($password !== $confirm_password) {
        $errors[] = "Passwords do not match";
    }
    
    if (empty($role_id)) {
        $errors[] = "Role is required";
    }
    
    // Check for duplicate username
    if (empty($errors)) {
        $check_username = $conn->prepare("SELECT user_id FROM users WHERE username = ?");
        $check_username->bind_param("s", $username);
        $check_username->execute();
        if ($check_username->get_result()->num_rows > 0) {
            $errors[] = "Username already exists";
        }
    }
    
    // Check for duplicate email
    if (empty($errors)) {
        $check_email = $conn->prepare("SELECT user_id FROM users WHERE email = ?");
        $check_email->bind_param("s", $email);
        $check_email->execute();
        if ($check_email->get_result()->num_rows > 0) {
            $errors[] = "Email already exists";
        }
    }
    
    if (!empty($errors)) {
        echo json_encode(['success' => false, 'message' => implode(', ', $errors)]);
        exit();
    }
    
    // Hash password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    // Insert new user
    $insert_sql = "INSERT INTO users (username, email, full_name, password, role_id, phone, status, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param("ssssiss", $username, $email, $full_name, $hashed_password, $role_id, $phone, $status);
    
    if ($stmt->execute()) {
        $new_user_id = $conn->insert_id;
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                   VALUES (?, 'CREATE', 'users', ?, ?)";
        $stmt_log = $conn->prepare($log_sql);
        $log_data = json_encode(['username' => $username, 'email' => $email, 'full_name' => $full_name, 'role_id' => $role_id]);
        $stmt_log->bind_param("iss", $user_id, $new_user_id, $log_data);
        $stmt_log->execute();
        
        echo json_encode(['success' => true, 'message' => 'User created successfully', 'user_id' => $new_user_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to create user']);
    }
    exit();
}

// Fetch available roles
$sql_roles = "SELECT role_id, role_name, description FROM user_roles ORDER BY role_name";
$roles_result = $conn->query($sql_roles);

// Get user statistics
$sql_stats = "SELECT 
    COUNT(*) as total_users,
    SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active_users,
    SUM(CASE WHEN status = 'INACTIVE' THEN 1 ELSE 0 END) as inactive_users,
    SUM(CASE WHEN status = 'SUSPENDED' THEN 1 ELSE 0 END) as suspended_users,
    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_created
FROM users";
$stats_result = $conn->query($sql_stats);
$stats = $stats_result->fetch_assoc();

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create User')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .user-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .user-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .form-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .form-section h5 {
            color: #495057;
            margin-bottom: 1rem;
            font-weight: 600;
        }
        
        .password-strength {
            margin-top: 0.5rem;
        }
        
        .strength-bar {
            height: 4px;
            border-radius: 2px;
            background: #e9ecef;
            overflow: hidden;
        }
        
        .strength-fill {
            height: 100%;
            transition: width 0.3s ease;
            border-radius: 2px;
        }
        
        .strength-weak { background: #dc3545; width: 25%; }
        .strength-fair { background: #fd7e14; width: 50%; }
        .strength-good { background: #ffc107; width: 75%; }
        .strength-strong { background: #28a745; width: 100%; }
        
        .password-requirements {
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 0.5rem;
        }
        
        .requirement {
            margin: 0.2rem 0;
        }
        
        .requirement.met {
            color: #28a745;
        }
        
        .requirement.not-met {
            color: #dc3545;
        }
        
        .create-user-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .create-user-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        .role-card {
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .role-card:hover {
            border-color: #667eea;
            background: #f8f9ff;
        }
        
        .role-card.selected {
            border-color: #667eea;
            background: #e7f3ff;
        }
        
        .role-title {
            font-weight: 600;
            color: #495057;
        }
        
        .role-description {
            font-size: 0.9rem;
            color: #6c757d;
            margin-top: 0.25rem;
        }
        
        .avatar-preview {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            font-weight: 600;
            margin: 0 auto 1rem auto;
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .form-section {
                padding: 1rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-user-add-line me-2"></i>Create User</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="users.php">Users</a></li>
                                        <li class="breadcrumb-item active">Create User</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($stats['total_users']); ?></div>
                                <div class="summary-label">Total Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($stats['active_users']); ?></div>
                                <div class="summary-label">Active Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($stats['inactive_users']); ?></div>
                                <div class="summary-label">Inactive Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="summary-value"><?php echo number_format($stats['today_created']); ?></div>
                                <div class="summary-label">Created Today</div>
                            </div>
                        </div>
                    </div>

                    <!-- Create User Form -->
                    <div class="row">
                        <div class="col-12">
                            <form id="createUserForm">
                                <input type="hidden" name="action" value="create_user">
                                
                                <div class="row">
                                    <!-- User Information -->
                                    <div class="col-xl-8">
                                        <div class="user-card">
                                            <div class="card-header bg-transparent border-bottom">
                                                <h5 class="card-title mb-0">
                                                    <i class="ri-user-settings-line me-2"></i>User Information
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="row g-3">
                                                    <div class="col-md-6">
                                                        <label for="username" class="form-label">Username <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="username" name="username" required
                                                               placeholder="Enter username" onkeyup="checkUsername()">
                                                        <div class="form-text">Username must be at least 3 characters long</div>
                                                        <div id="usernameCheck" class="mt-1"></div>
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                                                        <input type="email" class="form-control" id="email" name="email" required
                                                               placeholder="Enter email address" onkeyup="checkEmail()">
                                                        <div id="emailCheck" class="mt-1"></div>
                                                    </div>
                                                    
                                                    <div class="col-md-12">
                                                        <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="full_name" name="full_name" required
                                                               placeholder="Enter full name" onkeyup="updateAvatarPreview()">
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <label for="phone" class="form-label">Phone Number</label>
                                                        <input type="tel" class="form-control" id="phone" name="phone"
                                                               placeholder="Enter phone number">
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                                                        <select class="form-select" id="status" name="status" required>
                                                            <option value="ACTIVE">Active</option>
                                                            <option value="INACTIVE">Inactive</option>
                                                            <option value="SUSPENDED">Suspended</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Password Section -->
                                        <div class="user-card">
                                            <div class="card-header bg-transparent border-bottom">
                                                <h5 class="card-title mb-0">
                                                    <i class="ri-lock-line me-2"></i>Password Settings
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="row g-3">
                                                    <div class="col-md-6">
                                                        <label for="password" class="form-label">Password <span class="text-danger">*</span></label>
                                                        <div class="position-relative">
                                                            <input type="password" class="form-control" id="password" name="password" required
                                                                   placeholder="Enter password" onkeyup="checkPasswordStrength()">
                                                            <button type="button" class="btn btn-link position-absolute top-50 end-0 translate-middle-y" 
                                                                    onclick="togglePassword('password')">
                                                                <i class="ri-eye-off-line" id="passwordToggleIcon"></i>
                                                            </button>
                                                        </div>
                                                        <div class="password-strength">
                                                            <div class="strength-bar">
                                                                <div class="strength-fill" id="strengthFill"></div>
                                                            </div>
                                                            <div class="mt-1">
                                                                <small id="strengthText" class="text-muted">Password strength</small>
                                                            </div>
                                                        </div>
                                                        <div class="password-requirements">
                                                            <div class="requirement" id="req-length">• At least 8 characters</div>
                                                            <div class="requirement" id="req-upper">• One uppercase letter</div>
                                                            <div class="requirement" id="req-lower">• One lowercase letter</div>
                                                            <div class="requirement" id="req-number">• One number</div>
                                                            <div class="requirement" id="req-special">• One special character</div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <label for="confirm_password" class="form-label">Confirm Password <span class="text-danger">*</span></label>
                                                        <div class="position-relative">
                                                            <input type="password" class="form-control" id="confirm_password" name="confirm_password" required
                                                                   placeholder="Confirm password" onkeyup="checkPasswordMatch()">
                                                            <button type="button" class="btn btn-link position-absolute top-50 end-0 translate-middle-y" 
                                                                    onclick="togglePassword('confirm_password')">
                                                                <i class="ri-eye-off-line" id="confirmPasswordToggleIcon"></i>
                                                            </button>
                                                        </div>
                                                        <div id="passwordMatch" class="mt-1"></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Role Selection and Preview -->
                                    <div class="col-xl-4">
                                        <div class="user-card">
                                            <div class="card-header bg-transparent border-bottom">
                                                <h5 class="card-title mb-0">
                                                    <i class="ri-shield-user-line me-2"></i>User Preview
                                                </h5>
                                            </div>
                                            <div class="card-body text-center">
                                                <div class="avatar-preview" id="avatarPreview">
                                                    <i class="ri-user-line"></i>
                                                </div>
                                                <h5 id="previewName" class="mb-1">New User</h5>
                                                <p id="previewEmail" class="text-muted mb-2">user@example.com</p>
                                                <span class="badge bg-primary" id="previewRole">Select Role</span>
                                            </div>
                                        </div>

                                        <!-- Role Selection -->
                                        <div class="user-card">
                                            <div class="card-header bg-transparent border-bottom">
                                                <h5 class="card-title mb-0">
                                                    <i class="ri-user-settings-line me-2"></i>Assign Role <span class="text-danger">*</span>
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <input type="hidden" id="role_id" name="role_id" required>
                                                <div id="rolesList">
                                                    <?php while ($role = $roles_result->fetch_assoc()): ?>
                                                    <div class="role-card" onclick="selectRole(<?php echo $role['role_id']; ?>, '<?php echo htmlspecialchars($role['role_name']); ?>')"
                                                         data-role-id="<?php echo $role['role_id']; ?>">
                                                        <div class="role-title"><?php echo htmlspecialchars($role['role_name']); ?></div>
                                                        <div class="role-description"><?php echo htmlspecialchars($role['description'] ?? 'Role description'); ?></div>
                                                    </div>
                                                    <?php endwhile; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Action Buttons -->
                                <div class="row mt-4">
                                    <div class="col-12">
                                        <div class="d-flex justify-content-between">
                                            <a href="users.php" class="btn btn-outline-secondary">
                                                <i class="ri-arrow-left-line me-1"></i>Back to Users
                                            </a>
                                            <div>
                                                <button type="button" class="btn btn-outline-primary me-2" onclick="resetForm()">
                                                    <i class="ri-refresh-line me-1"></i>Reset Form
                                                </button>
                                                <button type="submit" class="btn create-user-btn" id="createUserBtn">
                                                    <i class="ri-user-add-line me-1"></i>Create User
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Form submission handler
    $('#createUserForm').on('submit', function(e) {
        e.preventDefault();
        
        // Validate form
        if (!validateForm()) {
            return;
        }
        
        const formData = new FormData(this);
        
        // Show loading
        Swal.fire({
            title: 'Creating User...',
            text: 'Please wait while we create the new user account.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'create_user.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'User Created!',
                        text: response.message,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'Create Another User',
                        cancelButtonText: 'Go to Users List'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            resetForm();
                        } else {
                            window.location.href = 'users.php';
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: response.message,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'An error occurred while creating the user.',
                    icon: 'error'
                });
            }
        });
    });
});

// Form validation
function validateForm() {
    const username = $('#username').val().trim();
    const email = $('#email').val().trim();
    const fullName = $('#full_name').val().trim();
    const password = $('#password').val();
    const confirmPassword = $('#confirm_password').val();
    const roleId = $('#role_id').val();
    
    if (!username || username.length < 3) {
        Swal.fire('Validation Error', 'Username must be at least 3 characters long', 'error');
        return false;
    }
    
    if (!email || !validateEmail(email)) {
        Swal.fire('Validation Error', 'Please enter a valid email address', 'error');
        return false;
    }
    
    if (!fullName) {
        Swal.fire('Validation Error', 'Full name is required', 'error');
        return false;
    }
    
    if (!password || password.length < 8) {
        Swal.fire('Validation Error', 'Password must be at least 8 characters long', 'error');
        return false;
    }
    
    if (password !== confirmPassword) {
        Swal.fire('Validation Error', 'Passwords do not match', 'error');
        return false;
    }
    
    if (!roleId) {
        Swal.fire('Validation Error', 'Please select a role for the user', 'error');
        return false;
    }
    
    return true;
}

// Email validation
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

// Check username availability
function checkUsername() {
    const username = $('#username').val().trim();
    const checkDiv = $('#usernameCheck');
    
    if (username.length < 3) {
        checkDiv.html('<small class="text-warning">Username must be at least 3 characters</small>');
        return;
    }
    
    // Simulate username check (in real implementation, make AJAX call)
    setTimeout(() => {
        checkDiv.html('<small class="text-success"><i class="ri-check-line"></i> Username is available</small>');
    }, 500);
}

// Check email availability
function checkEmail() {
    const email = $('#email').val().trim();
    const checkDiv = $('#emailCheck');
    
    if (!validateEmail(email)) {
        checkDiv.html('<small class="text-danger">Please enter a valid email address</small>');
        return;
    }
    
    // Simulate email check (in real implementation, make AJAX call)
    setTimeout(() => {
        checkDiv.html('<small class="text-success"><i class="ri-check-line"></i> Email is available</small>');
    }, 500);
}

// Password strength checker
function checkPasswordStrength() {
    const password = $('#password').val();
    const strengthFill = $('#strengthFill');
    const strengthText = $('#strengthText');
    
    let score = 0;
    let feedback = [];
    
    // Check requirements
    const requirements = {
        'req-length': password.length >= 8,
        'req-upper': /[A-Z]/.test(password),
        'req-lower': /[a-z]/.test(password),
        'req-number': /[0-9]/.test(password),
        'req-special': /[^A-Za-z0-9]/.test(password)
    };
    
    // Update requirement indicators
    for (const [reqId, met] of Object.entries(requirements)) {
        const element = $(`#${reqId}`);
        if (met) {
            element.removeClass('not-met').addClass('met');
            score++;
        } else {
            element.removeClass('met').addClass('not-met');
        }
    }
    
    // Update strength bar and text
    strengthFill.removeClass('strength-weak strength-fair strength-good strength-strong');
    
    if (score === 0) {
        strengthText.text('Enter password');
    } else if (score <= 2) {
        strengthFill.addClass('strength-weak');
        strengthText.text('Weak password').removeClass('text-muted').addClass('text-danger');
    } else if (score <= 3) {
        strengthFill.addClass('strength-fair');
        strengthText.text('Fair password').removeClass('text-muted text-danger').addClass('text-warning');
    } else if (score <= 4) {
        strengthFill.addClass('strength-good');
        strengthText.text('Good password').removeClass('text-muted text-danger text-warning').addClass('text-info');
    } else {
        strengthFill.addClass('strength-strong');
        strengthText.text('Strong password').removeClass('text-muted text-danger text-warning text-info').addClass('text-success');
    }
}

// Check password match
function checkPasswordMatch() {
    const password = $('#password').val();
    const confirmPassword = $('#confirm_password').val();
    const matchDiv = $('#passwordMatch');
    
    if (confirmPassword === '') {
        matchDiv.html('');
        return;
    }
    
    if (password === confirmPassword) {
        matchDiv.html('<small class="text-success"><i class="ri-check-line"></i> Passwords match</small>');
    } else {
        matchDiv.html('<small class="text-danger"><i class="ri-close-line"></i> Passwords do not match</small>');
    }
}

// Toggle password visibility
function togglePassword(fieldId) {
    const field = $(`#${fieldId}`);
    const icon = $(`#${fieldId}ToggleIcon`);
    
    if (field.attr('type') === 'password') {
        field.attr('type', 'text');
        icon.removeClass('ri-eye-off-line').addClass('ri-eye-line');
    } else {
        field.attr('type', 'password');
        icon.removeClass('ri-eye-line').addClass('ri-eye-off-line');
    }
}

// Role selection
function selectRole(roleId, roleName) {
    // Update hidden field
    $('#role_id').val(roleId);
    
    // Update visual selection
    $('.role-card').removeClass('selected');
    $(`.role-card[data-role-id="${roleId}"]`).addClass('selected');
    
    // Update preview
    $('#previewRole').text(roleName);
}

// Update avatar preview
function updateAvatarPreview() {
    const fullName = $('#full_name').val().trim();
    const email = $('#email').val().trim();
    
    if (fullName) {
        const initials = fullName.split(' ').map(name => name.charAt(0).toUpperCase()).join('').substring(0, 2);
        $('#avatarPreview').text(initials);
        $('#previewName').text(fullName);
    } else {
        $('#avatarPreview').html('<i class="ri-user-line"></i>');
        $('#previewName').text('New User');
    }
    
    if (email) {
        $('#previewEmail').text(email);
    } else {
        $('#previewEmail').text('user@example.com');
    }
}

// Reset form
function resetForm() {
    Swal.fire({
        title: 'Reset Form?',
        text: 'This will clear all entered information.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Reset',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $('#createUserForm')[0].reset();
            $('#role_id').val('');
            $('.role-card').removeClass('selected');
            $('#usernameCheck, #emailCheck, #passwordMatch').html('');
            $('#strengthFill').removeClass('strength-weak strength-fair strength-good strength-strong');
            $('#strengthText').text('Password strength').removeClass('text-danger text-warning text-info text-success').addClass('text-muted');
            $('.requirement').removeClass('met not-met');
            updateAvatarPreview();
            $('#previewRole').text('Select Role');
        }
    });
}

// Auto-update preview when email changes
$('#email').on('keyup', updateAvatarPreview);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>
        '