<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';
require_once __DIR__ . '/classes/GradeCalculator.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || (!$auth->hasPermission('enter_grades') && !$auth->hasPermission('manage_grades'))) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();
$gradeCalculator = new GradeCalculator();

// دالة لتحويل رقم الفصل إلى نص عربي (الفصل الأول، الثاني، ...)
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;
    }
}
$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 = isset($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
$message = '';

// معالجة حفظ التعديلات
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_grades') {
    // الحصول على المعاملات من POST
    $post_college_id = isset($_POST['college_id']) ? (int)$_POST['college_id'] : 0;
    $post_major_id = isset($_POST['major_id']) ? (int)$_POST['major_id'] : 0;
    $post_semester_number = isset($_POST['semester_number']) ? (int)$_POST['semester_number'] : 0;
    $post_academic_year = isset($_POST['academic_year']) ? trim($_POST['academic_year']) : '';
    
    // الحصول على semester_id من POST أو من semester_number و academic_year
    $post_semester_id = isset($_POST['semester_id']) ? (int)$_POST['semester_id'] : 0;
    if ($post_semester_id <= 0 && $post_major_id > 0 && $post_semester_number > 0 && $post_academic_year !== '') {
        $semester_check = $db->fetchOne(
            "SELECT id FROM semesters WHERE major_id = ? AND semester_number = ? AND academic_year = ?",
            [$post_major_id, $post_semester_number, $post_academic_year]
        );
        if ($semester_check) {
            $post_semester_id = $semester_check['id'];
        }
    }
    
    $grades_data = $_POST['grades'] ?? [];
    $success_count = 0;
    $error_count = 0;
    $updated_students = [];
    
    if (empty($grades_data)) {
        $message = '<div class="alert alert-warning">⚠️ لم يتم إدخال أي درجات</div>';
    } elseif ($post_semester_id <= 0) {
        $message = '<div class="alert alert-error">⚠️ خطأ: لم يتم تحديد الفصل الدراسي بشكل صحيح</div>';
    } else {
        try {
            $db->getConnection()->beginTransaction();
            
            foreach ($grades_data as $key => $marks_input) {
                // تحليل المفتاح: student_id-course_id
                $parts = explode('-', $key);
                if (count($parts) !== 2) {
                    $error_count++;
                    continue;
                }
                
                $student_id = (int)$parts[0];
                $course_id = (int)$parts[1];
                $marks_input = trim($marks_input);
                
                // تخطي الحقول الفارغة
                if ($marks_input === '') {
                    continue;
                }
                
                // معالجة الدرجة (رقمية أو نصية)
                $grade_data = $gradeCalculator->processGradeInput($marks_input);
                
                if (!$grade_data) {
                    $error_count++;
                    continue;
                }
                
                // التحقق من نطاق الدرجة الرقمية
                if (!$grade_data['is_text'] && ($grade_data['marks'] < 0 || $grade_data['marks'] > 100)) {
                    $error_count++;
                    continue;
                }
                
                // جلب معلومات تسجيل الطالب في المادة
                $student_course = $db->fetchOne(
                    "SELECT sc.*, s.college_id, s.id as student_id 
                     FROM student_courses sc 
                     JOIN students s ON sc.student_id = s.id 
                     WHERE sc.student_id = ? AND sc.course_id = ? AND sc.semester_id = ?",
                    [$student_id, $course_id, $post_semester_id]
                );
                
                if (!$student_course) {
                    $error_count++;
                    continue;
                }
                
                // التحقق من الصلاحيات
                if (!$auth->belongsToCollege($student_course['college_id']) && !$auth->hasRole('admin')) {
                    $error_count++;
                    continue;
                }
                
                // إعداد القيم للحفظ
                if ($grade_data['is_text']) {
                    $marks = $marks_input; // حفظ القيمة النصية الأصلية
                } else {
                    $marks = $grade_data['marks'] !== null ? $grade_data['marks'] : 0;
                }
                $letter_grade = $grade_data['letter_grade'];
                $points = $grade_data['points'];
                
                // التحقق من وجود درجة سابقة
                $existing = $db->fetchOne(
                    "SELECT * FROM grades WHERE student_course_id = ?",
                    [$student_course['id']]
                );
                
                if ($existing) {
                    // تحديث الدرجة
                    $db->query(
                        "UPDATE grades SET marks = ?, letter_grade = ?, points = ?, updated_at = CURRENT_TIMESTAMP, entered_by = ?
                         WHERE student_course_id = ?",
                        [$marks, $letter_grade, $points, $_SESSION['user_id'], $student_course['id']]
                    );
                } else {
                    // إضافة درجة جديدة
                    $db->query(
                        "INSERT INTO grades (student_course_id, student_id, course_id, semester_id, marks, letter_grade, points, entered_by) 
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                        [
                            $student_course['id'],
                            $student_course['student_id'],
                            $student_course['course_id'],
                            $student_course['semester_id'],
                            $marks,
                            $letter_grade,
                            $points,
                            $_SESSION['user_id']
                        ]
                    );
                }
                
                $success_count++;
                if (!in_array($student_id, $updated_students)) {
                    $updated_students[] = $student_id;
                }
            }
            
            // تأكيد المعاملة
            $db->getConnection()->commit();
            
            // تحديث المعدلات لجميع الطلاب المحدثين
            foreach ($updated_students as $student_id) {
                try {
                    $gradeCalculator->updateAllGPAs($student_id);
                } catch (Exception $e) {
                    error_log("Error updating GPA for student $student_id: " . $e->getMessage());
                }
            }
            
            // بناء رسالة النتيجة
            if ($success_count > 0) {
                $message = '<div class="alert alert-success">✓ تم حفظ ' . $success_count . ' درجة بنجاح</div>';
            }
            if ($error_count > 0) {
                $message .= '<div class="alert alert-warning">⚠ ' . $error_count . ' خطأ في الإدخال (تم تخطيها)</div>';
            }
            
            // إعادة توجيه لتجنب إعادة إرسال النموذج
            if ($success_count > 0) {
                $redirect_params = [];
                if ($post_college_id > 0) $redirect_params[] = 'college_id=' . $post_college_id;
                if ($post_major_id > 0) $redirect_params[] = 'major_id=' . $post_major_id;
                if ($post_semester_number > 0) $redirect_params[] = 'semester_number=' . $post_semester_number;
                if ($post_academic_year !== '') $redirect_params[] = 'academic_year=' . urlencode($post_academic_year);
                $redirect_params[] = 'msg=success';
                $redirect_params[] = 'count=' . $success_count;
                
                header("Location: edit_major_semester_grades.php?" . implode('&', $redirect_params));
                exit;
            }
            
        } catch (Exception $e) {
            $db->getConnection()->rollBack();
            $message = '<div class="alert alert-error">
                <strong>خطأ في حفظ الدرجات:</strong><br>
                ' . htmlspecialchars($e->getMessage()) . '<br>
                <small>يرجى التحقق من سجلات الأخطاء للتفاصيل</small>
            </div>';
            error_log("Error saving grades: " . $e->getMessage());
            error_log("POST data: " . print_r($_POST, true));
            error_log("Grades data: " . print_r($grades_data, true));
        }
    }
}

