<?php
// user_control.php - WITH COMPLETE INSTRUCTOR SUBJECT ASSIGNMENT
session_start();
error_reporting(1);
ini_set('display_errors', 1);

// Check login
if (!isset($_SESSION['committee_id'])) {
    header('Location: admin_login.php');
    exit();
}

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

// Get user role
$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 {
    $stmt = $mysqli1->prepare("SELECT role_name FROM committee_users WHERE id = ?");
    $stmt->bind_param("i", $_SESSION['committee_id']);
    $stmt->execute();
    $stmt->bind_result($dbRole);
    if ($stmt->fetch()) {
        $userRole = $dbRole ?: '';
        $_SESSION['committee_role_name'] = $userRole;
        $_SESSION['user_role'] = $userRole;
    }
    $stmt->close();
}

// Check admin
$adminRoles = ['admin', 'administrator', 'مدير', 'مسؤول'];
$isAdmin = in_array(strtolower($userRole), array_map('strtolower', $adminRoles));

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

// Helper functions
function getRoleIcon($roleName) {
    $icons = ['admin' => 'user-shield', 'instructor' => 'chalkboard-teacher', 'committee' => 'user-tie', 'accountant' => 'calculator'];
    $roleLower = strtolower($roleName);
    return $icons[$roleLower] ?? 'user';
}

function roleRequiresCollege($roleName) {
    $roles = ['committee', 'dean', 'registrar', 'instructor', 'مدرس', 'مسجل الكلية', 'عميد'];
    return in_array(strtolower($roleName), $roles);
}

function isInstructorRole($roleName) {
    return in_array(strtolower($roleName), ['instructor', 'مدرس']);
}

// Handle AJAX requests
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    
    // Get subjects by college
    if ($_GET['ajax'] == 'get_subjects_by_college' && isset($_GET['college_id'])) {
        $college_id = (int)$_GET['college_id'];
        $subjects = [];
        $query = "SELECT subjectcode, subjectnamea, subjectnamee, credit_hours FROM subjects WHERE college_id = ? AND deleted_at IS NULL ORDER BY subjectcode";
        $stmt = $mysqli1->prepare($query);
        $stmt->bind_param("i", $college_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $subjects[] = $row;
        }
        $stmt->close();
        echo json_encode(['success' => true, 'subjects' => $subjects]);
        exit;
    }
    
    // Get assigned subjects for instructor
    if ($_GET['ajax'] == 'get_assigned_subjects' && isset($_GET['user_id'])) {
        $user_id = (int)$_GET['user_id'];
        $assigned = [];
        $query = "SELECT isub.*, s.subjectnamea, s.subjectnamee, s.credit_hours, c.name as college_name
                  FROM instructor_subjects isub
                  JOIN subjects s ON isub.subjectcode = s.subjectcode
                  JOIN colleges c ON s.college_id = c.id
                  WHERE isub.instructor_id = ?
                  ORDER BY c.name, s.subjectcode";
        $stmt = $mysqli1->prepare($query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $assigned[] = $row;
        }
        $stmt->close();
        echo json_encode(['success' => true, 'assigned' => $assigned]);
        exit;
    }
    
    // Assign single subject
    if ($_GET['ajax'] == 'assign_subject') {
        $user_id = (int)$_POST['user_id'];
        $subjectcode = $_POST['subjectcode'];
        
        $check = $mysqli1->prepare("SELECT id FROM instructor_subjects WHERE instructor_id = ? AND subjectcode = ?");
        $check->bind_param("is", $user_id, $subjectcode);
        $check->execute();
        if ($check->get_result()->num_rows == 0) {
            $insert = $mysqli1->prepare("INSERT INTO instructor_subjects (instructor_id, subjectcode, created_at) VALUES (?, ?, NOW())");
            $insert->bind_param("is", $user_id, $subjectcode);
            $insert->execute();
            $insert->close();
            echo json_encode(['success' => true, 'message' => 'تم تعيين المادة بنجاح']);
        } else {
            echo json_encode(['success' => false, 'message' => 'المادة مسندة بالفعل']);
        }
        $check->close();
        exit;
    }
    
    // Remove subject
    if ($_GET['ajax'] == 'remove_subject') {
        $user_id = (int)$_POST['user_id'];
        $subjectcode = $_POST['subjectcode'];
        $delete = $mysqli1->prepare("DELETE FROM instructor_subjects WHERE instructor_id = ? AND subjectcode = ?");
        $delete->bind_param("is", $user_id, $subjectcode);
        $delete->execute();
        $delete->close();
        echo json_encode(['success' => true, 'message' => 'تم إلغاء تعيين المادة']);
        exit;
    }
}

