<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';
require_once __DIR__ . '/classes/GradeCalculator.php';
require_once __DIR__ . '/classes/ThorndikeCalibrator.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();

// معالجة 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 DISTINCT semester_number FROM semesters WHERE major_id = ? ORDER BY semester_number",
            [$major_id]
        );
        echo json_encode($semesters);
        exit;
    }
    
    if ($_GET['action'] == 'get_years' && isset($_GET['major_id']) && isset($_GET['semester_number'])) {
        $major_id = (int)$_GET['major_id'];
        $semester_number = (int)$_GET['semester_number'];
        $years = $db->fetchAll(
            "SELECT DISTINCT academic_year FROM semesters WHERE major_id = ? AND semester_number = ? ORDER BY academic_year DESC",
            [$major_id, $semester_number]
        );
        echo json_encode($years);
        exit;
    }
}

// دالة لتحويل المعدل الفصلي إلى تقدير حرفي
// التقدير الجديد: A (80-100), B (70-79), C (60-69), D (50-59), F (<50)
function getLetterGradeFromGPA($gpa) {
    // تحويل GPA من 5 إلى درجة رقمية تقريبية (GPA * 20)
    $estimated_marks = $gpa * 20;
    if ($estimated_marks >= 80 && $estimated_marks <= 100) return 'A';
    elseif ($estimated_marks >= 70 && $estimated_marks < 80) return 'B';
    elseif ($estimated_marks >= 60 && $estimated_marks < 70) return 'C';
    elseif ($estimated_marks >= 50 && $estimated_marks < 60) return 'D';
    else return 'F';
}

// دالة لحساب التقدير النصي بناءً على المعدل الفصلي (المعدل من 5)
// القواعد: >=4 ممتاز، >=3.5 جيد جداً، >=3 جيد، >=2.5 بدون رسوب مقبول، >=2.5 مع رسوب ملاحق، <2.5 إعادة السنة، <1.5 فصل بسبب المعدل
function getTextGrade($gpa, $status = '', $failed_credits = 0) {
    if ($gpa < 1.5) return 'فصل';
    if ($gpa < 2.5) return 'إعادة السنة';
    if ($gpa >= 2.5 && $gpa < 3) {
        if ($failed_credits > 0 || strpos($status, 'ملاحق') !== false) return 'ملاحق';
        return 'مقبول';
    }
    if ($gpa >= 3 && $gpa < 3.5) return 'جيد';
    if ($gpa >= 3.5 && $gpa < 4) return 'جيد جداً';
    if ($gpa >= 4 && $gpa <= 5) return 'ممتاز';
    return '-';
}

// دالة لتحويل رقم الفصل إلى نص عربي (الفصل الأول، الثاني، ...)
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;
    }
}

