<?php
/**
 * نظام التسجيل الشامل لطلاب الجامعة
 * University Student Registration System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../classes/Auth.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || (!$auth->hasRole('admin') && !$auth->hasRole('college_admin') && !$auth->hasRole('registrar'))) {
    header('Location: ../index.php');
    exit;
}

$db = Database::getInstance();
$message = '';

// معالجة AJAX requests
if (isset($_GET['action']) && $_GET['action'] == 'get_majors' && isset($_GET['college_id'])) {
    header('Content-Type: application/json');
    $college_id = (int)$_GET['college_id'];
    $majors = $db->fetchAll(
        "SELECT id, name_ar FROM majors WHERE college_id = ? ORDER BY name_ar",
        [$college_id]
    );
    echo json_encode($majors);
    exit;
}

if (isset($_GET['action']) && $_GET['action'] == 'get_semesters' && isset($_GET['major_id'])) {
    header('Content-Type: application/json');
    $major_id = (int)$_GET['major_id'];
    $semesters = $db->fetchAll(
        "SELECT id, semester_number, academic_year FROM semesters WHERE major_id = ? ORDER BY academic_year, semester_number",
        [$major_id]
    );
    echo json_encode($semesters);
    exit;
}

// الفلاتر
$filter_college_id = isset($_GET['filter_college_id']) ? (int)$_GET['filter_college_id'] : 0;
$filter_major_id = isset($_GET['filter_major_id']) ? (int)$_GET['filter_major_id'] : 0;
$filter_semester_id = isset($_GET['filter_semester_id']) ? (int)$_GET['filter_semester_id'] : 0;
$filter_academic_year = isset($_GET['filter_academic_year']) ? $_GET['filter_academic_year'] : '';
$search_term = isset($_GET['search']) ? trim($_GET['search']) : '';

// جلب الكليات
if ($auth->hasRole('admin')) {
    $colleges = $db->fetchAll("SELECT * FROM colleges ORDER BY name_ar");
} else {
    $college_id = $_SESSION['college_id'] ?? 0;
    $colleges = $db->fetchAll("SELECT * FROM colleges WHERE id = ? ORDER BY name_ar", [$college_id]);
}

// جلب التخصصات
$majors_for_filter = [];
if ($filter_college_id > 0) {
    $majors_for_filter = $db->fetchAll(
        "SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar",
        [$filter_college_id]
    );
} elseif ($auth->hasRole('admin')) {
    $majors_for_filter = $db->fetchAll("SELECT * FROM majors ORDER BY name_ar");
} else {
    $college_id = $_SESSION['college_id'] ?? 0;
    $majors_for_filter = $db->fetchAll(
        "SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar",
        [$college_id]
    );
}

// جلب الفصول الدراسية
$semesters_for_filter = [];
if ($filter_major_id > 0) {
    $semesters_for_filter = $db->fetchAll(
        "SELECT * FROM semesters WHERE major_id = ? ORDER BY academic_year, semester_number",
        [$filter_major_id]
    );
}

// جلب السنوات الدراسية المتاحة
$academic_years = $db->fetchAll(
    "SELECT DISTINCT academic_year FROM semesters ORDER BY academic_year DESC"
);

// جلب الطلاب المسجلين مع الفلاتر
$where_conditions = [];
$where_params = [];

// بناء شروط البحث
if ($filter_college_id > 0) {
    $where_conditions[] = "c.id = ?";
    $where_params[] = $filter_college_id;
} elseif (!$auth->hasRole('admin')) {
    $college_id = $_SESSION['college_id'] ?? 0;
    if ($college_id > 0) {
        $where_conditions[] = "c.id = ?";
        $where_params[] = $college_id;
    }
}

if ($filter_major_id > 0) {
    $where_conditions[] = "m.id = ?";
    $where_params[] = $filter_major_id;
}

if ($filter_semester_id > 0) {
    $where_conditions[] = "sc.semester_id = ?";
    $where_params[] = $filter_semester_id;
}

if ($filter_academic_year) {
    $where_conditions[] = "s.academic_year = ?";
    $where_params[] = $filter_academic_year;
}

if ($search_term) {
    $where_conditions[] = "(st.student_number LIKE ? OR st.full_name_ar LIKE ? OR st.full_name_en LIKE ? OR st.national_id LIKE ?)";
    $search_param = '%' . $search_term . '%';
    $where_params[] = $search_param;
    $where_params[] = $search_param;
    $where_params[] = $search_param;
    $where_params[] = $search_param;
}

$where = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// جلب الطلاب المسجلين
$students = $db->fetchAll(
    "SELECT DISTINCT 
        st.id, st.student_number, st.full_name_ar, st.full_name_en, st.national_id, 
        st.email, st.phone, st.status, st.enrollment_date,
        c.name_ar as college_name, c.id as college_id,
        m.name_ar as major_name, m.id as major_id,
        COUNT(DISTINCT sc.id) as registered_courses_count,
        COUNT(DISTINCT sc.semester_id) as registered_semesters_count
     FROM students st
     JOIN colleges c ON st.college_id = c.id
     JOIN majors m ON st.major_id = m.id
     LEFT JOIN student_courses sc ON st.id = sc.student_id
     LEFT JOIN semesters s ON sc.semester_id = s.id
     $where
     GROUP BY st.id
     ORDER BY c.name_ar, m.name_ar, st.student_number",
    $where_params
);

// إحصائيات
$total_students = count($students);
$active_students = 0;
$graduated_students = 0;
foreach ($students as $student) {
    if ($student['status'] == 'active') $active_students++;
    if ($student['status'] == 'graduated') $graduated_students++;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>نظام التسجيل الشامل - طلاب جامعة الشرق للعلوم والتكنولوجيا: Alsharg University of Science and Technology</title>
    <?php include __DIR__ . '/../includes/compatibility.php'; ?>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .stat-card h3 {
            margin: 0 0 10px 0;
            font-size: 14px;
            opacity: 0.9;
        }
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            margin: 0;
        }
        .filter-section {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            border: 2px solid #667eea;
        }
        .search-box {
            margin-bottom: 15px;
        }
        .search-box input {
            width: 100%;
            max-width: 500px;
            padding: 12px;
            border: 2px solid #667eea;
            border-radius: 5px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h2>📋 نظام التسجيل الشامل - طلاب الجامعة</h2>
            <div>
                <a href="../dashboard.php" class="btn btn-secondary">العودة للوحة التحكم</a>
            </div>
        </div>
        
        <?php echo $message; ?>
        
        <!-- الإحصائيات -->
        <div class="stats-container">
            <div class="stat-card">
                <h3>إجمالي الطلاب</h3>
                <p class="number"><?php echo $total_students; ?></p>
            </div>
            <div class="stat-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                <h3>الطلاب النشطون</h3>
                <p class="number"><?php echo $active_students; ?></p>
            </div>
            <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <h3>الطلاب المتخرجون</h3>
                <p class="number"><?php echo $graduated_students; ?></p>
            </div>
        </div>
        
        <!-- قسم الفلاتر والبحث -->
        <div class="filter-section">
            <h3 style="margin-top: 0; color: #667eea;">🔍 البحث والتصفية</h3>
            <form method="GET" style="margin-bottom: 15px;">
                <div class="search-box">
                    <input type="text" 
                           name="search" 
                           placeholder="ابحث بالرقم الجامعي، الاسم، أو الرقم الوطني..."
                           value="<?php echo htmlspecialchars($search_term); ?>"
                           style="width: 100%; max-width: 500px; padding: 12px; border: 2px solid #667eea; border-radius: 5px; font-size: 16px;">
                </div>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                    <div class="form-group">
                        <label>الكلية:</label>
                        <select name="filter_college_id" id="filter_college_id" onchange="loadMajorsForFilter()" style="width: 100%; padding: 8px;">
                            <option value="">-- جميع الكليات --</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?php echo $college['id']; ?>" <?php echo $filter_college_id == $college['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($college['name_ar']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>التخصص:</label>
                        <select name="filter_major_id" id="filter_major_id" onchange="loadSemestersForFilter()" style="width: 100%; padding: 8px;">
                            <option value="">-- جميع التخصصات --</option>
                            <?php foreach ($majors_for_filter as $major): ?>
                                <option value="<?php echo $major['id']; ?>" <?php echo $filter_major_id == $major['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($major['name_ar']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>الفصل الدراسي:</label>
                        <select name="filter_semester_id" id="filter_semester_id" style="width: 100%; padding: 8px;">
                            <option value="">-- جميع الفصول --</option>
                            <?php foreach ($semesters_for_filter as $sem): ?>
                                <option value="<?php echo $sem['id']; ?>" <?php echo $filter_semester_id == $sem['id'] ? 'selected' : ''; ?>>
                                    فصل <?php echo $sem['semester_number']; ?> - <?php echo htmlspecialchars($sem['academic_year']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>السنة الدراسية:</label>
                        <select name="filter_academic_year" style="width: 100%; padding: 8px;">
                            <option value="">-- جميع السنوات --</option>
                            <?php foreach ($academic_years as $year): ?>
                                <option value="<?php echo htmlspecialchars($year['academic_year']); ?>" <?php echo $filter_academic_year == $year['academic_year'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($year['academic_year']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div style="margin-top: 15px; text-align: center;">
                    <button type="submit" class="btn btn-primary">🔍 عرض الطلاب</button>
                    <a href="index.php" class="btn btn-secondary">إعادة تعيين</a>
                </div>
            </form>
        </div>
        
        <!-- جدول الطلاب -->
        <div class="table-container">
            <?php if (empty($students)): ?>
                <div class="alert alert-info" style="text-align: center; padding: 30px;">
                    <h3>لا توجد نتائج</h3>
                    <p>لم يتم العثور على أي طلاب تطابق معايير البحث المحددة.</p>
                </div>
            <?php else: ?>
                <div style="margin-bottom: 15px; padding: 10px; background: #e3f2fd; border-radius: 5px;">
                    <strong>عدد الطلاب المعروضين: <?php echo count($students); ?></strong>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>الرقم الجامعي</th>
                            <th>الاسم</th>
                            <th>الكلية</th>
                            <th>التخصص</th>
                            <th>الرقم الوطني</th>
                            <th>البريد الإلكتروني</th>
                            <th>الهاتف</th>
                            <th>تاريخ التسجيل</th>
                            <th>عدد المواد المسجلة</th>
                            <th>الحالة</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($students as $student): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($student['student_number']); ?></td>
                                <td><?php echo htmlspecialchars($student['full_name_ar']); ?></td>
                                <td><?php echo htmlspecialchars($student['college_name']); ?></td>
                                <td><?php echo htmlspecialchars($student['major_name']); ?></td>
                                <td><?php echo htmlspecialchars($student['national_id'] ?: '-'); ?></td>
                                <td><?php echo htmlspecialchars($student['email'] ?: '-'); ?></td>
                                <td><?php echo htmlspecialchars($student['phone'] ?: '-'); ?></td>
                                <td><?php echo htmlspecialchars($student['enrollment_date']); ?></td>
                                <td><?php echo $student['registered_courses_count']; ?></td>
                                <td>
                                    <?php
                                    $status_labels = [
                                        'active' => 'نشط',
                                        'graduated' => 'متخرج',
                                        'suspended' => 'معلق',
                                        'withdrawn' => 'منسحب'
                                    ];
                                    $status_colors = [
                                        'active' => '#4CAF50',
                                        'graduated' => '#2196F3',
                                        'suspended' => '#FF9800',
                                        'withdrawn' => '#F44336'
                                    ];
                                    $status = $student['status'] ?? 'active';
                                    ?>
                                    <span style="padding: 5px 10px; border-radius: 5px; background: <?php echo $status_colors[$status]; ?>; color: white; font-size: 12px;">
                                        <?php echo $status_labels[$status] ?? $status; ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="../student_details.php?id=<?php echo $student['id']; ?>" class="btn btn-primary" style="margin: 2px;">التفاصيل</a>
                                    <a href="../student_grades.php?student_id=<?php echo $student['id']; ?>" class="btn btn-success" style="margin: 2px;">الدرجات</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    
    <?php include __DIR__ . '/../includes/footer.php'; ?>
    
    <script>
    // دالة تحميل التخصصات عند تغيير الكلية
    function loadMajorsForFilter() {
        const collegeId = document.getElementById('filter_college_id').value;
        const majorSelect = document.getElementById('filter_major_id');
        const semesterSelect = document.getElementById('filter_semester_id');
        
        majorSelect.innerHTML = '<option value="">-- جميع التخصصات --</option>';
        semesterSelect.innerHTML = '<option value="">-- جميع الفصول --</option>';
        majorSelect.disabled = !collegeId;
        semesterSelect.disabled = true;
        
        if (!collegeId) return;
        
        fetch(`index.php?action=get_majors&college_id=${collegeId}`)
            .then(response => response.json())
            .then(data => {
                data.forEach(major => {
                    const option = document.createElement('option');
                    option.value = major.id;
                    option.textContent = major.name_ar;
                    majorSelect.appendChild(option);
                });
                majorSelect.disabled = false;
            })
            .catch(error => {
                console.error('Error loading majors:', error);
            });
    }
    
    // دالة تحميل الفصول عند تغيير التخصص
    function loadSemestersForFilter() {
        const majorId = document.getElementById('filter_major_id').value;
        const semesterSelect = document.getElementById('filter_semester_id');
        
        semesterSelect.innerHTML = '<option value="">-- جميع الفصول --</option>';
        semesterSelect.disabled = !majorId;
        
        if (!majorId) return;
        
        fetch(`index.php?action=get_semesters&major_id=${majorId}`)
            .then(response => response.json())
            .then(data => {
                data.forEach(semester => {
                    const option = document.createElement('option');
                    option.value = semester.id;
                    option.textContent = 'فصل ' + semester.semester_number + ' - ' + semester.academic_year;
                    semesterSelect.appendChild(option);
                });
                semesterSelect.disabled = false;
            })
            .catch(error => {
                console.error('Error loading semesters:', error);
            });
    }
    </script>
</body>
</html>


