<?php
/**
 * تقرير قائمة الطلاب الملاحق والبديل لكل مادة
 * Supplementary and Alternative Students Report by Courses
 */

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();

function getSemesterName($number) {
    switch ((int)$number) {
        case 1: return 'الفصل الأول';
        case 2: return 'الفصل الثاني';
        case 3: return 'الفصل الثالث';
        case 4: return 'الفصل الرابع';
        case 5: return 'الفصل الخامس';
        case 6: return 'الفصل السادس';
        case 7: return 'الفصل السابع';
        case 8: return 'الفصل الثامن';
        default: return 'فصل ' . (int)$number;
    }
}

// معالجة AJAX requests
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    if ($_GET['action'] == 'get_majors' && isset($_GET['college_id'])) {
        $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 ($_GET['action'] == 'get_semesters' && isset($_GET['major_id'])) {
        $major_id = (int)$_GET['major_id'];
        $semesters = $db->fetchAll(
            "SELECT id, semester_number, academic_year FROM semesters WHERE major_id = ? ORDER BY academic_year DESC, semester_number",
            [$major_id]
        );
        echo json_encode($semesters);
        exit;
    }
    
    if ($_GET['action'] == 'get_courses' && isset($_GET['semester_id'])) {
        $semester_id = (int)$_GET['semester_id'];
        // جلب المواد المرتبطة بالفصل الدراسي من خلال student_courses
        $courses = $db->fetchAll(
            "SELECT DISTINCT c.id, c.code, c.name_ar 
             FROM courses c
             JOIN student_courses sc ON c.id = sc.course_id
             WHERE sc.semester_id = ?
             ORDER BY c.code",
            [$semester_id]
        );
        echo json_encode($courses);
        exit;
    }
}

