<?php
// user_control.php - WITH COLLEGE SELECTION FOR SPECIFIC ROLES
session_start(); // Start session at the very beginning

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

// 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" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
        }
        
        .user-card {
            border: 1px solid #dee2e6;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            background: #fff;
        }
        
        .user-role-badge {
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 0.7rem;
            font-weight: 600;
            display: inline-block;
            white-space: nowrap;
        }
        
        .role-admin { background: #dc2626; color: white; }
        .role-committee { background: #3b82f6; color: white; }
        .role-viewer { background: #10b981; color: white; }
        .role-accountant { background: #f59e0b; color: white; }
        .role-card_printing { background: #8b5cf6; color: white; }
        
        .admin-panel {
            border-left: 4px solid #dc2626;
            background: #fef2f2;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 15px;
        }
        
        .current-user-info {
            background: #e6f7ff;
            border: 1px solid #91d5ff;
            border-radius: 6px;
            padding: 8px 12px;
            margin-bottom: 15px;
        }
        
        /* SUPER COMPACT ACTION BUTTONS - AWESOME ICONS */
        .icon-actions {
            display: flex;
            gap: 6px;
            justify-content: center;
        }
        
        .icon-actions .btn {
            width: 32px;
            height: 32px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
            border-radius: 4px;
            background: none;
            border: 1px solid #dee2e6;
            color: #6c757d;
            transition: all 0.2s ease;
        }
        
        .icon-actions .btn i {
            font-size: 0.9rem;
        }
        
        /* Hover effects - subtle and clean */
        .icon-actions .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            background-color: #f8f9fa;
            color: #495057;
        }
        
        /* Specific icon hover colors - keep icons but add subtle background on hover */
        .icon-actions .btn:hover i.fa-user-tag {
            color: #0dcaf0;
        }
        
        .icon-actions .btn:hover i.fa-key {
            color: #ffc107;
        }
        
        .icon-actions .btn:hover i.fa-trash {
            color: #dc3545;
        }
        
        .icon-actions .btn:hover i.fa-user {
            color: #6c757d;
        }
        
        .icon-actions .btn:disabled {
            opacity: 0.3;
            cursor: not-allowed;
            transform: none !important;
            box-shadow: none !important;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
            font-size: 0.8rem;
            padding: 8px 4px;
            white-space: nowrap;
        }
        
        .table td {
            padding: 8px 4px;
            font-size: 0.8rem;
            vertical-align: middle;
            white-space: nowrap;
        }
        
        .table tbody tr:hover {
            background-color: #f8f9fa;
        }
        
        .compact-text {
            font-size: 0.75rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .compact-role {
            max-width: 90px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .date-compact {
            font-size: 0.75rem;
            white-space: nowrap;
        }
        
        /* Table layout */
        .table-responsive table {
            table-layout: fixed;
            width: 100%;
        }
        
        /* Column widths */
        .col-index { width: 35px; }
        .col-username { width: 100px; }
        .col-name { width: 130px; }
        .col-role { width: 85px; }
        .col-college { width: 100px; }
        .col-permissions { width: 80px; }
        .col-created { width: 70px; }
        .col-lastlogin { width: 85px; }
        .col-actions { width: 110px; }
        
        /* College selection for specific roles */
        .college-select-container {
            display: none;
            margin-top: 8px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
            border: 1px solid #dee2e6;
        }
        
        .college-select-container label {
            font-size: 0.85rem;
            font-weight: 600;
            margin-bottom: 4px;
            color: #495057;
        }
        
        /* Role-specific styling */
        .role-college {
            font-size: 0.7rem;
            color: #6c757d;
            margin-top: 2px;
        }
        
        /* Modal adjustments */
        .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
        
        .modal-footer {
            padding: 10px 15px;
        }
        
        /* Badge adjustments */
        .badge {
            font-size: 0.65rem;
            padding: 2px 5px;
        }
        
        /* Form adjustments */
        .form-control-sm, .form-select-sm {
            font-size: 0.85rem;
        }
        
        /* Tooltip adjustments */
        .tooltip-inner {
            font-size: 0.75rem;
            padding: 4px 8px;
        }
        
        /* Statistics cards */
        .stat-card {
            transition: transform 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        /* Truncated text with tooltip */
        .truncate-text {
            cursor: help;
        }
        
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body>
<div class="container py-3" dir="rtl">
    <!-- Admin Panel Header -->
    <div class="admin-panel">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h3 class="fw-bold mb-1" style="font-size: 1.2rem;">
                    <i class="fas fa-users-cog me-2"></i>
                    إدارة المستخدمين
                </h3>
                <p class="mb-0 text-muted" style="font-size: 0.8rem;">مرحباً <?= e($current_user_name) ?> - صلاحيات المسؤول</p>
            </div>
            <a href="admin_dashboard.php" class="btn btn-outline-secondary btn-sm">
                <i class="fas fa-arrow-right"></i>
            </a>
        </div>
    </div>
    
    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert" style="padding: 8px 12px; font-size: 0.85rem;">
            <i class="fas fa-check-circle me-2"></i>
            <?= e($_SESSION['success']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert" style="padding: 8px 12px; font-size: 0.85rem;">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?= e($_SESSION['error']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>
    
    <!-- Current User Info -->
    <div class="current-user-info" style="padding: 6px 10px;">
        <div class="d-flex align-items-center">
            <div class="me-2">
                <i class="fas fa-user-shield text-primary"></i>
            </div>
            <div>
                <h6 class="mb-0 fw-bold" style="font-size: 0.85rem;">أنت: <span class="text-primary"><?= e($userRole) ?></span></h6>
            </div>
        </div>
    </div>

    <!-- Add User Form -->
    <div class="card mb-3 border-primary">
        <div class="card-header bg-primary text-white py-2">
            <h5 class="mb-0" style="font-size: 0.95rem;">
                <i class="fas fa-user-plus me-2"></i>
                إضافة مستخدم جديد
            </h5>
        </div>
        <div class="card-body p-3">
            <form method="post" id="addUserForm" onsubmit="return validateAddUserForm()">
                <div class="row g-2">
                    <div class="col-md-3">
                        <label class="form-label fw-semibold mb-1" style="font-size: 0.85rem;">
                            اسم المستخدم
                        </label>
                        <input type="text" class="form-control form-control-sm" name="username" required 
                               placeholder="اسم المستخدم">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-semibold mb-1" style="font-size: 0.85rem;">
                            الاسم الكامل
                        </label>
                        <input type="text" class="form-control form-control-sm" name="name" required 
                               placeholder="الاسم الكامل">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-semibold mb-1" style="font-size: 0.85rem;">
                            كلمة المرور
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="password" class="form-control" name="password" id="password" required 
                                   placeholder="كلمة المرور">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="togglePassword('password')">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label fw-semibold mb-1" style="font-size: 0.85rem;">
                            الدور
                        </label>
                        <select class="form-select form-select-sm" name="role_id" id="role_id" required 
                                onchange="toggleCollegeSelection(this.value, 'add')">
                            <?php foreach ($roles as $role): 
                                $roleName = $role['role_name'] ?? '';
                                $roleIcon = getRoleIcon($roleName);
                            ?>
                                <option value="<?= $role['role_id'] ?>" 
                                    <?= $roleName == 'committee' ? 'selected' : '' ?>>
                                    <i class="fas fa-<?= $roleIcon ?> me-1"></i>
                                    <?= e($roleName) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- College Selection for Specific Roles (Initially Hidden) -->
                    <div class="col-12 mt-2">
                        <div id="collegeSelectAdd" class="college-select-container">
                            <label class="form-label fw-semibold mb-1" style="font-size: 0.85rem;">
                                <i class="fas fa-university me-1"></i>
                                اختر الكلية التابع لها
                            </label>
                            <select class="form-select form-select-sm" 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.75rem;">
                                يجب اختيار الكلية للمستخدمين ذوي الأدوار المحددة (مسجل الكلية، عميد، إلخ)
                            </small>
                        </div>
                    </div>
                    
                    <div class="col-12 mt-2">
                        <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 fw-semibold" for="can_view_all" style="font-size: 0.85rem;">
                                صلاحية مشاهدة جميع الكليات
                            </label>
                            <small class="text-muted d-block" style="font-size: 0.75rem;">
                                (سيتم إلغاء هذا الخيار تلقائياً إذا تم اختيار دور يتطلب كلية محددة)
                            </small>
                        </div>
                    </div>
                    
                    <div class="col-12 mt-2">
                        <div class="d-flex justify-content-end gap-2">
                            <button type="reset" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-eraser me-1"></i>
                                مسح
                            </button>
                            <button type="submit" name="add_user" class="btn btn-primary btn-sm">
                                <i class="fas fa-save me-1"></i>
                                إضافة
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Users List -->
    <div class="card shadow-sm">
        <div class="card-header bg-secondary text-white py-2">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0" style="font-size: 0.95rem;">
                    <i class="fas fa-list me-2"></i>
                    قائمة المستخدمين (<?= count($users) ?>)
                </h5>
            </div>
        </div>
        <div class="card-body p-2">
            <?php if (empty($users)): ?>
                <div class="text-center py-3">
                    <i class="fas fa-users fa-lg text-muted mb-2"></i>
                    <h6 class="text-muted">لا يوجد مستخدمين</h6>
                </div>
            <?php else: ?>
                <div class="table-responsive" style="font-size: 0.8rem;">
                    <table class="table table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="col-index text-center">#</th>
                                <th class="col-username">المستخدم</th>
                                <th class="col-name">الاسم</th>
                                <th class="col-role">الدور</th>
                                <th class="col-college">الكلية</th>
                                <th class="col-permissions">الصلاحيات</th>
                                <th class="col-created text-center">التاريخ</th>
                                <th class="col-lastlogin text-center">آخر دخول</th>
                                <th class="col-actions text-center">الإجراءات <i class="fas fa-cog ms-1"></i></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'] ?? '';
                                
                                // Format dates
                                $createdDate = !empty($createdAt) ? date('m/Y', strtotime($createdAt)) : '--';
                                $lastLoginDate = !empty($lastLogin) ? date('d/m/y', strtotime($lastLogin)) : '--';
                                
                                // Truncate text
                                $shortName = mb_strlen($user['name'] ?? '') > 12 ? mb_substr($user['name'] ?? '', 0, 10) . '...' : ($user['name'] ?? '');
                                $shortUsername = mb_strlen($user['username'] ?? '') > 10 ? mb_substr($user['username'] ?? '', 0, 8) . '...' : ($user['username'] ?? '');
                                $shortCollege = mb_strlen($collegeName) > 10 ? mb_substr($collegeName, 0, 8) . '...' : $collegeName;
                            ?>
                                <tr class="<?= $isCurrentUser ? 'table-info' : '' ?>">
                                    <td class="text-center fw-bold"><?= $index + 1 ?></td>
                                    <td class="truncate-text" data-fulltext="<?= e($user['username'] ?? '') ?>" title="<?= e($user['username'] ?? '') ?>">
                                        <?= e($shortUsername) ?>
                                        <?php if ($isCurrentUser): ?>
                                            <span class="badge bg-info ms-1" title="أنت">!</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="truncate-text" data-fulltext="<?= e($user['name'] ?? '') ?>" title="<?= e($user['name'] ?? '') ?>">
                                        <?= e($shortName) ?>
                                    </td>
                                    <td class="compact-role">
                                        <?php if (!empty($roleName)): 
                                            $roleIcon = getRoleIcon($roleName);
                                        ?>
                                            <span class="user-role-badge role-<?= e($roleName) ?>">
                                                <i class="fas fa-<?= $roleIcon ?> me-1"></i>
                                                <?= e(mb_strlen($roleName) > 8 ? mb_substr($roleName, 0, 6) . '...' : $roleName) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">--</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="truncate-text" data-fulltext="<?= e($collegeName) ?>" title="<?= e($collegeName) ?>">
                                        <?= e($shortCollege) ?>
                                    </td>
                                    <td>
                                        <?php if (($user['can_view_all'] ?? 0) == 1): ?>
                                            <span class="badge bg-success" title="مشاهدة جميع الكليات">
                                                <i class="fas fa-eye me-1"></i>الكل
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary" title="كلية محددة">
                                                <i class="fas fa-university me-1"></i>محدد
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center date-compact" title="<?= !empty($createdAt) ? date('Y-m-d', strtotime($createdAt)) : '' ?>">
                                        <?= $createdDate ?>
                                    </td>
                                    <td class="text-center date-compact" title="<?= !empty($lastLogin) ? date('Y-m-d H:i', strtotime($lastLogin)) : '' ?>">
                                        <?php if (!empty($lastLogin)): ?>
                                            <i class="fas fa-sign-in-alt me-1 text-muted"></i><?= $lastLoginDate ?>
                                        <?php else: ?>
                                            <span class="badge bg-warning" title="لم يدخل بعد">
                                                <i class="fas fa-times me-1"></i>--
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <div class="icon-actions">
                                            <!-- Change Role Button -->
                                            <button type="button" class="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="btn" data-bs-toggle="modal" 
                                                    data-bs-target="#resetPasswordModal<?= $user['id'] ?? '' ?>"
                                                    title="تغيير كلمة المرور">
                                                <i class="fas fa-key"></i>
                                            </button>
                                            
                                            <?php if (!$isCurrentUser): ?>
                                                <!-- Delete Button -->
                                                <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="btn"
                                                            title="حذف المستخدم">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <!-- Current user indicator -->
                                                <span class="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 bg-info text-white py-2">
                                                            <h6 class="modal-title mb-0" style="font-size: 0.9rem;">
                                                                <i class="fas fa-user-tag me-2"></i>
                                                                تغيير دور <?= e($user['name'] ?? '') ?>
                                                            </h6>
                                                            <button type="button" class="btn-close btn-close-white" 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="form-label fw-semibold mb-2" style="font-size: 0.85rem;">
                                                                    اختر الدور الجديد
                                                                </label>
                                                                <select class="form-select form-select-sm" name="new_role_id" id="new_role_id_<?= $user['id'] ?? '' ?>" 
                                                                        required onchange="toggleCollegeSelectionUpdate(this.value, '<?= $user['id'] ?? '' ?>')">
                                                                    <?php foreach ($roles as $role): 
                                                                        $roleIcon = getRoleIcon($role['role_name'] ?? '');
                                                                    ?>
                                                                        <option value="<?= $role['role_id'] ?>" 
                                                                            <?= ($user['role_id'] ?? 0) == $role['role_id'] ? 'selected' : '' ?>>
                                                                            <i class="fas fa-<?= $roleIcon ?> me-1"></i>
                                                                            <?= e($role['role_name'] ?? '') ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>
                                                            
                                                            <!-- College Selection for Update (Conditional) -->
                                                            <div id="collegeSelectUpdate<?= $user['id'] ?? '' ?>" class="college-select-container" 
                                                                 style="<?= roleRequiresCollege($roleName) ? '' : 'display: none;' ?>">
                                                                <label class="form-label fw-semibold mb-2" style="font-size: 0.85rem;">
                                                                    <i class="fas fa-university me-1"></i>
                                                                    اختر الكلية التابع لها
                                                                </label>
                                                                <select class="form-select form-select-sm" 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 mt-1" style="font-size: 0.75rem;">
                                                                    مطلوب للمستخدمين ذوي الأدوار المحددة (مسجل الكلية، عميد، إلخ)
                                                                </small>
                                                            </div>
                                                            
                                                            <div class="alert alert-info mt-3" style="font-size: 0.8rem;">
                                                                <i class="fas fa-info-circle me-2"></i>
                                                                سيتم تحديث صلاحيات المستخدم فوراً بعد التغيير
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer py-2">
                                                            <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">
                                                                <i class="fas fa-times me-1"></i> إلغاء
                                                            </button>
                                                            <button type="submit" name="update_role" class="btn btn-sm btn-info">
                                                                <i class="fas fa-save me-1"></i> حفظ التغييرات
                                                            </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 bg-warning text-white py-2">
                                                            <h6 class="modal-title mb-0" style="font-size: 0.9rem;">
                                                                <i class="fas fa-key me-2"></i>
                                                                تغيير كلمة مرور <?= e($user['name'] ?? '') ?>
                                                            </h6>
                                                            <button type="button" class="btn-close btn-close-white" 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="form-label fw-semibold mb-2" style="font-size: 0.85rem;">
                                                                    كلمة المرور الجديدة
                                                                </label>
                                                                <div class="input-group input-group-sm">
                                                                    <input type="password" class="form-control" 
                                                                           name="new_password" id="new_password_<?= $user['id'] ?? '' ?>" 
                                                                           required minlength="6"
                                                                           placeholder="كلمة المرور الجديدة">
                                                                    <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                                            onclick="togglePassword('new_password_<?= $user['id'] ?? '' ?>')">
                                                                        <i class="fas fa-eye"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label class="form-label fw-semibold mb-2" style="font-size: 0.85rem;">
                                                                    تأكيد كلمة المرور
                                                                </label>
                                                                <div class="input-group input-group-sm">
                                                                    <input type="password" class="form-control" 
                                                                           id="confirm_password_<?= $user['id'] ?? '' ?>" 
                                                                           required minlength="6"
                                                                           placeholder="تأكيد كلمة المرور">
                                                                    <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                                            onclick="togglePassword('confirm_password_<?= $user['id'] ?? '' ?>')">
                                                                        <i class="fas fa-eye"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                            <?php if ($isCurrentUser): ?>
                                                                <div class="alert alert-warning" style="font-size: 0.8rem;">
                                                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                                                    أنت تقوم بتغيير كلمة مرور حسابك الخاص
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="modal-footer py-2">
                                                            <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">
                                                                <i class="fas fa-times me-1"></i> إلغاء
                                                            </button>
                                                            <button type="submit" name="reset_password" class="btn btn-sm btn-warning">
                                                                <i class="fas fa-save me-1"></i> حفظ التغييرات
                                                            </button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Statistics Summary -->
                <div class="row mt-3 g-2">
                    <?php
                    // Calculate statistics
                    $adminCount = 0;
                    $committeeCount = 0;
                    $activeCount = 0;
                    $collegeSpecificCount = 0;
                    
                    foreach ($users as $user) {
                        $roleLower = isset($user['role_name']) ? strtolower($user['role_name']) : '';
                        if (in_array($roleLower, ['admin', 'administrator', 'مدير', 'مسؤول'])) {
                            $adminCount++;
                        }
                        if ($roleLower === 'committee' || $roleLower === 'مسجل الكلية') {
                            $committeeCount++;
                        }
                        if (!empty($user['last_login'])) {
                            $activeCount++;
                        }
                        if (($user['can_view_all'] ?? 0) == 0 && !empty($user['college_id'])) {
                            $collegeSpecificCount++;
                        }
                    }
                    ?>
                    <div class="col-md-3">
                        <div class="card stat-card bg-primary text-white">
                            <div class="card-body py-2 px-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title mb-0"><?= count($users) ?></h6>
                                        <p class="card-text mb-0" style="font-size: 0.7rem;"><i class="fas fa-users me-1"></i>المستخدمين</p>
                                    </div>
                                    <i class="fas fa-users opacity-50 fa-lg"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-success text-white">
                            <div class="card-body py-2 px-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title mb-0"><?= $adminCount ?></h6>
                                        <p class="card-text mb-0" style="font-size: 0.7rem;"><i class="fas fa-user-shield me-1"></i>مسؤولين</p>
                                    </div>
                                    <i class="fas fa-user-shield opacity-50 fa-lg"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-info text-white">
                            <div class="card-body py-2 px-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title mb-0"><?= $committeeCount ?></h6>
                                        <p class="card-text mb-0" style="font-size: 0.7rem;"><i class="fas fa-user-tie me-1"></i>مسجلين</p>
                                    </div>
                                    <i class="fas fa-user-tie opacity-50 fa-lg"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-warning text-white">
                            <div class="card-body py-2 px-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title mb-0"><?= $collegeSpecificCount ?></h6>
                                        <p class="card-text mb-0" style="font-size: 0.7rem;"><i class="fas fa-university me-1"></i>بكلية محددة</p>
                                    </div>
                                    <i class="fas fa-university opacity-50 fa-lg"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Security Notice -->
    <div class="alert alert-warning mt-3 py-2" style="font-size: 0.85rem;">
        <div class="d-flex align-items-start">
            <i class="fas fa-shield-alt me-2 mt-1"></i>
            <div>
                <h6 class="alert-heading fw-bold mb-1" style="font-size: 0.9rem;">ملاحظات أمنية</h6>
                <div class="row g-1">
                    <div class="col-md-3">
                        <i class="fas fa-user-tag me-1"></i>
                        <small>تحديث الأدوار بحذر</small>
                    </div>
                    <div class="col-md-3">
                        <i class="fas fa-university me-1"></i>
                        <small>تعيين الكلية للمسجلين</small>
                    </div>
                    <div class="col-md-3">
                        <i class="fas fa-trash-alt me-1"></i>
                        <small>حذف الحسابات غير النشطة</small>
                    </div>
                    <div class="col-md-3">
                        <i class="fas fa-key me-1"></i>
                        <small>تغيير كلمات المرور دورياً</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS Bundle with Popper -->
<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 button = input.nextElementSibling;
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

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

// Check if role requires college
function roleRequiresCollege(roleName) {
    return COLLEGE_REQUIRED_ROLES.some(role => 
        roleName.toLowerCase().includes(role.toLowerCase()) || 
        role.toLowerCase().includes(roleName.toLowerCase())
    );
}

// Toggle college selection for ADD form
function toggleCollegeSelection(roleId, formType) {
    // Get role name from select option text
    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;
    
    // Show/hide college selection based on role
    if (roleRequiresCollege(roleName)) {
        collegeContainer.style.display = 'block';
        
        // Uncheck "view all colleges" if it exists
        const viewAllCheckbox = document.getElementById('can_view_all');
        if (viewAllCheckbox) {
            viewAllCheckbox.checked = false;
            viewAllCheckbox.disabled = true;
        }
    } else {
        collegeContainer.style.display = 'none';
        
        // Enable "view all colleges" checkbox
        const viewAllCheckbox = document.getElementById('can_view_all');
        if (viewAllCheckbox) {
            viewAllCheckbox.disabled = false;
        }
    }
}

// Toggle college selection for UPDATE form
function toggleCollegeSelectionUpdate(roleId, userId) {
    toggleCollegeSelection(roleId, userId);
}

// Validate add user form
function validateAddUserForm() {
    const password = document.getElementById('password');
    const roleSelect = document.getElementById('role_id');
    const selectedRole = roleSelect.options[roleSelect.selectedIndex].text.trim();
    
    // Check password length
    if (password && password.value.length < 6) {
        alert('كلمة المرور يجب أن تحتوي على 6 أحرف على الأقل');
        password.focus();
        return false;
    }
    
    // If role requires college, check if college is selected
    if (roleRequiresCollege(selectedRole)) {
        const collegeSelect = document.getElementById('role_specific_college');
        if (!collegeSelect || !collegeSelect.value) {
            alert('يجب اختيار الكلية للمستخدمين ذوي الأدوار المحددة (مسجل الكلية، عميد، إلخ)');
            collegeSelect.focus();
            return false;
        }
    }
    
    return true;
}

// Validate password reset
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;
}

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

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize college selection for add form
    const initialRoleSelect = document.getElementById('role_id');
    if (initialRoleSelect) {
        toggleCollegeSelection(initialRoleSelect.value, 'add');
    }
    
    // Initialize college selection for existing update modals
    <?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'] ?? '' ?>');
        }
    <?php endforeach; ?>
    
    // Add tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Form validation for update role forms
    <?php foreach ($users as $user): ?>
        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();
                        collegeSelect.focus();
                    }
                }
            });
        }
    <?php endforeach; ?>
});
</script>

</body>
</html>