// عرض رسالة النجاح من URL
if (isset($_GET['msg']) && $_GET['msg'] === 'success') {
    if (isset($_GET['count']) && (int)$_GET['count'] > 0) {
        $message = '<div class="alert alert-success">✓ تم حفظ ' . (int)$_GET['count'] . ' درجة بنجاح</div>';
    } else {
        $message = '<div class="alert alert-success">✓ تم حفظ الدرجات بنجاح</div>';
    }
}

// جلب البيانات
$college = null;
$major = null;
$semester = null;
$students = [];
$courses = [];
$grades_map = []; // خريطة للدرجات: ['student_id-course_id' => grade_data]
$registrations_map = []; // خريطة للتسجيلات: ['student_id-course_id' => true]
$course_ids_by_name = []; // مفتاح الاسم الموحّد => مصفوفة معرفات المواد (لدمج المكرر)
$normalize_name = function ($n) {
    $n = preg_replace('/\s+/u', ' ', trim($n ?? ''));
    $n = preg_replace('/\s*\(\s*/u', '(', $n);
    $n = preg_replace('/\s*\)\s*/u', ')', $n);
    // دمج صيغ مثل "(1)" و "_1" في مفتاح واحد
    $n = preg_replace('/\((\d+)\)/u', '_$1', $n);
    return $n;
};

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