// دالة لحساب حالة الطالب
function calculateStudentStatus($student_grades, $courses_list, $total_semester_credits, $is_supplementary_student = false) {
    $failed_credits = 0;
    $failed_courses = [];
    $no_grade_courses = [];
    
    foreach ($courses_list as $course) {
        $grade = isset($student_grades[$course['id']]) ? $student_grades[$course['id']] : null;
        
        if ($grade) {
            $letter_grade = isset($grade['letter_grade']) ? trim($grade['letter_grade']) : '';
            $marks = isset($grade['marks']) ? $grade['marks'] : null;
            
            $is_failed = false;
            
            if ($marks !== null && !is_numeric($marks)) {
                $marks_text = trim($marks);
                if ($marks_text == 'ب') $marks_text = 'بد';
                
                if ($marks_text == 'بد') {
                    $is_failed = false;
                    $no_grade_courses[] = ['name_ar' => $course['name_ar'], 'code' => $course['code']];
                } elseif ($marks_text == 'غ' || $marks_text == 'غياب' || $marks_text == 'غش' || $marks_text == 'غشش') {
                    $is_failed = true;
                } else {
                    if ($letter_grade) {
                        $letter_grade_trimmed = trim($letter_grade);
                        if ($letter_grade_trimmed == 'ب') $letter_grade_trimmed = 'بد';
                        
                        if ($letter_grade_trimmed == 'بد') {
                            $is_failed = false;
                            $no_grade_courses[] = ['name_ar' => $course['name_ar'], 'code' => $course['code']];
                        } elseif ($letter_grade_trimmed == 'غ' || $letter_grade_trimmed == 'غياب' || 
                                  $letter_grade_trimmed == 'غش' || $letter_grade_trimmed == 'غشش' ||
                                  $letter_grade_trimmed == 'F' || $letter_grade_trimmed == 'راسب') {
                            $is_failed = true;
                        }
                    }
                }
            } elseif ($letter_grade) {
                $letter_grade_trimmed = trim($letter_grade);
                if ($letter_grade_trimmed == 'ب') $letter_grade_trimmed = 'بد';
                
                if ($letter_grade_trimmed == 'بد') {
                    $is_failed = false;
                    $no_grade_courses[] = ['name_ar' => $course['name_ar'], 'code' => $course['code']];
                } elseif ($letter_grade_trimmed == 'غ' || $letter_grade_trimmed == 'غياب' || 
                          $letter_grade_trimmed == 'غش' || $letter_grade_trimmed == 'غشش' ||
                          $letter_grade_trimmed == 'F' || $letter_grade_trimmed == 'راسب') {
                    $is_failed = true;
                }
            } elseif ($marks !== null && is_numeric($marks)) {
                $is_failed = ((float)$marks < 50);
            }
            
            if ($is_failed) {
                $failed_credits += (float)$course['credit_hours'];
                $failed_courses[] = ['name_ar' => $course['name_ar'], 'code' => $course['code'], 'credits' => (float)$course['credit_hours']];
            }
        }
    }
    
    $notes = '';
    $status = 'ناجح';
    
    if (!empty($no_grade_courses)) {
        $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
        $notes = 'بديل: ' . implode('، ', $no_grade_names);
    }
    
    if ($failed_credits > 0) {
        $one_third = $total_semester_credits / 3;
        $two_thirds = ($total_semester_credits * 2) / 3;
        $one_sixth = $total_semester_credits / 6;
        
        if ($is_supplementary_student) {
            if ($failed_credits > $one_sixth) {
                $status = 'إعادة الفصل';
                $notes = 'راسب في أكثر من سدس الساعات المعتمدة (' . number_format($failed_credits, 1) . ' من ' . number_format($total_semester_credits, 1) . ')';
                if (!empty($no_grade_courses)) {
                    $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
                    $notes .= ' | بديل: ' . implode('، ', $no_grade_names);
                }
            } else {
                $status = 'ناجح (يحمل المواد الراسبة)';
                $failed_course_names = array_map(function($course) { return $course['name_ar']; }, $failed_courses);
                $notes = 'يحمل المواد التالية: ' . implode('، ', $failed_course_names);
                if (!empty($no_grade_courses)) {
                    $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
                    $notes .= ' | بديل: ' . implode('، ', $no_grade_names);
                }
            }
        } else {
            if ($failed_credits > $two_thirds) {
                $status = 'فصل';
                $notes = 'راسب في أكثر من ثلثي الساعات المعتمدة (' . number_format($failed_credits, 1) . ' من ' . number_format($total_semester_credits, 1) . ')';
                if (!empty($no_grade_courses)) {
                    $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
                    $notes .= ' | بديل: ' . implode('، ', $no_grade_names);
                }
            } elseif ($failed_credits > $one_third) {
                $status = 'إعادة الفصل';
                $notes = 'راسب في أكثر من ثلث الساعات المعتمدة (' . number_format($failed_credits, 1) . ' من ' . number_format($total_semester_credits, 1) . ')';
                if (!empty($no_grade_courses)) {
                    $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
                    $notes .= ' | بديل: ' . implode('، ', $no_grade_names);
                }
            } else {
                $status = 'ملاحق';
                $failed_course_names = array_map(function($course) { return $course['name_ar']; }, $failed_courses);
                $notes_parts = [];
                if (!empty($no_grade_courses)) {
                    $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
                    $notes_parts[] = 'بديل: ' . implode('، ', $no_grade_names);
                }
                if (!empty($failed_course_names)) {
                    $notes_parts[] = 'ملاحق في: ' . implode('، ', $failed_course_names);
                }
                $notes = implode(' + ', $notes_parts);
            }
        }
    } else {
        if (!empty($no_grade_courses)) {
            $no_grade_names = array_map(function($course) { return $course['name_ar']; }, $no_grade_courses);
            $notes = 'بديل: ' . implode('، ', $no_grade_names);
        }
    }
    
    return [
        'status' => $status,
        'notes' => $notes,
        'failed_credits' => $failed_credits,
        'failed_courses' => $failed_courses
    ];
}