// جلب المعاملات
$course_id = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
$semester_id = isset($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;

// جلب معلومات المادة والفصل
$course = null;
$semester = null;
$college = null;
$major = null;
$students_list = [];

if ($course_id > 0 && $semester_id > 0) {
    // جلب معلومات المادة
    $course = $db->fetchOne(
        "SELECT c.*, m.college_id, m.id as major_id, m.name_ar as major_name,
                col.name_ar as college_name
         FROM courses c 
         JOIN majors m ON c.major_id = m.id 
         JOIN colleges col ON m.college_id = col.id
         WHERE c.id = ?",
        [$course_id]
    );
    
    if ($course) {
        // التحقق من الصلاحيات
        if (!$auth->belongsToCollege($course['college_id']) && !$auth->hasRole('admin')) {
            header('Location: courses.php');
            exit;
        }
        
        // جلب معلومات الفصل
        $semester = $db->fetchOne("SELECT * FROM semesters WHERE id = ?", [$semester_id]);
        
        if ($semester) {
            $college = ['id' => $course['college_id'], 'name_ar' => $course['college_name']];
            $major = ['id' => $course['major_id'], 'name_ar' => $course['major_name']];
            
            // جلب الطلاب المسجلين في المادة
            $registered_students = $db->fetchAll(
                "SELECT sc.*, s.student_number, s.full_name_ar, g.marks, g.letter_grade
                 FROM student_courses sc
                 JOIN students s ON sc.student_id = s.id
                 LEFT JOIN grades g ON sc.id = g.student_course_id
                 WHERE sc.course_id = ? AND sc.semester_id = ?
                 ORDER BY s.student_number",
                [$course_id, $semester_id]
            );
            
            // تصنيف الطلاب
            $is_alternative_course = $course['is_alternative'] == 1;
            
            foreach ($registered_students as $reg_student) {
                $is_failed = false;
                
                // إذا كانت المادة بديل، جميع الطلاب المسجلين فيها هم بديل
                if ($is_alternative_course) {
                    // تحديد الدرجة للعرض
                    $grade_display = '';
                    if ($reg_student['marks'] !== null) {
                        if (is_numeric($reg_student['marks'])) {
                            $grade_display = $reg_student['marks'];
                        } else {
                            $grade_display = $reg_student['marks'];
                        }
                    } elseif ($reg_student['letter_grade']) {
                        $grade_display = $reg_student['letter_grade'];
                    }
                    
                    $students_list[] = [
                        'student_number' => $reg_student['student_number'],
                        'full_name_ar' => $reg_student['full_name_ar'],
                        'status' => 'بديل',
                        'grade' => $grade_display
                    ];
                    continue;
                }
                
                // التحقق من الرسوب (للمواد العادية)
                if ($reg_student['marks'] !== null) {
                    if (is_numeric($reg_student['marks'])) {
                        // إذا كانت الدرجة رقمية، تحقق من كونها أقل من 50
                        $is_failed = ((float)$reg_student['marks'] < 50);
                    } else {
                        // إذا كانت نصية، تحقق من كونها F أو راسب أو غياب أو غش
                        $marks_text = trim($reg_student['marks']);
                        $letter_grade = trim($reg_student['letter_grade'] ?? '');
                        
                        if ($marks_text == 'غ' || $marks_text == 'غياب' || 
                            $marks_text == 'غش' || $marks_text == 'غشش' ||
                            $letter_grade == 'F' || $letter_grade == 'راسب' ||
                            $letter_grade == 'غ' || $letter_grade == 'غياب' ||
                            $letter_grade == 'غش' || $letter_grade == 'غشش') {
                            $is_failed = true;
                        }
                    }
                }
                
                // إضافة الطالب للقائمة إذا كان ملحق
                if ($is_failed) {
                    // تحديد الدرجة للعرض
                    $grade_display = '';
                    if ($reg_student['marks'] !== null) {
                        if (is_numeric($reg_student['marks'])) {
                            $grade_display = $reg_student['marks'];
                        } else {
                            $grade_display = $reg_student['marks'];
                        }
                    } elseif ($reg_student['letter_grade']) {
                        $grade_display = $reg_student['letter_grade'];
                    }
                    
                    $students_list[] = [
                        'student_number' => $reg_student['student_number'],
                        'full_name_ar' => $reg_student['full_name_ar'],
                        'status' => 'رسوب',
                        'grade' => $grade_display
                    ];
                }
            }
        }
    }
}

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

$university_name = "جامعة الشرق للعلوم والتكنولوجيا: Alsharg University of Science and Technology";

require_once __DIR__ . '/includes/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 rel="stylesheet" href="assets/css/style.css">
    <style>
        .report-container {
            background: white;
            padding: 30px;
            margin: 20px auto;
            max-width: 1200px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .report-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 3px solid #667eea;
        }
        
        .basmala {
            font-size: 20px;
            color: #666;
            margin-bottom: 15px;
            font-weight: bold;
        }
        
        .report-title {
            font-size: 24px;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .course-name {
            text-align: right;
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0;
            padding: 10px;
            background: #f5f5f5;
            border-right: 4px solid #667eea;
        }
        
        .report-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            font-size: 14px;
        }
        
        .report-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px;
            text-align: center;
            border: 1px solid #555;
            font-weight: bold;
        }
        
        .report-table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ddd;
        }
        
        .report-table tbody tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        .report-table tbody tr:hover {
            background-color: #f0f0f0;
        }
        
        .no-data {
            text-align: center;
            padding: 40px;
            color: #666;
            font-size: 18px;
        }
        
        .form-section {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .form-columns {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            align-items: end;
        }
        
        @media print {
            .form-section {
                display: none;
            }
            .report-container {
                box-shadow: none;
            }
        }
    </style>
</head>
<body>
    <?php require_once __DIR__ . '/includes/header.php'; ?>
    
    <div class="container">
        <h1>طلاب الملاحق والبدائل حسب المواد</h1>
        
        <div class="form-section">
            <form method="GET" action="طلاب_الملاحق_والبدائل_حسب_المواد.php" class="form-columns">
                <div class="form-group">
                    <label>اختر الكلية:</label>
                    <select name="college_id" id="college_id" onchange="loadMajors()" <?php echo (!$auth->hasRole('admin') && count($colleges) == 1) ? 'disabled' : ''; ?>>
                        <?php if (count($colleges) > 1 || $auth->hasRole('admin')): ?>
                            <option value="">-- اختر الكلية --</option>
                        <?php endif; ?>
                        <?php foreach ($colleges as $col): ?>
                            <option value="<?php echo $col['id']; ?>" <?php echo (isset($_GET['college_id']) && $_GET['college_id'] == $col['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($col['name_ar']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$auth->hasRole('admin') && count($colleges) == 1): ?>
                        <input type="hidden" name="college_id" value="<?php echo $colleges[0]['id']; ?>">
                    <?php endif; ?>
                </div>
                
                <div class="form-group">
                    <label>اختر التخصص:</label>
                    <select name="major_id" id="major_id" onchange="loadSemesters()">
                        <option value="">-- اختر التخصص --</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>اختر الفصل الدراسي:</label>
                    <select name="semester_id" id="semester_id" onchange="loadCourses()">
                        <option value="">-- اختر الفصل --</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>اختر المادة:</label>
                    <select name="course_id" id="course_id">
                        <option value="">-- اختر المادة --</option>
                    </select>
                </div>
                
                <div class="form-group" style="grid-column: 1 / -1;">
                    <button type="submit" class="btn btn-primary">عرض التقرير</button>
                </div>
            </form>
        </div>
        
        <?php if ($course && $semester && !empty($students_list)): ?>
            <div class="report-container">
                <div class="report-header">
                    <div class="basmala">بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ</div>
                    <div class="report-title" style="font-size: 18px;"><?php echo htmlspecialchars($university_name); ?></div>
                    <div class="report-title"><?php echo htmlspecialchars($college['name_ar']); ?></div>
                    <div class="report-title"><?php echo htmlspecialchars($major['name_ar']); ?></div>
                    <div class="report-title"><?php echo getSemesterName($semester['semester_number']); ?> - <?php echo htmlspecialchars($semester['academic_year']); ?></div>
                </div>
                
                <div class="course-name">
                    <?php echo htmlspecialchars($course['code']); ?> - <?php echo htmlspecialchars($course['name_ar']); ?>
                </div>
                
                <table class="report-table">
                    <thead>
                        <tr>
                            <th>م</th>
                            <th>الرقم الجامعي</th>
                            <th>اسم الطالب</th>
                            <th>الحالة</th>
                            <th>الدرجة</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $serial = 1;
                        foreach ($students_list as $student): 
                        ?>
                            <tr>
                                <td><?php echo $serial++; ?></td>
                                <td><?php echo htmlspecialchars($student['student_number']); ?></td>
                                <td><?php echo htmlspecialchars($student['full_name_ar']); ?></td>
                                <td><?php echo htmlspecialchars($student['status']); ?></td>
                                <td><?php echo htmlspecialchars($student['grade'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php elseif ($course && $semester && empty($students_list)): ?>
            <div class="report-container">
                <div class="report-header">
                    <div class="basmala">بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ</div>
                    <div class="report-title" style="font-size: 18px;"><?php echo htmlspecialchars($university_name); ?></div>
                    <div class="report-title"><?php echo htmlspecialchars($college['name_ar']); ?></div>
                    <div class="report-title"><?php echo htmlspecialchars($major['name_ar']); ?></div>
                    <div class="report-title"><?php echo getSemesterName($semester['semester_number']); ?> - <?php echo htmlspecialchars($semester['academic_year']); ?></div>
                </div>
                
                <div class="course-name">
                    <?php echo htmlspecialchars($course['code']); ?> - <?php echo htmlspecialchars($course['name_ar']); ?>
                </div>
                
                <div class="no-data">
                    هذه المادة ليس بها طالب بديل أو ملحق
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
    // AJAX functions for loading dropdowns
    function loadMajors() {
        const collegeId = document.getElementById('college_id').value;
        const majorSelect = document.getElementById('major_id');
        const semesterSelect = document.getElementById('semester_id');
        const courseSelect = document.getElementById('course_id');
        
        majorSelect.innerHTML = '<option value="">-- اختر التخصص --</option>';
        majorSelect.disabled = !collegeId;
        semesterSelect.innerHTML = '<option value="">-- اختر الفصل --</option>';
        semesterSelect.disabled = true;
        courseSelect.innerHTML = '<option value="">-- اختر المادة --</option>';
        courseSelect.disabled = true;
        
        if (!collegeId) return;
        
        fetch(`<?php echo basename(__FILE__); ?>?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 loadSemesters() {
        const majorId = document.getElementById('major_id').value;
        const semesterSelect = document.getElementById('semester_id');
        const courseSelect = document.getElementById('course_id');
        
        semesterSelect.innerHTML = '<option value="">-- اختر الفصل --</option>';
        semesterSelect.disabled = !majorId;
        courseSelect.innerHTML = '<option value="">-- اختر المادة --</option>';
        courseSelect.disabled = true;
        
        if (!majorId) return;
        
        fetch(`<?php echo basename(__FILE__); ?>?action=get_semesters&major_id=${majorId}`)
            .then(response => response.json())
            .then(data => {
                const semNames = {1:'الفصل الأول',2:'الفصل الثاني',3:'الفصل الثالث',4:'الفصل الرابع',5:'الفصل الخامس',6:'الفصل السادس',7:'الفصل السابع',8:'الفصل الثامن'};
                data.forEach(sem => {
                    const option = document.createElement('option');
                    option.value = sem.id;
                    option.textContent = (semNames[sem.semester_number] || ('فصل ' + sem.semester_number)) + ' - ' + sem.academic_year;
                    semesterSelect.appendChild(option);
                });
                semesterSelect.disabled = false;
            })
            .catch(error => console.error('Error loading semesters:', error));
    }
    
    function loadCourses() {
        const semesterId = document.getElementById('semester_id').value;
        const courseSelect = document.getElementById('course_id');
        
        courseSelect.innerHTML = '<option value="">-- اختر المادة --</option>';
        courseSelect.disabled = !semesterId;
        
        if (!semesterId) return;
        
        fetch(`<?php echo basename(__FILE__); ?>?action=get_courses&semester_id=${semesterId}`)
            .then(response => response.json())
            .then(data => {
                data.forEach(course => {
                    const option = document.createElement('option');
                    option.value = course.id;
                    option.textContent = `${course.code} - ${course.name_ar}`;
                    courseSelect.appendChild(option);
            });
                courseSelect.disabled = false;
            })
            .catch(error => console.error('Error loading courses:', error));
    }
    
    // تحميل البيانات عند تحميل الصفحة
    document.addEventListener('DOMContentLoaded', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const collegeId = urlParams.get('college_id');
        const majorId = urlParams.get('major_id');
        const semesterId = urlParams.get('semester_id');
        const courseId = urlParams.get('course_id');
        
        if (collegeId) {
            document.getElementById('college_id').value = collegeId;
            loadMajors();
            if (majorId) {
                setTimeout(() => {
                    document.getElementById('major_id').value = majorId;
                    loadSemesters();
                    if (semesterId) {
                        setTimeout(() => {
                            document.getElementById('semester_id').value = semesterId;
                            loadCourses();
                            if (courseId) {
                                setTimeout(() => {
                                    document.getElementById('course_id').value = courseId;
                                }, 100);
                            }
                        }, 100);
                    }
                }, 100);
            }
        }
    });
    </script>
    
    <?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>