// Handle POST submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_user'])) {
        $username = trim($_POST['username']);
        $name = trim($_POST['name']);
        $password = $_POST['password'];
        $role_id = (int)$_POST['role_id'];
        $role_specific_college = !empty($_POST['role_specific_college']) ? (int)$_POST['role_specific_college'] : null;
        
        $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();
        
        $college_id = null;
        $can_view_all = 1;
        if (roleRequiresCollege($role_name) && $role_specific_college) {
            $college_id = $role_specific_college;
            $can_view_all = 0;
        }
        
        if ($username && $password && $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->close();
        }
    } elseif (isset($_POST['delete_user'])) {
        $user_id = (int)$_POST['user_id'];
        if ($user_id && $user_id != $_SESSION['committee_id']) {
            $del_subjects = $mysqli1->prepare("DELETE FROM instructor_subjects WHERE instructor_id = ?");
            $del_subjects->bind_param("i", $user_id);
            $del_subjects->execute();
            $del_subjects->close();
            
            $stmt = $mysqli1->prepare("DELETE FROM committee_users WHERE id = ?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $stmt->close();
            $_SESSION['success'] = 'تم حذف المستخدم بنجاح';
        }
    } elseif (isset($_POST['reset_password'])) {
        $user_id = (int)$_POST['user_id'];
        $new_password = $_POST['new_password'];
        if ($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);
            $stmt->execute();
            $stmt->close();
            $_SESSION['success'] = 'تم تحديث كلمة المرور بنجاح';
        }
    } elseif (isset($_POST['update_role'])) {
        $user_id = (int)$_POST['user_id'];
        $new_role_id = (int)$_POST['new_role_id'];
        $role_specific_college = !empty($_POST['role_specific_college']) ? (int)$_POST['role_specific_college'] : null;
        
        $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();
        
        $college_id = null;
        $can_view_all = 1;
        if (roleRequiresCollege($role_name) && $role_specific_college) {
            $college_id = $role_specific_college;
            $can_view_all = 0;
        }
        
        $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);
        $stmt->execute();
        $stmt->close();
        $_SESSION['success'] = 'تم تحديث دور المستخدم بنجاح';
    }
    
    header('Location: user_control.php');
    exit();
}

// Fetch data
$users = [];
$result = $mysqli1->query("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 ($result) {
    $users = $result->fetch_all(MYSQLI_ASSOC);
}

$colleges = [];
$result = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    $colleges = $result->fetch_all(MYSQLI_ASSOC);
}