// دالة لترتيب الطلاب حسب الحالة
function getStudentSortOrder($student) {
    $status = $student['calibrated_status'] ?? $student['status'] ?? '';
    $notes = $student['calibrated_notes'] ?? $student['notes'] ?? '';
    $grades = $student['calibrated_grades'] ?? $student['grades'] ?? [];
    
    $has_cheating = false;
    foreach ($grades as $grade) {
        if ($grade) {
            $letter_grade = isset($grade['letter_grade']) ? trim($grade['letter_grade']) : '';
            $marks = isset($grade['marks']) ? $grade['marks'] : null;
            
            if (($marks !== null && !is_numeric($marks) && (trim($marks) == 'غش' || trim($marks) == 'غشش')) ||
                ($letter_grade == 'غش' || $letter_grade == 'غشش')) {
                $has_cheating = true;
                break;
            }
        }
    }
    
    $is_frozen = false;
    if (isset($student['status_db']) && ($student['status_db'] == 'suspended' || $student['status_db'] == 'frozen')) {
        $is_frozen = true;
    }
    
    if ($is_frozen) return 6;
    elseif ($has_cheating) return 5;
    elseif ($status == 'إعادة الفصل' || strpos($status, 'إعادة') !== false) return 4;
    elseif ($status == 'ملاحق' || strpos($status, 'ملاحق') !== false) {
        $has_alternative = strpos($notes, 'بديل') !== false || strpos($notes, 'بد') !== false;
        return $has_alternative ? 2 : 3;
    } elseif ($status == 'ناجح' || $status == 'ناجح (يحمل المواد الراسبة)') {
        $has_alternative = strpos($notes, 'بديل') !== false || strpos($notes, 'بد') !== false;
        $has_supplementary = strpos($notes, 'ملاحق') !== false;
        if ($has_alternative && $has_supplementary) return 2;
        elseif ($has_alternative) return 2;
        elseif ($has_supplementary) return 3;
        else return 1;
    } elseif ($status == 'فصل') return 4;
    else return 7;
}

function sortStudentsByStatus($students_data) {
    usort($students_data, function($a, $b) {
        $order_a = getStudentSortOrder($a);
        $order_b = getStudentSortOrder($b);
        
        if ($order_a == $order_b) {
            $gpa_a = $a['calibrated_gpa'] ?? $a['gpa'] ?? 0;
            $gpa_b = $b['calibrated_gpa'] ?? $b['gpa'] ?? 0;
            return $gpa_b <=> $gpa_a;
        }
        
        return $order_a <=> $order_b;
    });
    
    return $students_data;
}