// جلب التخصصات المتاحة (حسب الكلية المحددة)
$available_majors = [];
if ($college_id > 0) {
    $college = $db->fetchOne("SELECT * FROM colleges WHERE id = ?", [$college_id]);
    if ($college && ($auth->belongsToCollege($college_id) || $auth->hasRole('admin'))) {
        $available_majors = $db->fetchAll(
            "SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar",
            [$college_id]
        );
    }
}

// جلب الفصول الدراسية المتاحة (حسب التخصص المحدد)
$available_semester_numbers = [];
$available_academic_years = [];
if ($major_id > 0) {
    $major = $db->fetchOne(
        "SELECT m.*, c.name_ar as college_name, c.id as college_id 
         FROM majors m 
         JOIN colleges c ON m.college_id = c.id 
         WHERE m.id = ?",
        [$major_id]
    );
    
    if ($major && ($auth->belongsToCollege($major['college_id']) || $auth->hasRole('admin'))) {
        // جلب أرقام الفصول الدراسية المتاحة لهذا التخصص
        $semesters_list = $db->fetchAll(
            "SELECT DISTINCT semester_number FROM semesters WHERE major_id = ? ORDER BY semester_number",
            [$major_id]
        );
        $available_semester_numbers = array_column($semesters_list, 'semester_number');
        
        // جلب السنوات الدراسية المتاحة (حسب رقم الفصل المحدد)
        if ($semester_number > 0) {
            $years_list = $db->fetchAll(
                "SELECT DISTINCT academic_year FROM semesters WHERE major_id = ? AND semester_number = ? ORDER BY academic_year DESC",
                [$major_id, $semester_number]
            );
            $available_academic_years = array_column($years_list, 'academic_year');
            
            // جلب الفصل الدراسي المحدد
            if ($academic_year !== '') {
                $semester = $db->fetchOne(
                    "SELECT * 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 > 0 && $semester) {
            // جلب جميع الطلاب في التخصص
                $students = $db->fetchAll(
                    "SELECT id, student_number, full_name_ar, full_name_en, major_id, college_id, status 
                     FROM students 
                     WHERE major_id = ? AND status = 'active'
                     ORDER BY student_number",
                    [$major_id]
                );
                
                // جلب المواد المرتبطة بهذا الفصل فقط: إما courses.semester_id = هذا الفصل أو غير محدود (للتوافق)
                $courses_raw = $db->fetchAll(
                    "SELECT c.* 
                     FROM courses c
                     INNER JOIN student_courses sc ON c.id = sc.course_id AND sc.semester_id = ?
                     WHERE c.major_id = ? AND (c.semester_id = ? OR c.semester_id IS NULL)
                     GROUP BY c.id
                     ORDER BY c.code",
                    [$semester_id, $major_id, $semester_id]
                );
                // دمج المواد المكررة حسب الاسم العربي (عمود واحد لكل مادة) مع توحيد الاسم
                $by_name_ar = [];
                foreach ($courses_raw as $c) {
                    $name = trim($c['name_ar'] ?? '');
                    if ($name === '') continue;
                    $key = $normalize_name($name);
                    if (!isset($by_name_ar[$key])) {
                        $by_name_ar[$key] = ['course' => $c, 'course_ids' => []];
                    }
                    $by_name_ar[$key]['course_ids'][] = (int)$c['id'];
                }
                $courses = array_values(array_map(function ($x) { return $x['course']; }, $by_name_ar));
                $course_ids_by_name = [];
                foreach ($by_name_ar as $k => $x) {
                    $course_ids_by_name[$k] = $x['course_ids'];
                }
                $all_course_ids = [];
                foreach ($course_ids_by_name as $ids) {
                    $all_course_ids = array_merge($all_course_ids, $ids);
                }
                $all_course_ids = array_values(array_unique($all_course_ids));
                
                // جلب جميع الدرجات للطلاب والمواد في هذا الفصل
                if (!empty($students) && !empty($courses)) {
                    $student_ids = array_column($students, 'id');
                    $course_ids = $all_course_ids;
                    
                    if (!empty($student_ids) && !empty($course_ids)) {
                        $placeholders_students = implode(',', array_fill(0, count($student_ids), '?'));
                        $placeholders_courses = implode(',', array_fill(0, count($course_ids), '?'));
                        
                        $grades = $db->fetchAll(
                            "SELECT sc.student_id, sc.course_id, g.marks, g.letter_grade, g.points, sc.id as student_course_id
                             FROM student_courses sc
                             LEFT JOIN grades g ON sc.id = g.student_course_id
                             WHERE sc.student_id IN ($placeholders_students) 
                             AND sc.course_id IN ($placeholders_courses) 
                             AND sc.semester_id = ?",
                            array_merge($student_ids, $course_ids, [$semester_id])
                        );
                        
                        // بناء خريطة الدرجات وخريطة التسجيلات
                        foreach ($grades as $grade) {
                            $key = $grade['student_id'] . '-' . $grade['course_id'];
                            $grades_map[$key] = [
                                'marks' => $grade['marks'],
                                'letter_grade' => $grade['letter_grade'],
                                'points' => $grade['points'],
                                'student_course_id' => $grade['student_course_id']
                            ];
                            $registrations_map[$key] = true;
                        }
                    }
                }
        }
    }
}
?>
<!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>
        .grade-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .grade-table th,
        .grade-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        .grade-table th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .grade-table th:first-child,
        .grade-table td:first-child {
            position: sticky;
            left: 0;
            background-color: #fff !important;
            z-index: 5;
            min-width: 120px;
            max-width: 150px;
            white-space: nowrap;
            border: 1px solid #ddd;
        }
        .grade-table th:nth-child(2),
        .grade-table td:nth-child(2) {
            position: sticky;
            left: 150px;
            background-color: #fff !important;
            z-index: 5;
            min-width: 200px;
            max-width: 300px;
            white-space: nowrap;
            border: 1px solid #ddd;
            text-align: right !important;
            padding: 8px !important;
            display: table-cell !important;
        }
        .grade-table th:first-child {
            background-color: #4CAF50 !important;
            color: white !important;
        }
        .grade-table th:nth-child(2) {
            background-color: #4CAF50 !important;
            color: white !important;
        }
        .grade-input {
            width: 80px;
            padding: 5px;
            border: 2px solid #ddd;
            border-radius: 4px;
            text-align: center;
        }
        .grade-input:focus {
            border-color: #4CAF50;
            outline: none;
        }
        .student-info {
            font-weight: bold;
            background-color: #f5f5f5;
        }
        .actions-column {
            position: sticky;
            right: 0;
            background-color: #fff;
            z-index: 5;
            min-width: 150px;
        }
        .preview-badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            margin-right: 4px;
        }
        .preview-letter {
            background-color: #e3f2fd;
            color: #1976d2;
        }
        .preview-points {
            background-color: #f3e5f5;
            color: #7b1fa2;
        }
        .table-container {
            overflow-x: auto;
            max-width: 100%;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h2>تعديل درجات الطلاب حسب التخصص والفصل الدراسي</h2>
            <div style="margin-top: 10px;">
                <a href="dashboard.php" class="btn btn-secondary">العودة للوحة التحكم</a>
            </div>
        </div>
        
        <?php echo $message; ?>
        
        <!-- نموذج اختيار الخطوات المتتالية -->
        <div class="card" style="margin-bottom: 20px;">
            <div class="card-header">
                <h3>اختر المعايير لعرض الدرجات</h3>
            </div>
            <form method="GET" style="padding: 20px;">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">
                    <!-- الخطوة 1: الكلية -->
                    <div class="form-group">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">1. الكلية:</label>
                        <select name="college_id" id="college_id" required style="width: 100%; padding: 10px; font-size: 14px;" onchange="this.form.submit()">
                            <option value="">-- اختر الكلية --</option>
                            <?php foreach ($available_colleges as $c): ?>
                                <option value="<?php echo $c['id']; ?>" <?php echo ($college_id == $c['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($c['name_ar']); ?> (<?php echo htmlspecialchars($c['code']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- الخطوة 2: التخصص -->
                    <div class="form-group">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">2. التخصص:</label>
                        <select name="major_id" id="major_id" required style="width: 100%; padding: 10px; font-size: 14px;" <?php echo ($college_id <= 0) ? 'disabled' : ''; ?> onchange="this.form.submit()">
                            <option value="">-- اختر التخصص --</option>
                            <?php if ($college_id > 0): ?>
                                <?php foreach ($available_majors as $m): ?>
                                    <option value="<?php echo $m['id']; ?>" <?php echo ($major_id == $m['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($m['name_ar']); ?> (<?php echo htmlspecialchars($m['code']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <?php if ($college_id > 0): ?>
                            <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
                        <?php endif; ?>
                    </div>
                    
                    <!-- الخطوة 3: الفصل الدراسي -->
                    <div class="form-group">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">3. الفصل الدراسي:</label>
                        <select name="semester_number" id="semester_number" required style="width: 100%; padding: 10px; font-size: 14px;" <?php echo ($major_id <= 0) ? 'disabled' : ''; ?> onchange="this.form.submit()">
                            <option value="">-- اختر رقم الفصل --</option>
                            <?php if ($major_id > 0): ?>
                                <?php foreach ($available_semester_numbers as $sem_num): ?>
                                    <option value="<?php echo $sem_num; ?>" <?php echo ($semester_number == $sem_num) ? 'selected' : ''; ?>>
                                        <?php echo getSemesterName($sem_num); ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <?php if ($college_id > 0): ?>
                            <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
                        <?php endif; ?>
                        <?php if ($major_id > 0): ?>
                            <input type="hidden" name="major_id" value="<?php echo $major_id; ?>">
                        <?php endif; ?>
                    </div>
                    
                    <!-- الخطوة 4: السنة الدراسية -->
                    <div class="form-group">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">4. السنة الدراسية:</label>
                        <select name="academic_year" id="academic_year" required style="width: 100%; padding: 10px; font-size: 14px;" <?php echo ($semester_number <= 0) ? 'disabled' : ''; ?> onchange="this.form.submit()">
                            <option value="">-- اختر السنة الدراسية --</option>
                            <?php if ($semester_number > 0 && !empty($available_academic_years)): ?>
                                <?php foreach ($available_academic_years as $year): ?>
                                    <option value="<?php echo htmlspecialchars($year); ?>" <?php echo ($academic_year == $year) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($year); ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <?php if ($college_id > 0): ?>
                            <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
                        <?php endif; ?>
                        <?php if ($major_id > 0): ?>
                            <input type="hidden" name="major_id" value="<?php echo $major_id; ?>">
                        <?php endif; ?>
                        <?php if ($semester_number > 0): ?>
                            <input type="hidden" name="semester_number" value="<?php echo $semester_number; ?>">
                        <?php endif; ?>
                    </div>
                </div>
                
                <div style="margin-top: 20px; text-align: center;">
                    <?php if ($college_id > 0 && $major_id > 0 && $semester_number > 0 && $academic_year !== ''): ?>
                        <button type="button" onclick="window.location.reload()" class="btn btn-primary" style="padding: 10px 30px;">
                            🔄 تحديث الصفحة
                        </button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
        
        <?php if ($major && $semester): ?>
        <!-- جدول الدرجات -->
        <div class="card">
            <div class="card-header" style="background-color: #4CAF50; color: white;">
                <h3>
                    درجات الطلاب - 
                    <?php echo htmlspecialchars($major['name_ar']); ?> - 
                    <?php echo getSemesterName($semester['semester_number']); ?> - 
                    <?php echo htmlspecialchars($semester['academic_year']); ?>
                </h3>
            </div>
            
            <?php if (empty($students)): ?>
                <div style="padding: 20px;">
                    <div class="alert alert-warning">
                        <strong>⚠ لا يوجد طلاب في هذا التخصص</strong>
                    </div>
                </div>
            <?php elseif (empty($courses)): ?>
                <div style="padding: 20px;">
                    <div class="alert alert-warning">
                        <strong>⚠ لا توجد مواد مسجلة للطلاب في هذا الفصل الدراسي</strong>
                        <p>يجب تسجيل الطلاب في المواد أولاً قبل إدخال الدرجات.</p>
                    </div>
                    <!-- عرض جدول الطلاب فقط بدون مواد -->
                    <div class="table-container">
                        <table class="grade-table">
                            <thead>
                                <tr>
                                    <th class="student-info" style="background-color: #4CAF50 !important; color: white !important; padding: 8px !important; border: 1px solid #ddd;">
                                        الرقم الجامعي
                                    </th>
                                    <th class="student-info" style="background-color: #4CAF50 !important; color: white !important; padding: 8px !important; border: 1px solid #ddd; text-align: right !important;">
                                        اسم الطالب
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students as $student): ?>
                                    <tr>
                                        <td class="student-info" style="background-color: #f5f5f5 !important; font-weight: bold;">
                                            <?php echo htmlspecialchars($student['student_number'] ?? 'غير محدد'); ?>
                                        </td>
                                        <td class="student-info" style="background-color: #f5f5f5 !important; font-weight: bold; text-align: right;">
                                            <?php echo htmlspecialchars($student['full_name_ar'] ?? 'غير محدد'); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php else: ?>
            <form method="POST" id="gradesForm" onsubmit="return validateAndSubmit();">
                <input type="hidden" name="action" value="save_grades">
                <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
                <input type="hidden" name="major_id" value="<?php echo $major_id; ?>">
                <input type="hidden" name="semester_number" value="<?php echo $semester_number; ?>">
                <input type="hidden" name="academic_year" value="<?php echo htmlspecialchars($academic_year); ?>">
                <?php if ($semester && isset($semester['id'])): ?>
                    <input type="hidden" name="semester_id" value="<?php echo $semester['id']; ?>">
                <?php endif; ?>
                
                <div class="table-container">
                    <table class="grade-table">
                        <thead>
                            <tr>
                                <th class="student-info" style="background-color: #4CAF50 !important; color: white !important; padding: 8px !important; border: 1px solid #ddd;">
                                    الرقم الجامعي
                                </th>
                                <th class="student-info" style="background-color: #4CAF50 !important; color: white !important; padding: 8px !important; border: 1px solid #ddd; text-align: right !important;">
                                    اسم الطالب
                                </th>
                                <?php foreach ($courses as $course): ?>
                                    <th style="min-width: 150px;" title="<?php echo htmlspecialchars($course['name_ar']); ?>">
                                        <?php echo htmlspecialchars($course['name_ar']); ?>
                                    </th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($students)): ?>
                                <tr>
                                    <td colspan="<?php echo 2 + count($courses); ?>" style="text-align: center; padding: 20px;">
                                        <strong>لا يوجد طلاب في هذا التخصص</strong>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($students as $student): ?>
                                    <tr>
                                        <td class="student-info" style="background-color: #f5f5f5 !important; font-weight: bold;">
                                            <?php echo htmlspecialchars($student['student_number'] ?? 'غير محدد'); ?>
                                        </td>
                                        <td class="student-info" style="background-color: #f5f5f5 !important; font-weight: bold; text-align: right;">
                                            <?php echo htmlspecialchars($student['full_name_ar'] ?? 'غير محدد'); ?>
                                        </td>
                                        <?php foreach ($courses as $course): ?>
                                            <?php 
                                                $name_key = $normalize_name($course['name_ar'] ?? '');
                                                $ids_for_name = isset($course_ids_by_name[$name_key]) ? $course_ids_by_name[$name_key] : [(int)$course['id']];
                                                $key = null;
                                                foreach ($ids_for_name as $cid) {
                                                    $k = (int)$student['id'] . '-' . (int)$cid;
                                                    if (isset($registrations_map[$k])) { $key = $k; break; }
                                                }
                                                $is_registered = ($key !== null);
                                                $grade_data = $key ? (isset($grades_map[$key]) ? $grades_map[$key] : null) : null;
                                                $current_marks = $grade_data ? ($grade_data['marks'] ?? '') : '';
                                                $current_letter = $grade_data ? ($grade_data['letter_grade'] ?? '') : '';
                                                $current_points = $grade_data ? ($grade_data['points'] ?? '') : '';
                                            ?>
                                            <td>
                                                <?php if ($is_registered && $key): ?>
                                                    <input type="text" 
                                                           name="grades[<?php echo htmlspecialchars($key); ?>]" 
                                                           value="<?php echo htmlspecialchars((string)$current_marks); ?>" 
                                                           class="grade-input"
                                                           placeholder="درجة أو: بد، غ، غش"
                                                           data-student="<?php echo (int)$student['id']; ?>"
                                                           data-course="<?php echo (int)(explode('-', $key)[1]); ?>"
                                                           onchange="updateGradePreview(this)">
                                                    <div class="preview-info" id="preview-<?php echo htmlspecialchars($key); ?>" style="margin-top: 4px;">
                                                        <?php if ($current_letter || $current_points): ?>
                                                            <span class="preview-badge preview-letter"><?php echo htmlspecialchars($current_letter); ?></span>
                                                            <?php if ($current_points !== null && $current_points !== ''): ?>
                                                                <span class="preview-badge preview-points"><?php echo number_format((float)$current_points, 2); ?></span>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <span style="color: #999; font-style: italic;">لم يتم التسجيل</span>
                                                <?php endif; ?>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <div style="margin-top: 20px; padding: 15px; background: #e3f2fd; border-radius: 5px;">
                    <p><strong>عدد الطلاب:</strong> <?php echo count($students); ?> طالب</p>
                    <p><strong>عدد المواد:</strong> <?php echo count($courses); ?> مادة</p>
                    <?php if (!empty($students)): ?>
                        <p style="margin-top: 10px; font-size: 12px; color: #666;">
                            <strong>مثال على بيانات الطالب الأول:</strong> 
                            <?php $first_student = $students[0]; ?>
                            الرقم: <?php echo htmlspecialchars($first_student['student_number'] ?? 'غير موجود'); ?> | 
                            الاسم: <?php echo htmlspecialchars($first_student['full_name_ar'] ?? 'غير موجود'); ?>
                        </p>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($courses) && !empty($students)): ?>
                <div style="margin-top: 20px; text-align: center;">
                    <button type="submit" class="btn btn-success" style="padding: 12px 30px; font-size: 16px;">
                        ✅ حفظ جميع التعديلات
                    </button>
                    <button type="button" onclick="clearAllGrades()" class="btn btn-secondary" style="padding: 12px 30px; font-size: 16px;">
                        🗑️ مسح جميع الدرجات
                    </button>
                </div>
                <?php endif; ?>
            </form>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
    
    <script>
        // جدول التقديرات
        // التقدير الجديد: A (80-100), B (70-79), C (60-69), D (50-59), F (<50)
        const gradeScale = {
            'A': { min: 80, max: 100, points: 4.0 },
            'B': { min: 70, max: 79, points: 3.0 },
            'C': { min: 60, max: 69, points: 2.0 },
            'D': { min: 50, max: 59, points: 1.0 },
            'F': { min: 0, max: 49, points: 0.0 }
        };
        
        // معالجة الدرجات النصية
        const textGrades = {
            'بد': { letter: 'بد', points: null },
            'ب': { letter: 'بد', points: null },
            'غ': { letter: 'غياب', points: 0.0 },
            'غياب': { letter: 'غياب', points: 0.0 },
            'غش': { letter: 'غش', points: 0.0 },
            'غشش': { letter: 'غش', points: 0.0 }
        };
        
        function calculateGrade(marks) {
            const input = marks.trim();
            
            // إذا كانت نصية
            if (textGrades[input]) {
                return textGrades[input];
            }
            
            // إذا كانت رقمية
            if (isNaN(input) || input === '') {
                return { letter: '', points: null };
            }
            
            const num = parseFloat(input);
            if (num >= 80 && num <= 100) return { letter: 'A', points: 4.0 };
            if (num >= 70 && num <= 79) return { letter: 'B', points: 3.0 };
            if (num >= 60 && num <= 69) return { letter: 'C', points: 2.0 };
            if (num >= 50 && num <= 59) return { letter: 'D', points: 1.0 };
            return { letter: 'F', points: 0.0 };
        }
        
        function updateGradePreview(input) {
            const marks = input.value;
            const grade = calculateGrade(marks);
            const key = input.name.match(/\[(.*?)\]/)[1];
            const previewDiv = document.getElementById('preview-' + key);
            
            if (previewDiv) {
                let html = '';
                if (grade.letter) {
                    html += '<span class="preview-badge preview-letter">' + grade.letter + '</span>';
                }
                if (grade.points !== null) {
                    html += '<span class="preview-badge preview-points">' + grade.points.toFixed(2) + '</span>';
                }
                previewDiv.innerHTML = html;
            }
        }
        
        function clearAllGrades() {
            if (confirm('هل تريد مسح جميع الدرجات المدخلة؟')) {
                document.querySelectorAll('.grade-input').forEach(input => {
                    input.value = '';
                    updateGradePreview(input);
                });
            }
        }
        
        // التحقق من النموذج قبل الإرسال
        function validateAndSubmit() {
            const form = document.getElementById('gradesForm');
            const inputs = form.querySelectorAll('.grade-input');
            let hasValue = false;
            
            inputs.forEach(input => {
                if (input.value.trim() !== '') {
                    hasValue = true;
                }
            });
            
            if (!hasValue) {
                alert('⚠️ يرجى إدخال درجة واحدة على الأقل قبل الحفظ');
                return false;
            }
            
            return confirm('هل تريد حفظ جميع التعديلات؟');
        }
        
        // تحديث معاينة التقديرات عند تحميل الصفحة
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.grade-input').forEach(input => {
                updateGradePreview(input);
            });
        });
    </script>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>