$roles = [];
$result = $mysqli1->query("SELECT role_id, role_name FROM users_roles ORDER BY role_id");
if ($result) {
    $roles = $result->fetch_all(MYSQLI_ASSOC);
}

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>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Cairo', 'Tahoma', sans-serif;
            background: #f5f7fb;
            direction: rtl;
        }
        .page-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        .card {
            background: white;
            border-radius: 12px;
            margin-bottom: 25px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            border: 1px solid #e0e0e0;
        }
        .card-header {
            background: linear-gradient(135deg, #0056B3, #003366);
            color: white;
            padding: 15px 20px;
            border-radius: 12px 12px 0 0;
            font-weight: bold;
        }
        .card-header i {
            margin-left: 10px;
            color: #FFC107;
        }
        .card-body {
            padding: 20px;
        }
        .btn-primary {
            background: #0056B3;
            border: none;
        }
        .btn-primary:hover {
            background: #003366;
        }
        .btn-success {
            background: #28a745;
        }
        .btn-warning {
            background: #ffc107;
            color: #333;
        }
        .btn-outline {
            background: transparent;
            border: 1px solid #0056B3;
            color: #0056B3;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background: #f8f9fa;
            padding: 12px;
            text-align: center;
            border-bottom: 2px solid #FFC107;
        }
        td {
            padding: 10px;
            text-align: center;
            border-bottom: 1px solid #e0e0e0;
        }
        .role-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: bold;
        }
        .role-admin { background: #0056B3; color: white; }
        .role-instructor { background: #7B1FA2; color: white; }
        .role-committee { background: #2E7D32; color: white; }
        .role-default { background: #6c757d; color: white; }
        .action-btn {
            width: 30px;
            height: 30px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            margin: 0 2px;
        }
        .action-btn:hover {
            border-color: #0056B3;
            color: #0056B3;
        }
        .alert {
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-success { background: #d4edda; border: 1px solid #28a745; color: #155724; }
        .alert-danger { background: #f8d7da; border: 1px solid #dc3545; color: #721c24; }
        .form-control, .form-select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
        }
        .subjects-section {
            margin-top: 30px;
            padding: 20px;
            background: white;
            border-radius: 12px;
            border: 1px solid #e0e0e0;
        }
        .subjects-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 15px;
            max-height: 500px;
            overflow-y: auto;
            padding: 10px;
        }
        .subject-card {
            background: white;
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 15px;
            transition: all 0.2s;
        }
        .subject-card.assigned {
            background: #e8f5e9;
            border-color: #4caf50;
        }
        .subject-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .subject-code {
            font-weight: bold;
            color: #0056B3;
            margin-bottom: 5px;
        }
        .subject-name {
            font-size: 0.85rem;
            color: #666;
            margin-bottom: 10px;
        }
        .assigned-badge {
            background: #4caf50;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.7rem;
            display: inline-block;
            margin-bottom: 8px;
        }
        .selected-instructor {
            background: linear-gradient(135deg, #fff3e0, #ffe0b2);
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        .filter-bar {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .footer {
            text-align: center;
            padding: 20px;
            margin-top: 30px;
            border-top: 1px solid #ddd;
            font-size: 0.75rem;
            color: #666;
        }
        @media (max-width: 768px) {
            .subjects-grid { grid-template-columns: 1fr; }
            .page-container { padding: 10px; }
        }
    </style>
</head>
<body>

<div class="page-container">
    
    <!-- Header -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-users-cog"></i> إدارة المستخدمين والمدرسين
            <span style="float: left;">
                <a href="admin_dashboard.php" style="color: white; text-decoration: none;">
                    <i class="fas fa-arrow-right"></i> العودة للوحة التحكم
                </a>
            </span>
        </div>
    </div>

    <!-- Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success"><?= htmlspecialchars($_SESSION['success']) ?></div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($_SESSION['error']) ?></div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <!-- Add User Card -->
    <div class="card">
        <div class="card-header"><i class="fas fa-user-plus"></i> إضافة مستخدم جديد</div>
        <div class="card-body">
            <form method="post">
                <div class="row">
                    <div class="col-md-3">
                        <div class="mb-2"><label>اسم المستخدم</label></div>
                        <input type="text" class="form-control" name="username" required>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-2"><label>الاسم الكامل</label></div>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-2"><label>كلمة المرور</label></div>
                        <input type="password" class="form-control" name="password" required minlength="6">
                    </div>
                    <div class="col-md-3">
                        <div class="mb-2"><label>الدور</label></div>
                        <select class="form-control" name="role_id" id="role_id" onchange="toggleCollegeField(this)">
                            <?php foreach ($roles as $role): ?>
                                <option value="<?= $role['role_id'] ?>"><?= htmlspecialchars($role['role_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div id="collegeFieldAdd" style="display: none; margin-top: 15px;">
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 8px;">
                        <label>الكلية التابع لها</label>
                        <select class="form-control" name="role_specific_college">
                            <option value="">-- اختر الكلية --</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?= $college['id'] ?>"><?= htmlspecialchars($college['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small>مطلوب للمستخدمين ذوي الأدوار (مسجل الكلية، عميد، مدرس)</small>
                    </div>
                </div>
                <div class="mt-3">
                    <button type="submit" name="add_user" class="btn btn-primary">إضافة مستخدم</button>
                    <button type="reset" class="btn btn-outline">مسح</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Users List Card -->
    <div class="card">
        <div class="card-header"><i class="fas fa-list"></i> قائمة المستخدمين والمدرسين</div>
        <div class="card-body" style="overflow-x: auto;">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>اسم المستخدم</th>
                        <th>الاسم الكامل</th>
                        <th>الدور</th>
                        <th>الكلية</th>
                        <th>الصلاحية</th>
                        <th>تاريخ التسجيل</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $index => $user): 
                        $isInstructor = isInstructorRole($user['role_name'] ?? '');
                        $roleLower = strtolower($user['role_name'] ?? '');
                        $badgeClass = 'role-default';
                        if (in_array($roleLower, ['admin', 'administrator'])) $badgeClass = 'role-admin';
                        elseif ($roleLower == 'committee') $badgeClass = 'role-committee';
                        elseif (in_array($roleLower, ['instructor', 'مدرس'])) $badgeClass = 'role-instructor';
                    ?>
                        <tr>
                            <td><?= $index + 1 ?></td>
                            <td><?= htmlspecialchars($user['username'] ?? '') ?></td>
                            <td><?= htmlspecialchars($user['name'] ?? '') ?></td>
                            <td><span class="role-badge <?= $badgeClass ?>"><i class="fas fa-<?= getRoleIcon($user['role_name'] ?? '') ?>"></i> <?= htmlspecialchars($user['role_name'] ?? '-') ?></span></td>
                            <td><?= htmlspecialchars($user['college_name'] ?? 'الكل') ?></td>
                            <td><?= ($user['can_view_all'] ?? 0) == 1 ? '<span style="background:#28a745;color:white;padding:2px 8px;border-radius:15px;">الكل</span>' : '<span style="background:#6c757d;color:white;padding:2px 8px;border-radius:15px;">محدد</span>' ?></td>
                            <td><?= date('Y-m-d', strtotime($user['created_at'] ?? 'now')) ?></td>
                            <td>
                                <?php if ($isInstructor && $user['id'] != $_SESSION['committee_id']): ?>
                                    <button class="action-btn assign-btn" data-id="<?= $user['id'] ?>" data-name="<?= htmlspecialchars($user['name']) ?>" data-college="<?= $user['college_id'] ?>" data-role="<?= $user['role_name'] ?>" title="تعيين مواد" style="color:#7B1FA2;"><i class="fas fa-book"></i></button>
                                <?php endif; ?>
                                <button class="action-btn" onclick="openRoleModal(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name']) ?>', <?= $user['role_id'] ?? 2 ?>, <?= $user['college_id'] ?? 'null' ?>)" title="تغيير الدور"><i class="fas fa-user-tag"></i></button>
                                <button class="action-btn" onclick="openPassModal(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name']) ?>')" title="تغيير كلمة المرور"><i class="fas fa-key"></i></button>
                                <?php if ($user['id'] != $_SESSION['committee_id']): ?>
                                    <form method="post" style="display: inline;" onsubmit="return confirm('حذف المستخدم؟')">
                                        <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                        <button type="submit" name="delete_user" class="action-btn" style="color:#dc3545;"><i class="fas fa-trash"></i></button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <!-- Stats -->
            <?php
            $adminCount = $committeeCount = $instructorCount = 0;
            foreach ($users as $user) {
                $role = strtolower($user['role_name'] ?? '');
                if (in_array($role, ['admin', 'administrator'])) $adminCount++;
                elseif ($role == 'committee') $committeeCount++;
                elseif (in_array($role, ['instructor', 'مدرس'])) $instructorCount++;
            }
            ?>
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-top: 20px;">
                <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; text-align: center;"><h3><?= count($users) ?></h3><p>إجمالي المستخدمين</p></div>
                <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; text-align: center;"><h3><?= $adminCount ?></h3><p>مسؤولين</p></div>
                <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; text-align: center;"><h3><?= $committeeCount ?></h3><p>مسجلين</p></div>
                <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; text-align: center;"><h3><?= $instructorCount ?></h3><p>مدرسين</p></div>
            </div>
        </div>
    </div>

    <!-- Subjects Assignment Section (Hidden by default, appears when instructor selected) -->
    <div id="subjectsSection" style="display: none;">
        <div class="subjects-section">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h4><i class="fas fa-chalkboard-teacher"></i> تعيين المواد للمدرس</h4>
                <button class="btn btn-outline" onclick="$('#subjectsSection').hide()"><i class="fas fa-times"></i> إغلاق</button>
            </div>
            
            <div id="selectedInstructorInfo"></div>
            
            <div class="filter-bar">
                <div class="row">
                    <div class="col-md-6">
                        <input type="text" class="form-control" id="searchSubject" placeholder="بحث في المواد...">
                    </div>
                    <div class="col-md-3">
                        <label><input type="checkbox" id="showAssignedOnly"> عرض المواد المسندة فقط</label>
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-success btn-sm" id="assignSelectedBtn"><i class="fas fa-check-double"></i> تعيين المحددة</button>
                    </div>
                </div>
            </div>
            
            <div id="subjectsGrid" class="subjects-grid">
                <div class="text-center">اختر مدرساً لعرض المواد</div>
            </div>
        </div>
    </div>
</div>

<!-- Change Role Modal -->
<div id="roleModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header" style="background: #0056B3; color: white;">
                    <h5 class="modal-title" id="roleModalTitle"></h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="roleUserId">
                    <div class="mb-3">
                        <label>اختر الدور الجديد</label>
                        <select class="form-control" name="new_role_id" id="newRoleSelect" onchange="toggleRoleCollegeField(this)">
                            <?php foreach ($roles as $role): ?>
                                <option value="<?= $role['role_id'] ?>"><?= htmlspecialchars($role['role_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div id="roleCollegeField" style="display: none;">
                        <div style="background: #f8f9fa; padding: 10px; border-radius: 8px;">
                            <label>الكلية</label>
                            <select class="form-control" name="role_specific_college">
                                <option value="">-- اختر الكلية --</option>
                                <?php foreach ($colleges as $college): ?>
                                    <option value="<?= $college['id'] ?>"><?= htmlspecialchars($college['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="update_role" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reset Password Modal -->
<div id="passModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header" style="background: #0056B3; color: white;">
                    <h5 class="modal-title" id="passModalTitle"></h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="passUserId">
                    <div class="mb-3">
                        <label>كلمة المرور الجديدة</label>
                        <input type="password" class="form-control" name="new_password" required minlength="6">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="reset_password" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="footer">
    <p>الجامعة الوطنية - السودان | National University - Sudan</p>
    <p>نظام إدارة المستخدمين والمدرسين - يمكن للمدرسين تسجيل الدخول وإدارة درجات المواد المسندة</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let currentInstructor = null;
let allSubjects = [];
let assignedSubjects = [];

function toggleCollegeField(select) {
    const roleName = select.options[select.selectedIndex]?.text || '';
    const needsCollege = ['committee', 'dean', 'registrar', 'instructor', 'مدرس', 'مسجل الكلية', 'عميد'].some(r => 
        roleName.toLowerCase().includes(r.toLowerCase())
    );
    document.getElementById('collegeFieldAdd').style.display = needsCollege ? 'block' : 'none';
}

function toggleRoleCollegeField(select) {
    const roleName = select.options[select.selectedIndex]?.text || '';
    const needsCollege = ['committee', 'dean', 'registrar', 'instructor', 'مدرس', 'مسجل الكلية', 'عميد'].some(r => 
        roleName.toLowerCase().includes(r.toLowerCase())
    );
    document.getElementById('roleCollegeField').style.display = needsCollege ? 'block' : 'none';
}

function openRoleModal(userId, userName, currentRoleId, collegeId) {
    document.getElementById('roleUserId').value = userId;
    document.getElementById('roleModalTitle').innerHTML = 'تغيير دور ' + userName;
    const select = document.getElementById('newRoleSelect');
    for(let i = 0; i < select.options.length; i++) {
        if(select.options[i].value == currentRoleId) {
            select.selectedIndex = i;
            break;
        }
    }
    toggleRoleCollegeField(select);
    if(collegeId) {
        const collegeSelect = document.querySelector('#roleCollegeField select');
        for(let i = 0; i < collegeSelect.options.length; i++) {
            if(collegeSelect.options[i].value == collegeId) {
                collegeSelect.selectedIndex = i;
                break;
            }
        }
    }
    new bootstrap.Modal(document.getElementById('roleModal')).show();
}

function openPassModal(userId, userName) {
    document.getElementById('passUserId').value = userId;
    document.getElementById('passModalTitle').innerHTML = 'تغيير كلمة مرور ' + userName;
    new bootstrap.Modal(document.getElementById('passModal')).show();
}

// Subject assignment functions
$(document).ready(function() {
    $('.assign-btn').on('click', function() {
        const userId = $(this).data('id');
        const userName = $(this).data('name');
        const collegeId = $(this).data('college');
        const roleName = $(this).data('role');
        
        currentInstructor = { id: userId, name: userName, collegeId: collegeId, role: roleName };
        
        // Show section
        $('#subjectsSection').show();
        
        // Update instructor info
        $('#selectedInstructorInfo').html(`
            <div class="selected-instructor">
                <div>
                    <strong><i class="fas fa-chalkboard-teacher"></i> ${escapeHtml(userName)}</strong><br>
                    <small><i class="fas fa-university"></i> الكلية: ${getCollegeName(collegeId)} | <i class="fas fa-tag"></i> الدور: ${escapeHtml(roleName)}</small>
                </div>
                <button class="btn btn-success btn-sm" onclick="loadAllSubjectsForCollege(${collegeId})"><i class="fas fa-plus-circle"></i> تعيين جميع مواد الكلية</button>
            </div>
        `);
        
        // Load subjects
        loadAllSubjectsForCollege(collegeId);
        loadInstructorSubjects(userId);
    });
    
    $('#searchSubject').on('keyup', filterSubjects);
    $('#showAssignedOnly').on('change', filterSubjects);
    
    $('#assignSelectedBtn').on('click', function() {
        const selected = $('.subject-checkbox:checked');
        if (selected.length === 0) {
            alert('الرجاء اختيار مادة واحدة على الأقل');
            return;
        }
        const subjectsToAssign = [];
        selected.each(function() { subjectsToAssign.push($(this).val()); });
        
        let assigned = 0;
        let completed = 0;
        
        subjectsToAssign.forEach(function(subjectcode) {
            $.ajax({
                url: window.location.pathname,
                type: 'POST',
                async: false,
                data: { ajax: 'assign_subject', user_id: currentInstructor.id, subjectcode: subjectcode },
                dataType: 'json',
                success: function(res) {
                    if(res.success) assigned++;
                    completed++;
                    if(completed === subjectsToAssign.length) {
                        loadInstructorSubjects(currentInstructor.id);
                        alert(`تم تعيين ${assigned} مادة بنجاح`);
                    }
                }
            });
        });
    });
});

function getCollegeName(collegeId) {
    const colleges = <?= json_encode(array_column($colleges, 'name', 'id')) ?>;
    return colleges[collegeId] || 'غير محدد';
}

function loadAllSubjectsForCollege(collegeId) {
    if (!collegeId) return;
    $.ajax({
        url: window.location.pathname,
        type: 'GET',
        data: { ajax: 'get_subjects_by_college', college_id: collegeId },
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                allSubjects = res.subjects;
                filterSubjects();
            }
        }
    });
}

function loadInstructorSubjects(instructorId) {
    $.ajax({
        url: window.location.pathname,
        type: 'GET',
        data: { ajax: 'get_assigned_subjects', user_id: instructorId },
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                assignedSubjects = res.assigned;
                filterSubjects();
            }
        }
    });
}

function filterSubjects() {
    const searchTerm = $('#searchSubject').val().toLowerCase();
    const showAssignedOnly = $('#showAssignedOnly').is(':checked');
    
    let filtered = [...allSubjects];
    
    if (searchTerm) {
        filtered = filtered.filter(s => 
            s.subjectcode.toLowerCase().includes(searchTerm) || 
            s.subjectnamea.toLowerCase().includes(searchTerm)
        );
    }
    
    if (showAssignedOnly) {
        const assignedCodes = assignedSubjects.map(a => a.subjectcode);
        filtered = filtered.filter(s => assignedCodes.includes(s.subjectcode));
    }
    
    renderSubjectsGrid(filtered);
}

function renderSubjectsGrid(subjects) {
    const assignedCodes = assignedSubjects.map(a => a.subjectcode);
    const grid = $('#subjectsGrid');
    
    if (subjects.length === 0) {
        grid.html('<div class="text-center">لا توجد مواد لعرضها</div>');
        return;
    }
    
    let html = '';
    subjects.forEach(subject => {
        const isAssigned = assignedCodes.includes(subject.subjectcode);
        const assignedClass = isAssigned ? 'assigned' : '';
        
        html += `
            <div class="subject-card ${assignedClass}">
                ${isAssigned ? '<div class="assigned-badge"><i class="fas fa-check"></i> مسندة</div>' : ''}
                <div class="subject-code">${escapeHtml(subject.subjectcode)}</div>
                <div class="subject-name">${escapeHtml(subject.subjectnamea)}</div>
                <div class="subject-name" style="font-size:0.7rem;">${subject.credit_hours} ساعات</div>
                <div style="margin-top: 10px;">
                    <label>
                        <input type="checkbox" class="subject-checkbox" value="${subject.subjectcode}" ${isAssigned ? 'checked' : ''} 
                            onchange="toggleSubjectAssignment('${subject.subjectcode}', this.checked)">
                        ${isAssigned ? 'مسندة' : 'تعيين'}
                    </label>
                </div>
            </div>
        `;
    });
    
    grid.html(html);
}

function toggleSubjectAssignment(subjectcode, isChecked) {
    if (isChecked) {
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: { ajax: 'assign_subject', user_id: currentInstructor.id, subjectcode: subjectcode },
            dataType: 'json',
            success: function(res) {
                if (res.success) loadInstructorSubjects(currentInstructor.id);
                else alert(res.message);
            }
        });
    } else {
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: { ajax: 'remove_subject', user_id: currentInstructor.id, subjectcode: subjectcode },
            dataType: 'json',
            success: function(res) {
                if (res.success) loadInstructorSubjects(currentInstructor.id);
            }
        });
    }
}

function escapeHtml(text) {
    if (!text) return '';
    return String(text).replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}
</script>

</body>
</html>

<?php include 'footer.php'; ?>