// معالجة المعايير
$college_id = isset($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$major_id = isset($_GET['major_id']) ? (int)$_GET['major_id'] : 0;
$semester_number = isset($_GET['semester_number']) ? (int)$_GET['semester_number'] : 0;
$academic_year = isset($_GET['academic_year']) ? trim($_GET['academic_year']) : '';
$semester_id = 0;

// جلب معلومات الفصل الدراسي
$semester_info = null;
$college_info = null;
$major_info = null;
$students_data = [];
$courses_list = [];

if ($college_id && $major_id && $semester_number && $academic_year) {
    $semester = $db->fetchOne(
        "SELECT id FROM semesters 
         WHERE major_id = ? AND semester_number = ? AND academic_year = ?",
        [$major_id, $semester_number, $academic_year]
    );
    if ($semester) {
        $semester_id = $semester['id'];
    }
}

if ($semester_id) {
    $semester_info = $db->fetchOne(
        "SELECT s.*, m.name_ar as major_name, m.id as major_id, 
                c.name_ar as college_name, c.id as college_id
         FROM semesters s
         JOIN majors m ON s.major_id = m.id
         JOIN colleges c ON m.college_id = c.id
         WHERE s.id = ?",
        [$semester_id]
    );
    
    if ($semester_info) {
        if (!$auth->belongsToCollege($semester_info['college_id']) && !$auth->hasRole('admin')) {
            header('Location: semesters.php');
            exit;
        }
        
        $college_info = ['id' => $semester_info['college_id'], 'name_ar' => $semester_info['college_name']];
        $major_info = ['id' => $semester_info['major_id'], 'name_ar' => $semester_info['major_name']];
        
        $courses_list = $db->fetchAll(
            "SELECT c.id, c.code, c.name_ar, c.credit_hours, c.is_alternative
             FROM courses c
             WHERE c.semester_id = ?
             ORDER BY c.code",
            [$semester_id]
        );
        
        $total_semester_credits = array_sum(array_column($courses_list, 'credit_hours'));
        
        $students = $db->fetchAll(
            "SELECT DISTINCT s.id, s.student_number, s.full_name_ar, s.status as status_db
             FROM students s
             JOIN student_courses sc ON s.id = sc.student_id
             WHERE sc.semester_id = ?
             ORDER BY s.student_number",
            [$semester_id]
        );
        
        $calibrator = new ThorndikeCalibrator();
        $has_saved_calibration = $calibrator->hasCalibratedGrades($semester_id);
        $gradeCalculator = new GradeCalculator();
        
        foreach ($students as $student) {
            $student_grades = [];
            
            foreach ($courses_list as $course) {
                $grade = $db->fetchOne(
                    "SELECT g.marks, g.letter_grade, g.points
                     FROM grades g
                     WHERE g.student_id = ? AND g.course_id = ? AND g.semester_id = ?",
                    [$student['id'], $course['id'], $semester_id]
                );
                
                if ($grade) {
                    $student_grades[$course['id']] = $grade;
                }
            }
            
            $gpa_data = $gradeCalculator->calculateSemesterGPAFromGrades($student_grades, $courses_list);
            $gpa = $gpa_data['gpa'];
            $letter_grade = $gpa > 0 ? getLetterGradeFromGPA($gpa) : '-';
            $student_status = calculateStudentStatus($student_grades, $courses_list, $total_semester_credits, false);
            $failed_credits = isset($student_status['failed_credits']) ? $student_status['failed_credits'] : 0;
            $text_grade = getTextGrade($gpa, $student_status['status'], $failed_credits);
            
            $alternative_courses = [];
            foreach ($courses_list as $course) {
                if (isset($course['is_alternative']) && $course['is_alternative']) {
                    $grade = isset($student_grades[$course['id']]) ? $student_grades[$course['id']] : null;
                    if ($grade && $grade['letter_grade'] && $grade['letter_grade'] !== 'بد') {
                        $alternative_courses[] = $course['name_ar'];
                    }
                }
            }
            
            if (!empty($alternative_courses)) {
                $text_grade .= ' (بديل: ' . implode('، ', $alternative_courses) . ')';
            }
            
            // جلب الدرجات المعايرة
            $calibrated_grades = [];
            
            if ($has_saved_calibration) {
                $saved_grades = $calibrator->getSavedCalibratedGrades($semester_id);
                $saved_grades_map = [];
                
                foreach ($saved_grades as $saved_grade) {
                    $key = $saved_grade['student_id'] . '_' . $saved_grade['course_id'];
                    $saved_grades_map[$key] = $saved_grade;
                }
                
                foreach ($courses_list as $course) {
                    $key = $student['id'] . '_' . $course['id'];
                    if (isset($saved_grades_map[$key])) {
                        $saved_grade = $saved_grades_map[$key];
                        $calibrated_grades[$course['id']] = [
                            'marks' => $saved_grade['calibrated_marks'],
                            'letter_grade' => $saved_grade['calibrated_letter_grade'],
                            'points' => $saved_grade['calibrated_points'],
                            'original_marks' => $saved_grade['original_marks']
                        ];
                    } else {
                        $original_grade = isset($student_grades[$course['id']]) ? $student_grades[$course['id']] : null;
                        if ($original_grade) {
                            $calibrated_grades[$course['id']] = [
                                'marks' => $original_grade['marks'],
                                'letter_grade' => $original_grade['letter_grade'],
                                'points' => $original_grade['points'],
                                'original_marks' => $original_grade['marks']
                            ];
                        } else {
                            $calibrated_grades[$course['id']] = null;
                        }
                    }
                }
            } else {
                $calibrated_grades = $student_grades;
            }
            
            $calibrated_gpa_data = $gradeCalculator->calculateSemesterGPAFromGrades($calibrated_grades, $courses_list);
            $calibrated_gpa = $calibrated_gpa_data['gpa'];
            $calibrated_letter_grade = $calibrated_gpa > 0 ? getLetterGradeFromGPA($calibrated_gpa) : '-';
            $calibrated_status = calculateStudentStatus($calibrated_grades, $courses_list, $total_semester_credits, false);
            $calibrated_failed_credits = isset($calibrated_status['failed_credits']) ? $calibrated_status['failed_credits'] : 0;
            $calibrated_text_grade = getTextGrade($calibrated_gpa, $calibrated_status['status'], $calibrated_failed_credits);
            
            $alternative_courses_cal = [];
            foreach ($courses_list as $course) {
                if (isset($course['is_alternative']) && $course['is_alternative']) {
                    $cal_grade = isset($calibrated_grades[$course['id']]) ? $calibrated_grades[$course['id']] : null;
                    if ($cal_grade && $cal_grade['letter_grade'] && $cal_grade['letter_grade'] !== 'بد') {
                        $alternative_courses_cal[] = $course['name_ar'];
                    }
                }
            }
            
            if (!empty($alternative_courses_cal)) {
                $calibrated_text_grade .= ' (بديل: ' . implode('، ', $alternative_courses_cal) . ')';
            }
            
            $students_data[] = [
                'id' => $student['id'],
                'student_number' => $student['student_number'],
                'full_name_ar' => $student['full_name_ar'],
                'grades' => $student_grades,
                'gpa' => $gpa,
                'letter_grade' => $letter_grade,
                'text_grade' => $text_grade,
                'status' => $student_status['status'],
                'notes' => $student_status['notes'],
                'failed_credits' => $student_status['failed_credits'] ?? 0,
                'failed_courses' => $student_status['failed_courses'] ?? [],
                'calibrated_grades' => $calibrated_grades,
                'calibrated_gpa' => $calibrated_gpa,
                'calibrated_letter_grade' => $calibrated_letter_grade,
                'calibrated_text_grade' => $calibrated_text_grade,
                'calibrated_status' => $calibrated_status['status'],
                'calibrated_notes' => $calibrated_status['notes'],
                'calibrated_failed_credits' => $calibrated_failed_credits,
                'calibrated_failed_courses' => $calibrated_status['failed_courses'] ?? [],
                'status_db' => $student['status_db'] ?? null
            ];
        }
        
        // ترتيب الطلاب أبجدياً حسب الاسم
        usort($students_data, function($a, $b) { return strcmp($a['full_name_ar'], $b['full_name_ar']); });
    }
}

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

$majors = [];
if (isset($college_id) && $college_id) {
    $majors = $db->fetchAll("SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar", [$college_id]);
}

$semesters = [];
if (isset($major_id) && $major_id) {
    $semesters = $db->fetchAll(
        "SELECT DISTINCT semester_number FROM semesters WHERE major_id = ? ORDER BY semester_number",
        [$major_id]
    );
}

$years = [];
if (isset($major_id) && $major_id && isset($semester_number) && $semester_number) {
    $years = $db->fetchAll(
        "SELECT DISTINCT academic_year FROM semesters WHERE major_id = ? AND semester_number = ? ORDER BY academic_year DESC",
        [$major_id, $semester_number]
    );
}

require_once __DIR__ . '/includes/header.php';
$university_name = "جامعة الشرق للعلوم والتكنولوجيا: Alsharg University of Science and Technology";
?>

<!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>
    <?php include __DIR__ . '/includes/compatibility.php'; ?>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .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(4, 1fr);
            gap: 20px;
            align-items: end;
        }
        
        .form-column {
            display: flex;
            flex-direction: column;
        }
        
        .form-column-full {
            grid-column: 1 / -1;
        }
        
        .form-column .form-group {
            margin-bottom: 0;
        }
        
        .form-column label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
            font-size: 14px;
        }
        
        .form-column select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            background-color: white;
        }
        
        .form-column select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }
        
        .form-column select:disabled {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
        
        @media (max-width: 1200px) {
            .form-columns {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .form-columns {
                grid-template-columns: 1fr;
            }
        }
        
        .results-section {
            margin: 30px 0;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .results-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 3px solid #667eea;
        }
        
        .basmala {
            font-size: 18px;
            color: #666;
            margin-bottom: 10px;
        }
        
        .results-table {
            overflow-x: auto;
            margin-top: 20px;
            -webkit-overflow-scrolling: touch;
        }
        
        .results-table table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85em;
            table-layout: auto;
            min-width: 100%;
            border: 2px solid #000;
        }
        
        .results-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 7px 6px;
            text-align: center;
            border: 2px solid #000;
            font-weight: bold;
            vertical-align: middle;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        
        .results-table th.student-number-cell,
        .results-table td.student-number-cell {
            font-size: 0.8em;
            max-width: 90px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .results-table td {
            padding: 5px 5px;
            text-align: center;
            border: 2px solid #000;
            vertical-align: middle;
        }
        
        .results-table tbody tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        .results-table tbody tr:hover {
            background-color: #f0f0f0;
        }
        
        .grade-original {
            background-color: #f5f5f5;
        }
        
        .grade-calibrated {
            background-color: #e8f5e9;
            font-weight: bold;
        }
        
        .gpa-cell {
            font-weight: bold;
            color: #2c3e50;
        }
        
        .letter-grade-cell {
            font-weight: bold;
            color: #667eea;
        }
        .print-btns-group {
            display: inline-flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 12px;
        }
        .print-btns-group .btn {
            padding: 8px 16px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            border-radius: 8px;
            cursor: pointer;
            font-weight: bold;
        }
        .print-btns-group .btn:hover {
            background: #667eea;
            color: white;
        }
        @media print {
            @page {
                size: A4;
                margin: 12mm;
                @bottom-center {
                    content: "صفحة " counter(page) " من " counter(pages);
                    font-size: 9pt;
                    font-family: inherit;
                }
            }
            @page landscape {
                size: A4 landscape;
                margin: 12mm;
                @bottom-center {
                    content: "صفحة " counter(page) " من " counter(pages);
                    font-size: 9pt;
                    font-family: inherit;
                }
            }
            body.print-landscape .results-section {
                page: landscape;
            }
            .main-header, .main-footer,
            .container h1,
            .form-section,
            .print-btns-group {
                display: none !important;
            }
            body { margin: 0; padding: 0; }
            .container { padding: 0; max-width: 100%; }
            .results-section {
                margin: 0;
                padding: 0;
                box-shadow: none;
            }
            .results-header {
                page-break-after: avoid;
            }
            .results-table thead {
                page-break-inside: avoid;
            }
            .results-table table {
                font-size: 8pt;
            }
            .results-table th,
            .results-table td {
                padding: 3px 4px;
            }
            .results-header .basmala {
                font-size: 14px;
            }
            .results-header h1 {
                font-size: 14px !important;
            }
            .results-header h2,
            .results-header h3 {
                font-size: 12px !important;
            }
        }
    </style>
</head>
<body>
<?php require_once __DIR__ . '/includes/header.php'; ?>

<div class="container">
    <h1>النتيجة التي ستعرض للطلاب</h1>
    
    <div class="form-section">
        <form method="GET" action="student_facing_results.php" class="form-columns">
            <div class="form-column">
                <div class="form-group">
                    <label>اختر الكلية:</label>
                    <select name="college_id" id="college_id" required 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 $college): ?>
                            <option value="<?php echo $college['id']; ?>" <?php echo ($college_id == $college['id'] || (!$auth->hasRole('admin') && count($colleges) == 1)) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($college['name_ar']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$auth->hasRole('admin') && count($colleges) == 1): ?>
                        <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="form-column">
                <div class="form-group">
                    <label>اختر التخصص:</label>
                    <select name="major_id" id="major_id" required onchange="loadSemesters()" <?php echo !$college_id ? 'disabled' : ''; ?>>
                        <option value="">-- اختر التخصص --</option>
                        <?php foreach ($majors as $major): ?>
                            <option value="<?php echo $major['id']; ?>" <?php echo $major_id == $major['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($major['name_ar']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="form-column">
                <div class="form-group">
                    <label>اختر الفصل الدراسي:</label>
                    <select name="semester_number" id="semester_number" required onchange="loadYears()" <?php echo !$major_id ? 'disabled' : ''; ?>>
                        <option value="">-- اختر الفصل --</option>
                        <?php foreach ($semesters as $sem): ?>
                            <option value="<?php echo $sem['semester_number']; ?>" <?php echo $semester_number == $sem['semester_number'] ? 'selected' : ''; ?>>
                                <?php echo getSemesterName($sem['semester_number']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="form-column">
                <div class="form-group">
                    <label>اختر السنة الدراسية:</label>
                    <select name="academic_year" id="academic_year" required <?php echo !$semester_number ? 'disabled' : ''; ?>>
                        <option value="">-- اختر السنة --</option>
                        <?php foreach ($years as $year): ?>
                            <option value="<?php echo htmlspecialchars($year['academic_year']); ?>" <?php echo $academic_year == $year['academic_year'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($year['academic_year']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="form-column form-column-full">
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">عرض النتيجة</button>
                </div>
            </div>
        </form>
    </div>
    
    <?php if ($semester_id && $semester_info && !empty($students_data)): ?>
        <div class="results-section">
            <div class="results-header">
                <div class="print-btns-group">
                    <button type="button" class="btn" onclick="printResults('portrait')" title="طباعة بالطول">🖨️ طباعة بالطول</button>
                    <button type="button" class="btn" onclick="printResults('landscape')" title="طباعة بالعرض">🖨️ طباعة بالعرض</button>
                </div>
                <div class="basmala">بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ</div>
                <h1 style="font-size: 18px;"><?php echo htmlspecialchars($university_name); ?></h1>
                <h2><?php echo htmlspecialchars($college_info['name_ar']); ?></h2>
                <?php if (trim($major_info['name_ar'] ?? '') !== 'الكلية'): ?>
                <h3><?php echo htmlspecialchars($major_info['name_ar']); ?></h3>
                <?php endif; ?>
                <h3>نتائج <?php echo getSemesterName($semester_info['semester_number']); ?> - <?php echo htmlspecialchars($semester_info['academic_year']); ?></h3>
            </div>
            
            <div class="results-table table-container">
                <table>
                    <thead>
                        <tr>
                            <th>م</th>
                            <th class="student-number-cell">الرقم الجامعي</th>
                            <th>اسم الطالب</th>
                            <?php foreach ($courses_list as $course): ?>
                                <th><?php echo htmlspecialchars($course['name_ar']); ?></th>
                            <?php endforeach; ?>
                            <th>المعدل الفصلي</th>
                            <th>التقدير</th>
                            <th>ملاحظات</th>
                        </tr>
                        <tr>
                            <th></th>
                            <th class="student-number-cell"></th>
                            <th>الساعات</th>
                            <?php foreach ($courses_list as $course): ?>
                                <th><?php echo (float)$course['credit_hours']; ?></th>
                            <?php endforeach; ?>
                            <th></th>
                            <th></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $serial = 1;
                        foreach ($students_data as $student): 
                        ?>
                            <tr>
                                <td><?php echo $serial++; ?></td>
                                <td class="student-number-cell"><?php echo htmlspecialchars($student['student_number']); ?></td>
                                <td><?php echo htmlspecialchars($student['full_name_ar']); ?></td>
                                <?php foreach ($courses_list as $course): ?>
                                    <?php 
                                    // عرض التقدير الحرفي فقط (للعرض على الطلاب)
                                    $gr = $has_saved_calibration ? (isset($student['calibrated_grades'][$course['id']]) ? $student['calibrated_grades'][$course['id']] : null) : (isset($student['grades'][$course['id']]) ? $student['grades'][$course['id']] : null);
                                    $display_value = '-';
                                    if ($gr) {
                                        if (isset($gr['marks']) && $gr['marks'] !== null && is_numeric($gr['marks'])) {
                                            $pts = $gradeCalculator->calculatePoints($gr['marks']);
                                            $display_value = htmlspecialchars($pts['letter']);
                                        } elseif (isset($gr['letter_grade']) && trim((string)$gr['letter_grade']) !== '') {
                                            $cleaned = $gradeCalculator->cleanLetterGrade($gr['letter_grade']);
                                            $display_value = $cleaned !== null ? htmlspecialchars($cleaned) : htmlspecialchars(trim($gr['letter_grade']));
                                        }
                                    }
                                    ?>
                                    <td style="text-align: center;">
                                        <?php echo $display_value; ?>
                                    </td>
                                <?php endforeach; ?>
                                <td class="gpa-cell">
                                    <?php 
                                    if ($has_saved_calibration) {
                                        echo $student['calibrated_gpa'] > 0 ? number_format($student['calibrated_gpa'], 2) : '-';
                                    } else {
                                        echo $student['gpa'] > 0 ? number_format($student['gpa'], 2) : '-';
                                    }
                                    ?>
                                </td>
                                <td class="letter-grade-cell">
                                    <?php 
                                    if ($has_saved_calibration) {
                                        echo isset($student['calibrated_text_grade']) ? htmlspecialchars($student['calibrated_text_grade']) : '-';
                                    } else {
                                        echo isset($student['text_grade']) ? htmlspecialchars($student['text_grade']) : '-';
                                    }
                                    ?>
                                </td>
                                <td style="text-align: right; font-size: 0.9em;">
                                    <?php 
                                    $grades_for_notes = $has_saved_calibration ? ($student['calibrated_grades'] ?? []) : ($student['grades'] ?? []);
                                    $all_absence = true;
                                    $has_any_course = false;
                                    foreach ($courses_list as $c) {
                                        if (isset($c['is_alternative']) && $c['is_alternative']) continue;
                                        $has_any_course = true;
                                        $gr = isset($grades_for_notes[$c['id']]) ? $grades_for_notes[$c['id']] : null;
                                        if (!$gr) { $all_absence = false; break; }
                                        $m = isset($gr['marks']) ? trim((string)$gr['marks']) : '';
                                        $l = isset($gr['letter_grade']) ? trim((string)$gr['letter_grade']) : '';
                                        $is_absence = ($m === 'غ' || $m === 'غياب' || $l === 'غ' || $l === 'غياب');
                                        if (!$is_absence) { $all_absence = false; break; }
                                    }
                                    if ($has_any_course && $all_absence) {
                                        $display_notes = 'فصل بسبب الغياب';
                                        $status_color = 'color: #f44336; font-weight: bold;';
                                    } else {
                                        $gpa_notes = $has_saved_calibration ? (float)($student['calibrated_gpa'] ?? 0) : (float)($student['gpa'] ?? 0);
                                        $failed_credits_notes = $has_saved_calibration ? ($student['calibrated_failed_credits'] ?? 0) : ($student['failed_credits'] ?? 0);
                                        $failed_courses_notes = $has_saved_calibration ? ($student['calibrated_failed_courses'] ?? []) : ($student['failed_courses'] ?? []);
                                        
                                        if ($gpa_notes < 1.5) {
                                            $display_notes = 'فصل بسبب تدني المعدل';
                                            $status_color = 'color: #f44336; font-weight: bold;';
                                        } elseif ($gpa_notes < 2.5) {
                                            $display_notes = 'اعادة بسبب تدني المعدل';
                                            $status_color = 'color: #ff9800; font-weight: bold;';
                                        } elseif ($gpa_notes >= 2.5 && $failed_credits_notes > 0) {
                                            $failed_names = array_map(function($c) { return $c['name_ar'] ?? ''; }, $failed_courses_notes);
                                            $failed_names = array_filter($failed_names);
                                            $display_notes = !empty($failed_names) ? 'ملاحق: ' . implode('، ', $failed_names) : 'ملاحق';
                                            $status_color = 'color: #2196F3; font-weight: bold;';
                                        } elseif ($gpa_notes >= 2.5) {
                                            $display_notes = 'ناجح';
                                            $status_color = '';
                                        } else {
                                            $display_notes = '-';
                                            $status_color = '';
                                        }
                                    }
                                    
                                    if ($display_notes !== '-') {
                                        echo '<div style="' . $status_color . '">' . htmlspecialchars($display_notes) . '</div>';
                                    } else {
                                        echo '-';
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php elseif ($semester_id && $semester_info && empty($students_data)): ?>
        <div class="alert alert-warning">
            لا توجد نتائج للطلاب في هذا الفصل الدراسي.
        </div>
    <?php endif; ?>
</div>

<script>
const semesterNames = <?php echo json_encode([
    1 => 'الفصل الأول', 2 => 'الفصل الثاني', 3 => 'الفصل الثالث', 4 => 'الفصل الرابع',
    5 => 'الفصل الخامس', 6 => 'الفصل السادس', 7 => 'الفصل السابع', 8 => 'الفصل الثامن'
]); ?>;
function getSemesterLabel(n) { return semesterNames[n] || ('فصل ' + n); }

function loadMajors() {
    const collegeId = document.getElementById('college_id').value;
    const majorSelect = document.getElementById('major_id');
    const semesterSelect = document.getElementById('semester_number');
    const yearSelect = document.getElementById('academic_year');
    
    majorSelect.innerHTML = '<option value="">-- اختر التخصص --</option>';
    majorSelect.disabled = !collegeId;
    semesterSelect.innerHTML = '<option value="">-- اختر الفصل --</option>';
    semesterSelect.disabled = true;
    yearSelect.innerHTML = '<option value="">-- اختر السنة --</option>';
    yearSelect.disabled = true;
    
    if (!collegeId) return;
    
    fetch(`student_facing_results.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 loadSemesters() {
    const majorId = document.getElementById('major_id').value;
    const semesterSelect = document.getElementById('semester_number');
    const yearSelect = document.getElementById('academic_year');
    
    semesterSelect.innerHTML = '<option value="">-- اختر الفصل --</option>';
    semesterSelect.disabled = !majorId;
    yearSelect.innerHTML = '<option value="">-- اختر السنة --</option>';
    yearSelect.disabled = true;
    
    if (!majorId) return;
    
    fetch(`student_facing_results.php?action=get_semesters&major_id=${majorId}`)
        .then(response => response.json())
        .then(data => {
            const uniqueSemesters = [...new Set(data.map(s => s.semester_number))];
            uniqueSemesters.forEach(semNum => {
                const option = document.createElement('option');
                option.value = semNum;
                option.textContent = getSemesterLabel(semNum);
                semesterSelect.appendChild(option);
            });
            semesterSelect.disabled = false;
        })
        .catch(error => console.error('Error loading semesters:', error));
}

function loadYears() {
    const majorId = document.getElementById('major_id').value;
    const semesterNumber = document.getElementById('semester_number').value;
    const yearSelect = document.getElementById('academic_year');
    
    yearSelect.innerHTML = '<option value="">-- اختر السنة --</option>';
    yearSelect.disabled = !semesterNumber;
    
    if (!semesterNumber) return;
    
    fetch(`student_facing_results.php?action=get_years&major_id=${majorId}&semester_number=${semesterNumber}`)
        .then(response => response.json())
        .then(data => {
            data.forEach(year => {
                const option = document.createElement('option');
                option.value = year.academic_year;
                option.textContent = year.academic_year;
                yearSelect.appendChild(option);
            });
            yearSelect.disabled = false;
        })
        .catch(error => console.error('Error loading years:', error));
}

// تحميل التخصصات والفصول عند تحميل الصفحة
document.addEventListener('DOMContentLoaded', function() {
    const collegeId = document.getElementById('college_id').value;
    const majorId = document.getElementById('major_id').value;
    const semesterNumber = document.getElementById('semester_number').value;
    
    if (collegeId && !majorId) {
        loadMajors();
    } else if (collegeId && majorId && !semesterNumber) {
        loadMajors();
        setTimeout(() => {
            document.getElementById('major_id').value = majorId;
            loadSemesters();
        }, 100);
    } else if (collegeId && majorId && semesterNumber) {
        loadMajors();
        setTimeout(() => {
            document.getElementById('major_id').value = majorId;
            loadSemesters();
            setTimeout(() => {
                document.getElementById('semester_number').value = semesterNumber;
                loadYears();
            }, 100);
        }, 100);
    }
});

function printResults(orientation) {
    if (orientation === 'landscape') {
        document.body.classList.add('print-landscape');
    } else {
        document.body.classList.remove('print-landscape');
    }
    window.print();
}
window.addEventListener('afterprint', function() {
    document.body.classList.remove('print-landscape');
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>

