<?php
// user_control.php - WITH COLLEGE SELECTION FOR SPECIFIC ROLES
//遵照 National University Visual Identity Guidelines
session_start(); // Start session at the very beginning

// Disable error reporting for production
error_reporting(1);
ini_set('display_errors', 1);

// First, check if user is logged in
if (!isset($_SESSION['committee_id'])) {
    header('Location: admin_login.php');
    exit();
}

require 'db.php';
require 'helpers.php';

// Get the user's role - check all possible session variables
$userRole = '';
if (isset($_SESSION['user_role']) && !empty($_SESSION['user_role'])) {
    $userRole = $_SESSION['user_role'];
} elseif (isset($_SESSION['committee_role_name']) && !empty($_SESSION['committee_role_name'])) {
    $userRole = $_SESSION['committee_role_name'];
} else {
    // If role is not in session, get it from database
    $stmt = $mysqli1->prepare("SELECT role_name FROM committee_users WHERE id = ?");
    $stmt->bind_param("i", $_SESSION['committee_id']);
    if ($stmt->execute()) {
        $stmt->bind_result($dbRole);
        if ($stmt->fetch()) {
            $userRole = $dbRole ?: '';
            // Update session for future use
            $_SESSION['committee_role_name'] = $userRole;
            $_SESSION['user_role'] = $userRole;
        }
    }
    $stmt->close();
}

// Check if user is admin - support multiple admin role names
$adminRoles = ['admin', 'administrator', 'مدير', 'مسؤول'];
$userRoleLower = $userRole ? strtolower($userRole) : '';
$isAdmin = in_array($userRoleLower, array_map('strtolower', $adminRoles));

if (!$isAdmin) {
    $_SESSION['error'] = 'ليس لديك صلاحية للوصول إلى هذه الصفحة. تحتاج إلى دور "مدير" أو "مسؤول".';
    header('Location: admin_dashboard.php');
    exit();
}

// Helper function to get icon for each role
function getRoleIcon($roleName) {
    $roleIcons = [
        'admin' => 'user-shield',
        'administrator' => 'user-shield',
        'مدير' => 'user-shield',
        'مسؤول' => 'user-shield',
        'committee' => 'user-tie',
        'accountant' => 'calculator',
        'card_printing' => 'id-card',
        'viewer' => 'eye',
        'user' => 'user',
        'مشرف' => 'user-check',
        'dean' => 'user-graduate',
        'registrar' => 'user-tie'
    ];
    
    $roleLower = $roleName ? strtolower($roleName) : '';
    foreach ($roleIcons as $role => $icon) {
        if (strtolower($role) === $roleLower) {
            return $icon;
        }
    }
    
    return 'user';
}

// Helper function to check if role requires college selection
function roleRequiresCollege($roleName) {
    $rolesRequiringCollege = ['committee', 'dean', 'registrar', 'مسجل الكلية', 'عميد'];
    $roleLower = $roleName ? strtolower($roleName) : '';
    
    foreach ($rolesRequiringCollege as $role) {
        if (strtolower($role) === $roleLower) {
            return true;
        }
    }
    return false;
}

// Now we know user is admin, proceed with the page

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_user'])) {
        // Add new user
        $username = trim($_POST['username'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $password = $_POST['password'] ?? '';
        $can_view_all = isset($_POST['can_view_all']) ? 1 : 0;
        $college_id = !empty($_POST['college_id']) ? (int)$_POST['college_id'] : null;
        $role_id = (int)($_POST['role_id'] ?? 2); // Default to committee role
        $role_specific_college = !empty($_POST['role_specific_college']) ? (int)$_POST['role_specific_college'] : null;
        
        // Get role name
        $role_stmt = $mysqli1->prepare("SELECT role_name FROM users_roles WHERE role_id = ?");
        $role_stmt->bind_param("i", $role_id);
        $role_stmt->execute();
        $role_result = $role_stmt->get_result()->fetch_assoc();
        $role_name = $role_result['role_name'] ?? 'committee';
        $role_stmt->close();
        
        // If role requires college, use the role-specific college
        if (roleRequiresCollege($role_name) && $role_specific_college) {
            $college_id = $role_specific_college;
            $can_view_all = 0; // Cannot view all colleges if assigned to specific college
        }
        
        if (!empty($username) && !empty($password) && !empty($name)) {
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            
            $stmt = $mysqli1->prepare("
                INSERT INTO committee_users 
                (username, password_hash, name, can_view_all, college_id, role_id, role_name, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            $stmt->bind_param("sssiiss", $username, $password_hash, $name, $can_view_all, $college_id, $role_id, $role_name);
            
            if ($stmt->execute()) {
                $_SESSION['success'] = 'تم إضافة المستخدم بنجاح';
            } else {
                $_SESSION['error'] = 'خطأ في إضافة المستخدم: ' . ($stmt->error ?? '');
            }
            $stmt->close();
        } else {
            $_SESSION['error'] = 'الرجاء تعبئة جميع الحقول المطلوبة';
        }
    } elseif (isset($_POST['delete_user'])) {
        // Delete user
        $user_id = (int)($_POST['user_id'] ?? 0);
        if ($user_id > 0 && $user_id !== $_SESSION['committee_id']) {
            $stmt = $mysqli1->prepare("DELETE FROM committee_users WHERE id = ?");
            $stmt->bind_param("i", $user_id);
            if ($stmt->execute()) {
                $_SESSION['success'] = 'تم حذف المستخدم بنجاح';
            } else {
                $_SESSION['error'] = 'خطأ في حذف المستخدم';
            }
            $stmt->close();
        }
    } elseif (isset($_POST['reset_password'])) {
        // Reset password
        $user_id = (int)($_POST['user_id'] ?? 0);
        $new_password = $_POST['new_password'] ?? '';
        
        if (!empty($new_password)) {
            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $mysqli1->prepare("UPDATE committee_users SET password_hash = ? WHERE id = ?");
            $stmt->bind_param("si", $password_hash, $user_id);
            if ($stmt->execute()) {
                $_SESSION['success'] = 'تم تحديث كلمة المرور بنجاح';
            } else {
                $_SESSION['error'] = 'خطأ في تحديث كلمة المرور';
            }
            $stmt->close();
        }
    } elseif (isset($_POST['update_role'])) {
        // Update user role
        $user_id = (int)($_POST['user_id'] ?? 0);
        $new_role_id = (int)($_POST['new_role_id'] ?? 2);
        $role_specific_college = !empty($_POST['role_specific_college']) ? (int)$_POST['role_specific_college'] : null;
        
        if ($user_id > 0) {
            // Get role name
            $role_stmt = $mysqli1->prepare("SELECT role_name FROM users_roles WHERE role_id = ?");
            $role_stmt->bind_param("i", $new_role_id);
            $role_stmt->execute();
            $role_result = $role_stmt->get_result()->fetch_assoc();
            $role_name = $role_result['role_name'] ?? 'committee';
            $role_stmt->close();
            
            // Determine college_id and can_view_all based on role
            $college_id = null;
            $can_view_all = 1; // Default to view all
            
            if (roleRequiresCollege($role_name)) {
                if ($role_specific_college) {
                    $college_id = $role_specific_college;
                    $can_view_all = 0; // Cannot view all colleges if assigned to specific college
                } else {
                    // If role requires college but none selected, keep existing college
                    $existing_stmt = $mysqli1->prepare("SELECT college_id, can_view_all FROM committee_users WHERE id = ?");
                    $existing_stmt->bind_param("i", $user_id);
                    $existing_stmt->execute();
                    $existing_result = $existing_stmt->get_result()->fetch_assoc();
                    $existing_stmt->close();
                    
                    $college_id = $existing_result['college_id'] ?? null;
                    $can_view_all = $existing_result['can_view_all'] ?? 1;
                }
            } else {
                // For non-college roles, allow viewing all colleges
                $can_view_all = 1;
            }
            
            $stmt = $mysqli1->prepare("UPDATE committee_users SET role_id = ?, role_name = ?, college_id = ?, can_view_all = ? WHERE id = ?");
            $stmt->bind_param("isiii", $new_role_id, $role_name, $college_id, $can_view_all, $user_id);
            if ($stmt->execute()) {
                $_SESSION['success'] = 'تم تحديث دور المستخدم بنجاح';
            } else {
                $_SESSION['error'] = 'خطأ في تحديث دور المستخدم';
            }
            $stmt->close();
        }
    }
    
    header('Location: user_control.php');
    exit();
}

// Fetch all users
$users = [];
$users_stmt = $mysqli1->prepare("
    SELECT cu.*, c.name as college_name, ur.role_name 
    FROM committee_users cu
    LEFT JOIN colleges c ON c.id = cu.college_id
    LEFT JOIN users_roles ur ON ur.role_id = cu.role_id
    ORDER BY cu.created_at DESC
");
if ($users_stmt->execute()) {
    $users_result = $users_stmt->get_result();
    $users = $users_result->fetch_all(MYSQLI_ASSOC);
}
$users_stmt->close();

// Fetch colleges for dropdown
$colleges = [];
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($colleges_stmt->execute()) {
    $colleges_result = $colleges_stmt->get_result();
    $colleges = $colleges_result->fetch_all(MYSQLI_ASSOC);
}
$colleges_stmt->close();

// Fetch roles for dropdown
$roles = [];
$roles_stmt = $mysqli1->prepare("SELECT role_id, role_name FROM users_roles ORDER BY role_id");
if ($roles_stmt->execute()) {
    $roles_result = $roles_stmt->get_result();
    $roles = $roles_result->fetch_all(MYSQLI_ASSOC);
}
$roles_stmt->close();

// Get current user info for display
$current_user_id = $_SESSION['committee_id'];
$current_user_name = '';
$current_user_username = '';
$current_user_stmt = $mysqli1->prepare("SELECT name, username FROM committee_users WHERE id = ?");
$current_user_stmt->bind_param("i", $current_user_id);
if ($current_user_stmt->execute()) {
    $current_user_result = $current_user_stmt->get_result()->fetch_assoc();
    $current_user_name = $current_user_result['name'] ?? '';
    $current_user_username = $current_user_result['username'] ?? '';
}
$current_user_stmt->close();

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة المستخدمين | الجامعة الوطنية - السودان</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 6 Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        /* ============================================
           NATIONAL UNIVERSITY OFFICIAL COLORS
          遵照 Visual Identity Guide - Sudan
           Primary: #0056B3 (NU Blue)
           Accent: #FFC107 (Gold / Pantone 123)
           Dark Blue: #003366
           ============================================ */
        
        :root {
            --nu-blue: #0056B3;
            --nu-blue-dark: #003366;
            --nu-blue-light: #2596be;
            --nu-gold: #FFC107;
            --nu-gold-dark: #E6A800;
            --nu-gold-light: #FFD54F;
            --nu-white: #FFFFFF;
            --nu-light-bg: #F8FAFE;
            --nu-gray-light: #E9ECEF;
            --nu-gray: #ADB5BD;
            --nu-text-primary: #1A2C3E;
            --nu-text-secondary: #6C757D;
            --nu-success: #28A745;
            --nu-danger: #DC3545;
            --nu-warning: #FFC107;
            --nu-info: #17A2B8;
            --nu-shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.04);
            --nu-shadow-md: 0 4px 16px rgba(0, 0, 0, 0.06);
            --nu-shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --nu-transition: all 0.25s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Cairo', 'Noor', -apple-system, BlinkMacSystemFont, sans-serif;
            color: var(--nu-text-primary);
            background: linear-gradient(180deg, var(--nu-light-bg) 0%, #F1F4F9 100%);
            line-height: 1.5;
            direction: rtl;
            min-height: 100vh;
        }
        
        /* Top Accent Bar - Pantone 123 Gold */
        .nu-top-accent {
            height: 4px;
            background: linear-gradient(90deg, var(--nu-gold) 0%, var(--nu-gold-light) 50%, var(--nu-gold) 100%);
            width: 100%;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
        }
        
        /* ===== HEADER SECTION ===== */
        .nu-admin-header {
            background: var(--nu-white);
            border-radius: 16px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: var(--nu-shadow-sm);
            border: 1px solid rgba(0, 86, 179, 0.08);
        }
        
        .nu-admin-title {
            font-size: 1.2rem;
            font-weight: 700;
            color: var(--nu-blue-dark);
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .nu-admin-title i {
            color: var(--nu-gold);
            font-size: 1.3rem;
        }
        
        .nu-admin-subtitle {
            font-size: 0.8rem;
            color: var(--nu-text-secondary);
            margin: 0.25rem 0 0 0;
        }
        
        .nu-user-badge {
            background: linear-gradient(135deg, var(--nu-light-bg), var(--nu-white));
            border: 1px solid var(--nu-gray-light);
            border-radius: 12px;
            padding: 0.5rem 1rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .nu-user-badge i {
            color: var(--nu-gold);
            font-size: 1rem;
        }
        
        .nu-user-badge strong {
            color: var(--nu-blue);
        }
        
        /* ===== CARDS ===== */
        .nu-card {
            background: var(--nu-white);
            border-radius: 16px;
            margin-bottom: 1.5rem;
            overflow: hidden;
            box-shadow: var(--nu-shadow-sm);
            border: 1px solid rgba(0, 86, 179, 0.06);
            transition: var(--nu-transition);
        }
        
        .nu-card:hover {
            box-shadow: var(--nu-shadow-md);
        }
        
        .nu-card-header {
            background: var(--nu-white);
            border-bottom: 2px solid var(--nu-gold);
            padding: 0.85rem 1.25rem;
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }
        
        .nu-card-header i {
            color: var(--nu-blue);
            font-size: 1.1rem;
        }
        
        .nu-card-header h5 {
            font-size: 0.95rem;
            font-weight: 700;
            color: var(--nu-blue-dark);
            margin: 0;
        }
        
        .nu-card-body {
            padding: 1.25rem;
        }
        
        /* ===== FORM ELEMENTS ===== */
        .nu-form-label {
            font-size: 0.8rem;
            font-weight: 600;
            color: var(--nu-text-primary);
            margin-bottom: 0.3rem;
            display: block;
        }
        
        .nu-form-label i {
            color: var(--nu-gold);
            margin-left: 0.3rem;
        }
        
        .nu-form-control,
        .nu-form-select {
            width: 100%;
            padding: 0.55rem 0.85rem;
            font-size: 0.85rem;
            font-family: inherit;
            border: 1.5px solid var(--nu-gray-light);
            border-radius: 10px;
            transition: var(--nu-transition);
            background: var(--nu-white);
        }
        
        .nu-form-control:focus,
        .nu-form-select:focus {
            outline: none;
            border-color: var(--nu-blue);
            box-shadow: 0 0 0 3px rgba(0, 86, 179, 0.1);
        }
        
        /* ===== BUTTONS ===== */
        .nu-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 0.5rem 1.1rem;
            font-size: 0.8rem;
            font-weight: 600;
            font-family: inherit;
            text-decoration: none;
            border-radius: 10px;
            transition: var(--nu-transition);
            border: 1px solid transparent;
            cursor: pointer;
        }
        
        .nu-btn-primary {
            background: var(--nu-blue);
            color: var(--nu-white);
            border-color: var(--nu-blue);
        }
        
        .nu-btn-primary:hover {
            background: var(--nu-blue-dark);
            border-color: var(--nu-blue-dark);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 86, 179, 0.25);
        }
        
        .nu-btn-outline {
            background: transparent;
            color: var(--nu-blue);
            border-color: var(--nu-blue);
        }
        
        .nu-btn-outline:hover {
            background: var(--nu-blue);
            color: var(--nu-white);
            transform: translateY(-1px);
        }
        
        .nu-btn-outline-secondary {
            background: transparent;
            color: var(--nu-text-secondary);
            border-color: var(--nu-gray-light);
        }
        
        .nu-btn-outline-secondary:hover {
            background: var(--nu-gray-light);
            color: var(--nu-blue);
            border-color: var(--nu-blue);
        }
        
        .nu-btn-danger {
            background: transparent;
            color: var(--nu-danger);
            border-color: var(--nu-danger);
        }
        
        .nu-btn-danger:hover {
            background: var(--nu-danger);
            color: var(--nu-white);
        }
        
        .nu-btn-sm {
            padding: 0.35rem 0.8rem;
            font-size: 0.75rem;
        }
        
        /* ===== TABLE ===== */
        .nu-table-container {
            overflow-x: auto;
            border-radius: 12px;
        }
        
        .nu-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.8rem;
        }
        
        .nu-table th {
            background: linear-gradient(180deg, var(--nu-light-bg), #F1F4F9);
            color: var(--nu-blue-dark);
            font-weight: 700;
            padding: 0.85rem 0.6rem;
            border-bottom: 2px solid var(--nu-gold);
            text-align: right;
            white-space: nowrap;
        }
        
        .nu-table td {
            padding: 0.7rem 0.6rem;
            border-bottom: 1px solid var(--nu-gray-light);
            color: var(--nu-text-secondary);
            vertical-align: middle;
            white-space: nowrap;
        }
        
        .nu-table tr:hover td {
            background: rgba(0, 86, 179, 0.02);
        }
        
        /* ===== ROLE BADGES ===== */
        .nu-role-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            padding: 0.25rem 0.7rem;
            font-size: 0.7rem;
            font-weight: 600;
            border-radius: 30px;
            white-space: nowrap;
        }
        
        .nu-role-admin { background: linear-gradient(135deg, var(--nu-blue), var(--nu-blue-dark)); color: white; }
        .nu-role-committee { background: linear-gradient(135deg, #2E7D32, #1B5E20); color: white; }
        .nu-role-accountant { background: linear-gradient(135deg, #F57C00, #E65100); color: white; }
        .nu-role-card_printing { background: linear-gradient(135deg, #0097A7, #006064); color: white; }
        .nu-role-viewer { background: linear-gradient(135deg, #6C757D, #495057); color: white; }
        .nu-role-default { background: linear-gradient(135deg, var(--nu-gray), #6C757D); color: white; }
        
        /* ===== PERMISSION BADGES ===== */
        .nu-badge-success {
            background: linear-gradient(135deg, #28A745, #1E7E34);
            color: white;
            padding: 0.25rem 0.6rem;
            border-radius: 20px;
            font-size: 0.65rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .nu-badge-secondary {
            background: linear-gradient(135deg, var(--nu-gray), #6C757D);
            color: white;
            padding: 0.25rem 0.6rem;
            border-radius: 20px;
            font-size: 0.65rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .nu-badge-warning {
            background: linear-gradient(135deg, var(--nu-gold), var(--nu-gold-dark));
            color: var(--nu-blue-dark);
            padding: 0.25rem 0.6rem;
            border-radius: 20px;
            font-size: 0.65rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            font-weight: 600;
        }
        
        .nu-badge-info {
            background: linear-gradient(135deg, #17A2B8, #0F7A8A);
            color: white;
            padding: 0.25rem 0.6rem;
            border-radius: 20px;
            font-size: 0.65rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        /* ===== ACTION BUTTONS ===== */
        .nu-action-buttons {
            display: flex;
            gap: 0.4rem;
            justify-content: center;
        }
        
        .nu-action-btn {
            width: 30px;
            height: 30px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            background: transparent;
            border: 1px solid var(--nu-gray-light);
            color: var(--nu-text-secondary);
            transition: var(--nu-transition);
            cursor: pointer;
        }
        
        .nu-action-btn:hover {
            background: var(--nu-light-bg);
            color: var(--nu-blue);
            transform: translateY(-2px);
            border-color: var(--nu-blue);
        }
        
        .nu-action-btn-danger:hover {
            color: var(--nu-danger);
            border-color: var(--nu-danger);
        }
        
        .nu-action-btn-warning:hover {
            color: var(--nu-gold-dark);
            border-color: var(--nu-gold);
        }
        
        /* ===== STATISTICS CARDS ===== */
        .nu-stat-card {
            background: var(--nu-white);
            border: 1px solid rgba(0, 86, 179, 0.08);
            border-radius: 14px;
            padding: 0.9rem;
            transition: var(--nu-transition);
        }
        
        .nu-stat-card:hover {
            transform: translateY(-3px);
            box-shadow: var(--nu-shadow-md);
            border-color: var(--nu-gold);
        }
        
        .nu-stat-number {
            font-size: 1.6rem;
            font-weight: 800;
            margin: 0;
            color: var(--nu-blue-dark);
        }
        
        .nu-stat-label {
            font-size: 0.7rem;
            color: var(--nu-text-secondary);
            margin: 0;
        }
        
        /* ===== COLLEGE SELECTION CONTAINER ===== */
        .nu-college-container {
            display: none;
            margin-top: 0.75rem;
            padding: 0.85rem;
            background: var(--nu-light-bg);
            border-radius: 12px;
            border: 1px solid var(--nu-gray-light);
        }
        
        .nu-college-container label {
            font-size: 0.8rem;
            font-weight: 600;
            margin-bottom: 0.4rem;
            display: block;
            color: var(--nu-blue-dark);
        }
        
        /* ===== ALERTS ===== */
        .nu-alert {
            padding: 0.7rem 1rem;
            border-radius: 12px;
            font-size: 0.85rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }
        
        .nu-alert-success {
            background: linear-gradient(135deg, #D4EDDA, #C3E6CB);
            border: 1px solid #28A745;
            color: #155724;
        }
        
        .nu-alert-danger {
            background: linear-gradient(135deg, #F8D7DA, #F5C6CB);
            border: 1px solid #DC3545;
            color: #721C24;
        }
        
        .nu-alert-info {
            background: linear-gradient(135deg, #D1ECF1, #B8E4F0);
            border: 1px solid #17A2B8;
            color: #0C5460;
        }
        
        .nu-alert-warning {
            background: linear-gradient(135deg, #FFF3CD, #FFEAA7);
            border: 1px solid var(--nu-gold);
            color: #856404;
        }
        
        /* ===== MODAL ===== */
        .nu-modal-header {
            background: var(--nu-white);
            border-bottom: 2px solid var(--nu-gold);
            padding: 0.85rem 1.25rem;
        }
        
        .nu-modal-header h6 {
            font-size: 0.95rem;
            font-weight: 700;
            color: var(--nu-blue-dark);
            margin: 0;
        }
        
        .nu-modal-header i {
            color: var(--nu-gold);
        }
        
        /* ===== FOOTER ===== */
        .nu-footer {
            background: var(--nu-white);
            border-top: 1px solid var(--nu-gray-light);
            padding: 1.2rem 0;
            margin-top: 2rem;
            text-align: center;
            font-size: 0.75rem;
            color: var(--nu-text-secondary);
        }
        
        /* ===== UTILITY ===== */
        .text-gold { color: var(--nu-gold); }
        .text-blue { color: var(--nu-blue); }
        .cursor-help { cursor: help; }
        .bg-gold-light { background: rgba(255, 193, 7, 0.08); }
        
        .truncate-text {
            max-width: 130px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        /* ===== RESPONSIVE ===== */
        @media (max-width: 768px) {
            .nu-card-body { padding: 0.9rem; }
            .nu-table th, .nu-table td { padding: 0.5rem 0.35rem; font-size: 0.7rem; }
            .nu-action-btn { width: 26px; height: 26px; }
            .nu-stat-number { font-size: 1.2rem; }
            .nu-admin-header { padding: 0.8rem 1rem; }
            .nu-admin-title { font-size: 1rem; }
        }
        
        @media (max-width: 576px) {
            .truncate-text { max-width: 80px; }
            .nu-role-badge { padding: 0.2rem 0.4rem; font-size: 0.6rem; }
        }
    </style>
</head>
<body>

<!-- Top Accent Bar - Pantone 123 Gold -->
<div class="nu-top-accent"></div>

<div class="container py-3" dir="rtl">

    <!-- Admin Header -遵照 Official Colors -->
    <div class="nu-admin-header">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
            <div>
                <h1 class="nu-admin-title">
                    <i class="fas fa-users-cog"></i>
                    إدارة المستخدمين
                </h1>
                <p class="nu-admin-subtitle">
                    <i class="fas fa-user-shield me-1"></i>
                    مرحباً <?= e($current_user_name) ?> · صلاحيات المسؤول
                </p>
            </div>
            
            <div class="nu-user-badge">
                <i class="fas fa-crown"></i>
                <span>الدور: <strong><?= e($userRole) ?></strong></span>
                 <a href="admin_dashboard.php" class="nu-btn nu-btn-outline">
        <i class="fas fa-arrow-right"></i>
        العودة إلى لوحة التحكم
    </a>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="nu-alert nu-alert-success">
            <i class="fas fa-check-circle fa-lg"></i>
            <?= e($_SESSION['success']) ?>
            <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" style="font-size: 0.7rem;"></button>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="nu-alert nu-alert-danger">
            <i class="fas fa-exclamation-triangle fa-lg"></i>
            <?= e($_SESSION['error']) ?>
            <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" style="font-size: 0.7rem;"></button>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <!-- Add User Card -->
    <div class="nu-card">
        <div class="nu-card-header">
            <i class="fas fa-user-plus"></i>
            <h5>إضافة مستخدم جديد</h5>
        </div>
        <div class="nu-card-body">
            <form method="post" id="addUserForm" onsubmit="return validateAddUserForm()">
                <div class="row g-3">
                    <div class="col-md-3 col-sm-6">
                        <label class="nu-form-label"><i class="fas fa-user"></i> اسم المستخدم</label>
                        <input type="text" class="nu-form-control" name="username" required placeholder="اسم المستخدم">
                    </div>
                    <div class="col-md-3 col-sm-6">
                        <label class="nu-form-label"><i class="fas fa-user-circle"></i> الاسم الكامل</label>
                        <input type="text" class="nu-form-control" name="name" required placeholder="الاسم الكامل">
                    </div>
                    <div class="col-md-3 col-sm-6">
                        <label class="nu-form-label"><i class="fas fa-key"></i> كلمة المرور</label>
                        <div class="input-group">
                            <input type="password" class="nu-form-control" name="password" id="password" required placeholder="كلمة المرور">
                            <button type="button" class="nu-btn nu-btn-outline-secondary nu-btn-sm" onclick="togglePassword('password')">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-6">
                        <label class="nu-form-label"><i class="fas fa-tag"></i> الدور</label>
                        <select class="nu-form-select" name="role_id" id="role_id" required onchange="toggleCollegeSelection(this.value, 'add')">
                            <?php foreach ($roles as $role): ?>
                                <option value="<?= $role['role_id'] ?>" <?= ($role['role_name'] ?? '') == 'committee' ? 'selected' : '' ?>>
                                    <?= e($role['role_name'] ?? '') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- College Selection Container -->
                    <div class="col-12">
                        <div id="collegeSelectAdd" class="nu-college-container">
                            <label><i class="fas fa-university"></i> اختر الكلية التابع لها</label>
                            <select class="nu-form-select" name="role_specific_college" id="role_specific_college">
                                <option value="">-- اختر الكلية --</option>
                                <?php foreach ($colleges as $college): ?>
                                    <option value="<?= $college['id'] ?>"><?= e($college['name'] ?? '') ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted" style="font-size: 0.7rem;">مطلوب للمستخدمين ذوي الأدوار المحددة (مسجل الكلية، عميد، إلخ)</small>
                        </div>
                    </div>
                    
                    <div class="col-12">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_view_all" id="can_view_all" value="1" checked>
                            <label class="form-check-label" for="can_view_all" style="font-size: 0.8rem;">
                                <i class="fas fa-eye text-gold"></i>
                                صلاحية مشاهدة جميع الكليات
                            </label>
                        </div>
                    </div>
                    
                    <div class="col-12">
                        <div class="d-flex justify-content-end gap-2">
                            <button type="reset" class="nu-btn nu-btn-outline-secondary nu-btn-sm">
                                <i class="fas fa-eraser"></i> مسح
                            </button>
                            <button type="submit" name="add_user" class="nu-btn nu-btn-primary nu-btn-sm">
                                <i class="fas fa-save"></i> إضافة مستخدم
                            </button>
                             
    <a href="admin_dashboard.php" class="nu-btn nu-btn-outline">
        <i class="fas fa-arrow-right"></i>
        العودة إلى لوحة التحكم
    </a>

                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Users List Card -->
    <div class="nu-card">
        <div class="nu-card-header">
            <i class="fas fa-list"></i>
            <h5>قائمة المستخدمين <span class="text-gold">(<?= count($users) ?>)</span></h5>
        </div>
        
        <div class="nu-card-body">
            <?php if (empty($users)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                    <p class="text-muted">لا يوجد مستخدمين</p>
                </div>
            <?php else: ?>
                <div class="nu-table-container">
                    <table class="nu-table">
                        <thead>
                            <tr>
                                <th style="width: 35px;">#</th>
                                <th>المستخدم</th>
                                <th>الاسم</th>
                                <th>الدور</th>
                                <th>الكلية</th>
                                <th>الصلاحيات</th>
                                <th>تاريخ التسجيل</th>
                                <th>آخر دخول</th>
                                <th style="width: 100px;">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $index => $user): 
                                $isCurrentUser = ($user['id'] == $current_user_id);
                                $roleName = $user['role_name'] ?? '';
                                $collegeName = $user['college_name'] ?? 'الكل';
                                $lastLogin = $user['last_login'] ?? null;
                                $createdAt = $user['created_at'] ?? '';
                                
                                // Role badge class
                                $roleBadgeClass = 'nu-role-default';
                                $roleLower = strtolower($roleName);
                                if (in_array($roleLower, ['admin', 'administrator', 'مدير', 'مسؤول'])) $roleBadgeClass = 'nu-role-admin';
                                elseif ($roleLower == 'committee') $roleBadgeClass = 'nu-role-committee';
                                elseif ($roleLower == 'accountant') $roleBadgeClass = 'nu-role-accountant';
                                elseif ($roleLower == 'card_printing') $roleBadgeClass = 'nu-role-card_printing';
                                elseif ($roleLower == 'viewer') $roleBadgeClass = 'nu-role-viewer';
                                
                                // Format dates
                                $createdDate = !empty($createdAt) ? date('Y-m-d', strtotime($createdAt)) : '--';
                                $lastLoginDate = !empty($lastLogin) ? date('Y-m-d H:i', strtotime($lastLogin)) : 'لم يدخل بعد';
                                $lastLoginClass = !empty($lastLogin) ? 'nu-badge-info' : 'nu-badge-warning';
                                $lastLoginIcon = !empty($lastLogin) ? 'fa-sign-in-alt' : 'fa-clock';
                            ?>
                                <tr class="<?= $isCurrentUser ? 'bg-gold-light' : '' ?>">
                                    <td class="fw-bold text-gold"><?= $index + 1 ?></td>
                                    <td class="truncate-text" title="<?= e($user['username'] ?? '') ?>">
                                        <i class="fas fa-user-circle text-gold me-1"></i>
                                        <?= e($user['username'] ?? '') ?>
                                        <?php if ($isCurrentUser): ?>
                                            <span class="badge bg-info ms-1" style="font-size: 0.6rem;">أنت</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="truncate-text" title="<?= e($user['name'] ?? '') ?>">
                                        <?= e($user['name'] ?? '') ?>
                                    </td>
                                    <td>
                                        <span class="nu-role-badge <?= $roleBadgeClass ?>">
                                            <i class="fas fa-<?= getRoleIcon($roleName) ?>"></i>
                                            <?= e(mb_strlen($roleName) > 10 ? mb_substr($roleName, 0, 8) . '...' : $roleName) ?>
                                        </span>
                                    </td>
                                    <td class="truncate-text" title="<?= e($collegeName) ?>">
                                        <i class="fas fa-university text-muted me-1"></i>
                                        <?= e(mb_strlen($collegeName) > 12 ? mb_substr($collegeName, 0, 10) . '...' : $collegeName) ?>
                                    </td>
                                    <td>
                                        <?php if (($user['can_view_all'] ?? 0) == 1): ?>
                                            <span class="nu-badge-success">
                                                <i class="fas fa-eye"></i> الكل
                                            </span>
                                        <?php else: ?>
                                            <span class="nu-badge-secondary">
                                                <i class="fas fa-university"></i> محدد
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-nowrap">
                                        <i class="far fa-calendar-alt text-muted me-1"></i>
                                        <?= $createdDate ?>
                                    </td>
                                    <td>
                                        <span class="<?= $lastLoginClass ?>">
                                            <i class="fas <?= $lastLoginIcon ?>"></i>
                                            <?= $lastLoginDate ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="nu-action-buttons">
                                            <!-- Change Role Button -->
                                            <button type="button" class="nu-action-btn" data-bs-toggle="modal" 
                                                    data-bs-target="#changeRoleModal<?= $user['id'] ?? '' ?>" 
                                                    <?= $isCurrentUser ? 'disabled' : '' ?> title="تغيير الدور">
                                                <i class="fas fa-user-tag"></i>
                                            </button>
                                            
                                            <!-- Reset Password Button -->
                                            <button type="button" class="nu-action-btn nu-action-btn-warning" data-bs-toggle="modal" 
                                                    data-bs-target="#resetPasswordModal<?= $user['id'] ?? '' ?>" title="تغيير كلمة المرور">
                                                <i class="fas fa-key"></i>
                                            </button>
                                            
                                            <?php if (!$isCurrentUser): ?>
                                                <form method="post" class="d-inline" onsubmit="return confirmDeleteUser('<?= e($user['name'] ?? '') ?>')">
                                                    <input type="hidden" name="user_id" value="<?= $user['id'] ?? '' ?>">
                                                    <button type="submit" name="delete_user" class="nu-action-btn nu-action-btn-danger" title="حذف المستخدم">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <span class="nu-action-btn disabled" title="لا يمكن تعديل حسابك">
                                                    <i class="fas fa-user"></i>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- Change Role Modal -->
                                        <div class="modal fade" id="changeRoleModal<?= $user['id'] ?? '' ?>" tabindex="-1">
                                            <div class="modal-dialog modal-dialog-centered">
                                                <div class="modal-content">
                                                    <form method="post" id="changeRoleForm<?= $user['id'] ?? '' ?>">
                                                        <div class="modal-header nu-modal-header">
                                                            <h6 class="modal-title">
                                                                <i class="fas fa-user-tag me-2"></i>
                                                                تغيير دور <?= e($user['name'] ?? '') ?>
                                                            </h6>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <div class="modal-body p-3">
                                                            <input type="hidden" name="user_id" value="<?= $user['id'] ?? '' ?>">
                                                            <div class="mb-3">
                                                                <label class="nu-form-label">اختر الدور الجديد</label>
                                                                <select class="nu-form-select" name="new_role_id" id="new_role_id_<?= $user['id'] ?? '' ?>" 
                                                                        required onchange="toggleCollegeSelectionUpdate(this.value, '<?= $user['id'] ?? '' ?>')">
                                                                    <?php foreach ($roles as $role): ?>
                                                                        <option value="<?= $role['role_id'] ?>" <?= ($user['role_id'] ?? 0) == $role['role_id'] ? 'selected' : '' ?>>
                                                                            <?= e($role['role_name'] ?? '') ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>
                                                            
                                                            <div id="collegeSelectUpdate<?= $user['id'] ?? '' ?>" class="nu-college-container" style="<?= roleRequiresCollege($roleName) ? '' : 'display: none;' ?>">
                                                                <label><i class="fas fa-university"></i> اختر الكلية التابع لها</label>
                                                                <select class="nu-form-select" name="role_specific_college">
                                                                    <option value="">-- اختر الكلية --</option>
                                                                    <?php foreach ($colleges as $college): ?>
                                                                        <option value="<?= $college['id'] ?>" <?= ($user['college_id'] ?? 0) == $college['id'] ? 'selected' : '' ?>>
                                                                            <?= e($college['name'] ?? '') ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                                <small class="text-muted" style="font-size: 0.7rem;">مطلوب للمستخدمين ذوي الأدوار المحددة</small>
                                                            </div>
                                                            
                                                            <div class="nu-alert nu-alert-info mt-3">
                                                                <i class="fas fa-info-circle"></i>
                                                                سيتم تحديث صلاحيات المستخدم فوراً بعد التغيير
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer py-2">
                                                            <button type="button" class="nu-btn nu-btn-outline-secondary nu-btn-sm" data-bs-dismiss="modal">إلغاء</button>
                                                            <button type="submit" name="update_role" class="nu-btn nu-btn-primary nu-btn-sm">حفظ التغييرات</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Reset Password Modal -->
                                        <div class="modal fade" id="resetPasswordModal<?= $user['id'] ?? '' ?>" tabindex="-1">
                                            <div class="modal-dialog modal-dialog-centered">
                                                <div class="modal-content">
                                                    <form method="post" onsubmit="return validatePasswordReset('<?= $user['id'] ?? '' ?>')">
                                                        <div class="modal-header nu-modal-header">
                                                            <h6 class="modal-title">
                                                                <i class="fas fa-key me-2"></i>
                                                                تغيير كلمة مرور <?= e($user['name'] ?? '') ?>
                                                            </h6>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <div class="modal-body p-3">
                                                            <input type="hidden" name="user_id" value="<?= $user['id'] ?? '' ?>">
                                                            <div class="mb-3">
                                                                <label class="nu-form-label">كلمة المرور الجديدة</label>
                                                                <div class="input-group">
                                                                    <input type="password" class="nu-form-control" name="new_password" id="new_password_<?= $user['id'] ?? '' ?>" required minlength="6" placeholder="كلمة المرور الجديدة">
                                                                    <button type="button" class="nu-btn nu-btn-outline-secondary nu-btn-sm" onclick="togglePassword('new_password_<?= $user['id'] ?? '' ?>')">
                                                                        <i class="fas fa-eye"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label class="nu-form-label">تأكيد كلمة المرور</label>
                                                                <div class="input-group">
                                                                    <input type="password" class="nu-form-control" id="confirm_password_<?= $user['id'] ?? '' ?>" required minlength="6" placeholder="تأكيد كلمة المرور">
                                                                    <button type="button" class="nu-btn nu-btn-outline-secondary nu-btn-sm" onclick="togglePassword('confirm_password_<?= $user['id'] ?? '' ?>')">
                                                                        <i class="fas fa-eye"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer py-2">
                                                            <button type="button" class="nu-btn nu-btn-outline-secondary nu-btn-sm" data-bs-dismiss="modal">إلغاء</button>
                                                            <button type="submit" name="reset_password" class="nu-btn nu-btn-primary nu-btn-sm">حفظ التغييرات</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Statistics Summary -->
                <?php
                $adminCount = 0;
                $committeeCount = 0;
                $collegeSpecificCount = 0;
                $activeUsersCount = 0;
                foreach ($users as $user) {
                    $roleLower = isset($user['role_name']) ? strtolower($user['role_name']) : '';
                    if (in_array($roleLower, ['admin', 'administrator', 'مدير', 'مسؤول'])) $adminCount++;
                    if ($roleLower === 'committee') $committeeCount++;
                    if (($user['can_view_all'] ?? 0) == 0 && !empty($user['college_id'])) $collegeSpecificCount++;
                    if (!empty($user['last_login'])) $activeUsersCount++;
                }
                ?>
                <div class="row g-3 mt-3">
                    <div class="col-md-3 col-6">
                        <div class="nu-stat-card">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <p class="nu-stat-number"><?= count($users) ?></p>
                                    <p class="nu-stat-label"><i class="fas fa-users text-gold me-1"></i>إجمالي المستخدمين</p>
                                </div>
                                <i class="fas fa-users fa-2x text-gold opacity-30"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-6">
                        <div class="nu-stat-card">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <p class="nu-stat-number"><?= $adminCount ?></p>
                                    <p class="nu-stat-label"><i class="fas fa-user-shield text-gold me-1"></i>مسؤولين</p>
                                </div>
                                <i class="fas fa-user-shield fa-2x text-gold opacity-30"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-6">
                        <div class="nu-stat-card">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <p class="nu-stat-number"><?= $committeeCount ?></p>
                                    <p class="nu-stat-label"><i class="fas fa-user-tie text-gold me-1"></i>مسجلين</p>
                                </div>
                                <i class="fas fa-user-tie fa-2x text-gold opacity-30"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 col-6">
                        <div class="nu-stat-card">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <p class="nu-stat-number"><?= $activeUsersCount ?></p>
                                    <p class="nu-stat-label"><i class="fas fa-check-circle text-gold me-1"></i>مستخدمين نشطين</p>
                                </div>
                                <i class="fas fa-check-circle fa-2x text-gold opacity-30"></i>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Security Notice -->
    <div class="nu-alert nu-alert-warning">
        <i class="fas fa-shield-alt fa-lg"></i>
        <div>
            <strong>ملاحظات أمنية:</strong>
            <span class="mx-2">•</span> تحديث الأدوار بحذر
            <span class="mx-2">•</span> تعيين الكلية للمسجلين
            <span class="mx-2">•</span> حذف الحسابات غير النشطة
            <span class="mx-2">•</span> تغيير كلمات المرور دورياً
        </div>
    </div>

</div>

<!-- Footer -->
<footer class="nu-footer">
    <div class="container">
        <p>الجامعة الوطنية - السودان | National University - Sudan</p>
        <p style="font-size: 0.65rem;">© 2025 Visual Identity Guidelines v.December 2025 | نظام إدارة المستخدمين</p>
    </div>
</footer>

<!-- Bootstrap JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Toggle password visibility
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    if (!input) return;
    const icon = input.nextElementSibling?.querySelector('i');
    if (input.type === 'password') {
        input.type = 'text';
        if (icon) { icon.classList.remove('fa-eye'); icon.classList.add('fa-eye-slash'); }
    } else {
        input.type = 'password';
        if (icon) { icon.classList.remove('fa-eye-slash'); icon.classList.add('fa-eye'); }
    }
}

// Roles that require college selection
const COLLEGE_REQUIRED_ROLES = ['committee', 'dean', 'registrar', 'مسجل الكلية', 'عميد'];

function roleRequiresCollege(roleName) {
    return COLLEGE_REQUIRED_ROLES.some(role => 
        roleName.toLowerCase().includes(role.toLowerCase()) || 
        role.toLowerCase().includes(roleName.toLowerCase())
    );
}

function toggleCollegeSelection(roleId, formType) {
    const selectElement = formType === 'add' ? 
        document.getElementById('role_id') : 
        document.getElementById('new_role_id_' + formType);
    if (!selectElement) return;
    
    const selectedOption = selectElement.options[selectElement.selectedIndex];
    const roleName = selectedOption.text.trim();
    
    const collegeContainer = formType === 'add' ? 
        document.getElementById('collegeSelectAdd') : 
        document.getElementById('collegeSelectUpdate' + formType);
    
    if (!collegeContainer) return;
    
    if (roleRequiresCollege(roleName)) {
        collegeContainer.style.display = 'block';
        const viewAllCheckbox = document.getElementById('can_view_all');
        if (viewAllCheckbox) { viewAllCheckbox.checked = false; viewAllCheckbox.disabled = true; }
    } else {
        collegeContainer.style.display = 'none';
        const viewAllCheckbox = document.getElementById('can_view_all');
        if (viewAllCheckbox) { viewAllCheckbox.disabled = false; }
    }
}

function toggleCollegeSelectionUpdate(roleId, userId) { toggleCollegeSelection(roleId, userId); }

function validateAddUserForm() {
    const password = document.getElementById('password');
    if (password && password.value.length < 6) {
        alert('كلمة المرور يجب أن تحتوي على 6 أحرف على الأقل');
        password.focus();
        return false;
    }
    
    const roleSelect = document.getElementById('role_id');
    const selectedRole = roleSelect.options[roleSelect.selectedIndex].text.trim();
    if (roleRequiresCollege(selectedRole)) {
        const collegeSelect = document.getElementById('role_specific_college');
        if (!collegeSelect || !collegeSelect.value) {
            alert('يجب اختيار الكلية للمستخدمين ذوي الأدوار المحددة');
            collegeSelect.focus();
            return false;
        }
    }
    return true;
}

function validatePasswordReset(userId) {
    const newPassword = document.getElementById('new_password_' + userId);
    const confirmPassword = document.getElementById('confirm_password_' + userId);
    if (!newPassword || !confirmPassword) return false;
    if (newPassword.value.length < 6) {
        alert('كلمة المرور الجديدة يجب أن تحتوي على 6 أحرف على الأقل');
        newPassword.focus();
        return false;
    }
    if (newPassword.value !== confirmPassword.value) {
        alert('كلمتا المرور غير متطابقتين');
        confirmPassword.focus();
        return false;
    }
    return true;
}

function confirmDeleteUser(userName) {
    return confirm(`هل أنت متأكد من حذف المستخدم "${userName}"؟\n\nهذا الإجراء لا يمكن التراجع عنه.`);
}

document.addEventListener('DOMContentLoaded', function() {
    const initialRoleSelect = document.getElementById('role_id');
    if (initialRoleSelect) toggleCollegeSelection(initialRoleSelect.value, 'add');
    
    <?php foreach ($users as $user): ?>
        const updateRoleSelect<?= $user['id'] ?? '' ?> = document.getElementById('new_role_id_<?= $user['id'] ?? '' ?>');
        if (updateRoleSelect<?= $user['id'] ?? '' ?>) toggleCollegeSelectionUpdate(updateRoleSelect<?= $user['id'] ?? '' ?>.value, '<?= $user['id'] ?? '' ?>');
        
        const updateForm<?= $user['id'] ?? '' ?> = document.getElementById('changeRoleForm<?= $user['id'] ?? '' ?>');
        if (updateForm<?= $user['id'] ?? '' ?>) {
            updateForm<?= $user['id'] ?? '' ?>.addEventListener('submit', function(e) {
                const roleSelect = document.getElementById('new_role_id_<?= $user['id'] ?? '' ?>');
                const selectedRole = roleSelect.options[roleSelect.selectedIndex].text.trim();
                if (roleRequiresCollege(selectedRole)) {
                    const collegeContainer = document.getElementById('collegeSelectUpdate<?= $user['id'] ?? '' ?>');
                    const collegeSelect = collegeContainer.querySelector('select[name="role_specific_college"]');
                    if (!collegeSelect || !collegeSelect.value) {
                        alert('يجب اختيار الكلية للمستخدمين ذوي الأدوار المحددة');
                        e.preventDefault();
                    }
                }
            });
        }
    <?php endforeach; ?>
});
</script>

</body>
</html>
