<?php
// subject_grades.php - Insert grades/degrees for enrolled subjects
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// Start session only once at the beginning
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// التحقق من CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// وظائف الأمان
function validateInt($input, $default = 0) {
    if (isset($input) && ctype_digit((string)$input)) {
        return (int)$input;
    }
    return $default;
}

function validateString($input, $default = '') {
    if (isset($input) && is_string($input)) {
        $clean = trim($input);
        $clean = strip_tags($clean);
        $clean = htmlspecialchars($clean, ENT_QUOTES, 'UTF-8');
        return $clean;
    }
    return $default;
}

function validateFloat($input, $default = 0.0) {
    if (isset($input) && is_numeric($input)) {
        return (float)$input;
    }
    return $default;
}

$committeeId = validateInt($_SESSION['committee_id'] ?? 0);
$committeeName = validateString($_SESSION['committee_name'] ?? '');
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? validateInt($_SESSION['committee_college_id']) : null;

// Initialize variables
$errors = [];
$success_message = '';
$action = validateString($_GET['action'] ?? '');

// Get grades from database with prepared statement
$grades_for_js = [];
$grades_result = $mysqli1->query("SELECT id, grade, weight FROM tblgrade ORDER BY weight DESC, grade");
if ($grades_result) {
    while ($row = $grades_result->fetch_assoc()) {
        $grades_for_js[] = $row;
    }
}

// Create JavaScript array for grade ranges
$grades_js = [];
foreach ($grades_for_js as $grade) {
    $grades_js[] = [
        'id' => (int)$grade['id'],
        'grade' => validateString($grade['grade']),
        'weight' => (float)$grade['weight']
    ];
}
$grades_json = json_encode($grades_js, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

// Get ALL grades from tblgrade for dropdown
$grades = [];
$grades_result = $mysqli1->query("SELECT id, grade FROM tblgrade ORDER BY weight DESC, grade");
if ($grades_result) {
    while ($row = $grades_result->fetch_assoc()) {
        $grades[] = [
            'id' => (int)$row['id'],
            'grade' => validateString($row['grade'])
        ];
    }
}

// Get filter data for dropdowns
$colleges = [];
$result = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $colleges[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

$programs = [];
$result = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $programs[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

$all_sections = [];
$result = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $all_sections[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name']),
            'parent' => (int)$row['parent']
        ];
    }
}

$batches = [];
$result = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $batches[] = [
            'id' => (int)$row['id'],
            'value' => validateString($row['value'])
        ];
    }
}

$semesters = [];
$result = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $semesters[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

// If committee has restricted access, filter colleges
if (!$canAll && $scopeCollege !== null) {
    $colleges = array_filter($colleges, function($college) use ($scopeCollege) {
        return $college['id'] == $scopeCollege;
    });
}

// Handle form submission for filtering
$college_id = validateInt($_GET['college_id'] ?? 0);
$section_id = validateInt($_GET['section_id'] ?? 0);
$program_id = validateInt($_GET['program_id'] ?? 0);
$specialization_id = validateInt($_GET['specialization_id'] ?? 0);
$batch_id = validateInt($_GET['batch_id'] ?? 0);
$semester_id = validateInt($_GET['semester_id'] ?? 0);
$subject_filter = validateString($_GET['subject_filter'] ?? '');

// التحقق من الصلاحيات
if (!$canAll && $scopeCollege !== null && $college_id > 0 && $scopeCollege != $college_id) {
    die('غير مصرح لك بالوصول لهذه البيانات');
}

// Get selected specialization name if any
$selected_specialization_name = '';
if ($specialization_id > 0) {
    $specStmt = $mysqli1->prepare("SELECT specialization_name_ar FROM specializations WHERE specialization_id = ? AND deleted_at IS NULL");
    if ($specStmt) {
        $specStmt->bind_param('i', $specialization_id);
        $specStmt->execute();
        $specResult = $specStmt->get_result();
        if ($specRow = $specResult->fetch_assoc()) {
            $selected_specialization_name = validateString($specRow['specialization_name_ar']);
        }
        $specStmt->close();
    }
}

// Handle grade submission with degree
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_grades'])) {
        // التحقق من CSRF token
        if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
            $errors[] = 'طلب غير مصرح به';
        }
        
        $semester_id = validateInt($_POST['semester_id'] ?? 0);
        $batch_id = validateInt($_POST['batch_id'] ?? 0);
        $student_grades = $_POST['grades'] ?? [];
        
        // Validate
        if (empty($semester_id)) {
            $errors[] = 'الرجاء اختيار الفصل الدراسي';
        }
        
        if (empty($batch_id)) {
            $errors[] = 'الرجاء اختيار الدفعة';
        }
        
        if (empty($student_grades) || !is_array($student_grades)) {
            $errors[] = 'لم يتم إرسال أي تقديرات';
        }
        
        if (empty($errors)) {
            $success_count = 0;
            $error_count = 0;
            $skipped_count = 0;
            $no_change_count = 0;
            $degree_count = 0;
            
            // Begin transaction
            $mysqli1->begin_transaction();
            
            try {
                foreach ($student_grades as $student_id => $subjects) {
                    $student_id = validateString($student_id);
                    if (empty($student_id) || !is_array($subjects)) {
                        $skipped_count++;
                        continue;
                    }
                    
                    foreach ($subjects as $subjectcode => $grade_data) {
                        $subjectcode = validateString($subjectcode);
                        if (empty($subjectcode) || !is_array($grade_data)) {
                            $skipped_count++;
                            continue;
                        }
                        
                        $grade_id = isset($grade_data['grade_id']) ? validateInt($grade_data['grade_id']) : 0;
                        $degree = isset($grade_data['degree']) && $grade_data['degree'] !== '' ? validateFloat($grade_data['degree']) : null;
                        
                        // التحقق من وجود السجل
                        $checkStmt = $mysqli1->prepare("
                            SELECT id, grade, grade_id, weight, degree 
                            FROM studentsubjects 
                            WHERE student_id = ? 
                            AND subjectcode = ? 
                            AND semester_id = ? 
                            AND batch_id = ?
                        ");
                        
                        if (!$checkStmt) {
                            $error_count++;
                            continue;
                        }
                        
                        $checkStmt->bind_param('ssii', $student_id, $subjectcode, $semester_id, $batch_id);
                        $checkStmt->execute();
                        $checkResult = $checkStmt->get_result();
                        $checkRow = $checkResult->fetch_assoc();
                        
                        if ($checkRow) {
                            // السجل موجود - تحديث البيانات
                            $final_grade = $checkRow['grade'];
                            $final_grade_id = $checkRow['grade_id'];
                            $final_weight = $checkRow['weight'];
                            $final_degree = $degree !== null ? $degree : $checkRow['degree'];
                            $needs_update = false;
                            
                            // إذا تم اختيار تقدير جديد
                            if ($grade_id > 0 && $grade_id != $checkRow['grade_id']) {
                                $gradeQuery = $mysqli1->prepare("SELECT grade, weight FROM tblgrade WHERE id = ?");
                                if ($gradeQuery) {
                                    $gradeQuery->bind_param('i', $grade_id);
                                    $gradeQuery->execute();
                                    $gradeResult = $gradeQuery->get_result();
                                    if ($gradeRow = $gradeResult->fetch_assoc()) {
                                        $final_grade = validateString($gradeRow['grade']);
                                        $final_weight = (float)$gradeRow['weight'];
                                        $final_grade_id = $grade_id;
                                        $needs_update = true;
                                    }
                                    $gradeQuery->close();
                                }
                            }
                            
                            // إذا تم تغيير الدرجة
                            if ($degree !== null && $degree != $checkRow['degree']) {
                                $needs_update = true;
                            }
                            
                            if ($needs_update) {
                                $updateStmt = $mysqli1->prepare("
                                    UPDATE studentsubjects 
                                    SET grade = ?, grade_id = ?, weight = ?, degree = ?, updated_at = NOW()
                                    WHERE student_id = ? 
                                    AND subjectcode = ? 
                                    AND semester_id = ? 
                                    AND batch_id = ?
                                ");
                                
                                if ($updateStmt) {
                                    $updateStmt->bind_param(
                                        'siddssii',
                                        $final_grade,
                                        $final_grade_id,
                                        $final_weight,
                                        $final_degree,
                                        $student_id,
                                        $subjectcode,
                                        $semester_id,
                                        $batch_id
                                    );
                                    
                                    if ($updateStmt->execute()) {
                                        if ($mysqli1->affected_rows > 0) {
                                            $success_count++;
                                            if ($degree !== null && $degree != $checkRow['degree']) $degree_count++;
                                        } else {
                                            $error_count++;
                                        }
                                    } else {
                                        $error_count++;
                                    }
                                    $updateStmt->close();
                                } else {
                                    $error_count++;
                                }
                            } else {
                                $no_change_count++;
                            }
                        } else {
                            // إدراج سجل جديد
                            $final_grade = null;
                            $final_grade_id = null;
                            $final_weight = null;
                            $final_degree = $degree;
                            $needs_insert = false;
                            
                            if ($grade_id > 0 || ($degree !== null && $degree > 0)) {
                                $needs_insert = true;
                                
                                if ($grade_id > 0) {
                                    $gradeQuery = $mysqli1->prepare("SELECT grade, weight FROM tblgrade WHERE id = ?");
                                    if ($gradeQuery) {
                                        $gradeQuery->bind_param('i', $grade_id);
                                        $gradeQuery->execute();
                                        $gradeResult = $gradeQuery->get_result();
                                        if ($gradeRow = $gradeResult->fetch_assoc()) {
                                            $final_grade = validateString($gradeRow['grade']);
                                            $final_weight = (float)$gradeRow['weight'];
                                            $final_grade_id = $grade_id;
                                        }
                                        $gradeQuery->close();
                                    }
                                }
                            }
                            
                            if ($needs_insert) {
                                $insertStmt = $mysqli1->prepare("
                                    INSERT INTO studentsubjects 
                                    (student_id, subjectcode, semester_id, batch_id, grade, weight, grade_id, degree, created_at, updated_at)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                                ");
                                
                                if ($insertStmt) {
                                    $insertStmt->bind_param(
                                        'ssiisdis',
                                        $student_id,
                                        $subjectcode,
                                        $semester_id,
                                        $batch_id,
                                        $final_grade,
                                        $final_weight,
                                        $final_grade_id,
                                        $final_degree
                                    );
                                    
                                    if ($insertStmt->execute()) {
                                        $success_count++;
                                        if ($degree !== null && $degree > 0) $degree_count++;
                                    } else {
                                        $error_count++;
                                    }
                                    $insertStmt->close();
                                } else {
                                    $error_count++;
                                }
                            } else {
                                $skipped_count++;
                            }
                        }
                        $checkStmt->close();
                    }
                }
                
                $mysqli1->commit();
                
                if ($success_count > 0) {
                    $success_message = "✅ تم حفظ $success_count تقدير بنجاح";
                    if ($degree_count > 0) {
                        $success_message .= " ($degree_count درجات)";
                    }
                    if ($error_count > 0) {
                        $success_message .= " ❌ فشل في $error_count حالة";
                    }
                    if ($no_change_count > 0) {
                        $success_message .= " ⏭️ تخطي $no_change_count تقدير (لم يتغير)";
                    }
                    if ($skipped_count > 0) {
                        $success_message .= " 📝 تم تخطي $skipped_count حقل فارغ";
                    }
                } else {
                    if ($skipped_count > 0 && $no_change_count == 0) {
                        $errors[] = "⚠️ لم يتم إدخال أي درجات أو تقديرات جديدة - جميع الحقول فارغة";
                    } elseif ($no_change_count > 0 && $success_count == 0) {
                        $errors[] = "ℹ️ لم يتم حفظ أي تغييرات - جميع البيانات موجودة ولم تتغير";
                    } else {
                        $errors[] = "❌ لم يتم حفظ أي بيانات";
                    }
                }
                
            } catch (Exception $e) {
                $mysqli1->rollback();
                error_log("Grade save error: " . $e->getMessage());
                $errors[] = "❌ حدث خطأ أثناء الحفظ: " . $e->getMessage();
            }
        }
    }
}

// Get enrolled students and subjects based on selection
$enrolled_data = [];
$subject_list = [];
$all_subjects = [];

if ($college_id && $section_id && $program_id && $batch_id && $semester_id) {
    // Build the base query for subjects
    $subjectQuery = "
        SELECT DISTINCT 
            ss.subjectcode,
            sub.subjectnamea,
            sub.credit_hours
        FROM studentsubjects ss
        JOIN students s ON ss.student_id = s.student_id
        JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        WHERE s.college_id = ? 
        AND s.section_id = ? 
        AND s.program_id = ? 
        AND s.batch_id = ?
        AND ss.batch_id = ? 
        AND ss.semester_id = ?
        AND s.deleted_at IS NULL
        AND sub.deleted_at IS NULL
    ";
    
    $types = "iiiiii";
    $params = [$college_id, $section_id, $program_id, $batch_id, $batch_id, $semester_id];
    
    if ($specialization_id > 0) {
        $subjectQuery .= " AND s.specialization_id = ?";
        $types .= "i";
        $params[] = $specialization_id;
    }
    
    if (!empty($subject_filter)) {
        $subjectQuery .= " AND ss.subjectcode = ?";
        $types .= "s";
        $params[] = $subject_filter;
    }
    
    $subjectQuery .= " ORDER BY sub.subjectcode";
    
    $subjectStmt = $mysqli1->prepare($subjectQuery);
    if ($subjectStmt) {
        $subjectStmt->bind_param($types, ...$params);
        $subjectStmt->execute();
        $subjectResult = $subjectStmt->get_result();
        
        while ($row = $subjectResult->fetch_assoc()) {
            $subject_list[$row['subjectcode']] = [
                'name' => validateString($row['subjectnamea']),
                'hours' => (float)$row['credit_hours']
            ];
            $all_subjects[] = $row['subjectcode'];
        }
        $subjectStmt->close();
    }
    
    // Build the main query for enrolled students with their grades
    $enrolledQuery = "
        SELECT 
            s.student_id,
            s.student_name,
            ss.subjectcode,
            ss.grade,
            ss.grade_id,
            ss.weight,
            ss.degree,
            sub.subjectnamea,
            sub.credit_hours,
            g.grade as grade_name
        FROM studentsubjects ss
        JOIN students s ON ss.student_id = s.student_id
        JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE s.college_id = ? 
        AND s.section_id = ? 
        AND s.program_id = ? 
        AND s.batch_id = ?
        AND ss.batch_id = ?
        AND ss.semester_id = ?
        AND s.deleted_at IS NULL
        AND sub.deleted_at IS NULL
    ";
    
    $types = "iiiiii";
    $params = [$college_id, $section_id, $program_id, $batch_id, $batch_id, $semester_id];
    
    if ($specialization_id > 0) {
        $enrolledQuery .= " AND s.specialization_id = ?";
        $types .= "i";
        $params[] = $specialization_id;
    }
    
    if (!empty($subject_filter)) {
        $enrolledQuery .= " AND ss.subjectcode = ?";
        $types .= "s";
        $params[] = $subject_filter;
    }
    
    $enrolledQuery .= " ORDER BY s.student_name, ss.subjectcode";
    
    $enrolledStmt = $mysqli1->prepare($enrolledQuery);
    if ($enrolledStmt) {
        $enrolledStmt->bind_param($types, ...$params);
        $enrolledStmt->execute();
        $enrolledResult = $enrolledStmt->get_result();
        
        // Organize data by student and subject
        $students_data = [];
        while ($row = $enrolledResult->fetch_assoc()) {
            $student_id = $row['student_id'];
            $subjectcode = $row['subjectcode'];
            
            if (!isset($students_data[$student_id])) {
                $students_data[$student_id] = [
                    'student_id' => validateString($student_id),
                    'student_name' => validateString($row['student_name']),
                    'subjects' => []
                ];
            }
            
            $students_data[$student_id]['subjects'][$subjectcode] = [
                'grade' => $row['grade'] ? validateString($row['grade']) : null,
                'grade_id' => $row['grade_id'] ? (int)$row['grade_id'] : null,
                'weight' => $row['weight'] ? (float)$row['weight'] : null,
                'degree' => $row['degree'] ? (float)$row['degree'] : null
            ];
        }
        
        // Build the complete table data
     // Build the complete table data - عرض المقررات المسجلة فقط لكل طالب
$row_number = 1;
$enrolled_data = [];

foreach ($students_data as $student) {
    // الحصول على المقررات المسجلة لهذا الطالب فقط
    $student_subjects = $student['subjects'];
    
    foreach ($student_subjects as $subjectcode => $grade_info) {
        $subject_info = $subject_list[$subjectcode] ?? ['name' => $subjectcode, 'hours' => 0];
        
        $enrolled_data[] = [
            'row_number' => $row_number,
            'student_id' => $student['student_id'],
            'student_name' => $student['student_name'],
            'subjectcode' => $subjectcode,
            'subjectname' => $subject_info['name'],
            'credit_hours' => $subject_info['hours'],
            'current_degree' => $grade_info['degree'] ?? null,
            'current_grade' => $grade_info['grade'] ?? null,
            'current_grade_id' => $grade_info['grade_id'] ?? null,
            'current_weight' => $grade_info['weight'] ?? null
        ];
    }
    $row_number++;
}
    }
}

include 'header.php';
?>

<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --header-gradient: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
        --success-gradient: linear-gradient(135deg, #00b09b, #96c93d);
        --danger-gradient: linear-gradient(135deg, #fc6767, #ec008c);
    }

    body {
        font-family: 'Cairo', sans-serif;
        background-color: #f8fafc;
        min-height: 100vh;
    }

    .main-wrapper {
        padding: 30px 20px;
    }

    .page-header {
        background: var(--header-gradient);
        border-radius: 30px;
        padding: 30px 40px;
        margin-bottom: 30px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        position: relative;
        overflow: hidden;
        color: white;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
        animation: rotate 20s linear infinite;
    }

    @keyframes rotate {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    .page-header h1 {
        font-size: 2rem;
        font-weight: 800;
        margin: 0;
        text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        position: relative;
        z-index: 2;
    }

    .page-header p {
        font-size: 0.9rem;
        margin-top: 5px;
        opacity: 0.9;
        position: relative;
        z-index: 2;
    }

    .btn-gradient {
        background: var(--success-gradient);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 176, 155, 0.4);
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-gradient:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6);
        color: white;
    }

    .btn-outline-gradient {
        background: transparent;
        border: 2px solid rgba(255, 255, 255, 0.5);
        color: white;
        padding: 10px 25px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-outline-gradient:hover {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        transform: translateY(-2px);
    }

    .btn-reset {
        background: linear-gradient(135deg, #6b7280, #4b5563);
        border: none;
        color: white;
        padding: 10px 20px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .filter-card {
        background: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
    }

    .form-label {
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 8px;
        font-size: 0.9rem;
    }

    .required-field::after {
        content: " *";
        color: #e53e3e;
    }

    .form-control, .form-select {
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        padding: 8px 12px;
        font-size: 0.9rem;
        transition: all 0.3s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        outline: none;
    }

    .filter-card .form-select,
    .subject-filter-section .form-select {
        background-position: left 0.75rem center !important;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e") !important;
        padding-right: 0.75rem !important;
        padding-left: 2rem !important;
        text-align: right;
    }

    .content-card {
        background: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        border-right: 5px solid #667eea;
    }

    .content-card-header {
        border-bottom: 2px solid #e2e8f0;
        padding-bottom: 15px;
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;
    }

    .content-card-header h5 {
        font-weight: 700;
        color: #2d3748;
        margin: 0;
    }

    .content-card-header h5 i {
        color: #667eea;
        margin-left: 10px;
    }

    .stat-card {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        border-radius: 20px;
        padding: 20px 15px;
        text-align: center;
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        height: 100%;
    }

    .stat-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
    }

    .stat-icon {
        font-size: 1.8rem;
        margin-bottom: 8px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .stat-number {
        font-size: 1.8rem;
        font-weight: 800;
        color: #2d3748;
        margin-bottom: 5px;
    }

    .stat-label {
        color: #718096;
        font-weight: 600;
        font-size: 0.85rem;
    }

    .scrollable-area {
        max-height: 550px;
        overflow-y: auto;
        overflow-x: auto;
        border-radius: 20px;
        border: 1px solid #e2e8f0;
        background: white;
    }

    .scrollable-area::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .scrollable-area::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }

    .scrollable-area::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #667eea, #764ba2);
        border-radius: 10px;
    }

    .grades-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.85rem;
    }

    .grades-table th {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        font-weight: 700;
        color: #2d3748;
        padding: 12px 8px;
        text-align: center;
        position: sticky;
        top: 0;
        z-index: 10;
        border-bottom: 2px solid #e2e8f0;
        white-space: nowrap;
    }

    .grades-table td {
        padding: 8px;
        border-bottom: 1px solid #e2e8f0;
        text-align: center;
        vertical-align: middle;
    }

    .grades-table tr:hover {
        background-color: #f8fafc;
    }

    .grades-table tr.active-row {
        background-color: #e0f2fe;
        border-right: 3px solid #667eea;
    }

    .grade-select {
        width: 100px;
        padding: 6px 8px;
        border: 2px solid #e2e8f0;
        border-radius: 10px;
        font-size: 0.8rem;
        text-align: center;
        transition: all 0.3s ease;
        background-color: white;
    }

    .grade-select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        outline: none;
    }

    .degree-input {
        width: 70px;
        padding: 6px 8px;
        border: 2px solid #e2e8f0;
        border-radius: 10px;
        font-size: 0.8rem;
        text-align: center;
        transition: all 0.3s ease;
    }

    .degree-input:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        outline: none;
    }

    .grade-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        min-width: 35px;
    }

    .grade-pass { 
        background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
        color: #1e4620;
    }

    .grade-fail { 
        background: linear-gradient(135deg, #fc6767, #ec008c);
        color: white;
    }

    .info-card {
        background: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        border-right: 5px solid #667eea;
    }

    .subject-filter-section {
        background: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        border-right: 5px solid #667eea;
    }

    .loading-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        justify-content: center;
        align-items: center;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #2596be;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .active-filters {
        background: #f8fafc;
        border-radius: 15px;
        padding: 15px;
        margin-top: 15px;
        border: 1px solid #e2e8f0;
    }

    .filter-badge {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        padding: 5px 12px;
        border-radius: 50px;
        font-size: 0.8rem;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .alert {
        border-radius: 20px;
        border: none;
        padding: 15px 25px;
        font-weight: 600;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        animation: slideIn 0.5s ease;
        margin-bottom: 25px;
    }

    @keyframes slideIn {
        from { transform: translateY(-20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }

    .alert-success {
        background: linear-gradient(135deg, #dcfce7, #bbf7d0);
        color: #166534;
        border-right: 4px solid #22c55e;
    }

    .alert-danger {
        background: linear-gradient(135deg, #fee2e2, #fecaca);
        color: #991b1b;
        border-right: 4px solid #ef4444;
    }

    .me-1 { margin-left: 0.25rem !important; margin-right: 0 !important; }
    .me-2 { margin-left: 0.5rem !important; margin-right: 0 !important; }
    .ms-1 { margin-right: 0.25rem !important; margin-left: 0 !important; }
    .ms-2 { margin-right: 0.5rem !important; margin-left: 0 !important; }

    .row-number {
        font-weight: 700;
        color: #667eea;
        background: #f0f4ff;
        border-radius: 50%;
        width: 28px;
        height: 28px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.8rem;
    }

    kbd {
        background: linear-gradient(135deg, #2d3748, #1a202c);
        border-radius: 5px;
        padding: 3px 8px;
        font-size: 0.7rem;
        font-weight: 700;
        color: white;
        box-shadow: 0 1px 2px rgba(0,0,0,0.2);
        display: inline-block;
        min-width: 30px;
        text-align: center;
    }

    .keyboard-shortcuts {
        background: #f8fafc;
        border-radius: 16px;
        padding: 12px 20px;
        margin-top: 15px;
        border: 1px solid #e2e8f0;
    }

    .shortcut-item {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        margin-left: 20px;
        margin-bottom: 8px;
    }

    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }
        .page-header h1 {
            font-size: 1.5rem;
        }
        .grades-table {
            font-size: 0.75rem;
        }
        .grade-select, .degree-input {
            width: 65px;
            font-size: 0.7rem;
            padding: 4px;
        }
        kbd {
            padding: 2px 5px;
            font-size: 0.6rem;
        }
    }
</style>

<div class="main-wrapper" dir="rtl">
    <div class="container-fluid px-4">
        <!-- Page Header -->
        <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
            <div>
                <h1 class="mb-2" style="color: white;">
    <i class="fas fa-chart-bar ms-3"></i>
    إدخال الدرجات والتقديرات
</h1>
                <p class="mb-0">
                    <i class="fas fa-layer-group ms-2"></i>
                    إدخال وتعديل درجات وتقديرات الطلاب للمواد المسجلة
                </p>
            </div>
            <div class="d-flex gap-3 mt-3 mt-md-0">
                <a href="subject_enrollment.php" class="btn-outline-gradient">
                    <i class="fas fa-user-graduate ms-2"></i>
                    تسجيل المقررات
                </a>
                <a href="admin_dashboard.php" class="btn-outline-gradient">
                    <i class="fas fa-arrow-right ms-2"></i>
                    العودة للوحة التحكم
                </a>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle ms-2"></i>
                <?php foreach ($errors as $error): ?>
                    <div><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endforeach; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle ms-2"></i>
                <?= htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="filter-card">
            <form method="get" class="row g-3" id="filterForm">
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-university ms-1"></i> الكلية
                    </label>
                    <select class="form-select" name="college_id" id="college_id" required
                            <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                        <option value="">اختر الكلية</option>
                        <?php foreach ($colleges as $college): ?>
                            <option value="<?= (int)$college['id'] ?>" 
                                <?= ($college_id == $college['id']) || (!$canAll && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$canAll && $scopeCollege !== null): ?>
                        <input type="hidden" name="college_id" value="<?= (int)$scopeCollege ?>">
                    <?php endif; ?>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-layer-group ms-1"></i> القسم
                    </label>
                    <select class="form-select" name="section_id" id="section_id" required>
                        <option value="">اختر القسم</option>
                    </select>
                    <small class="text-muted" id="sectionStatus"></small>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-graduation-cap ms-1"></i> البرنامج
                    </label>
                    <select class="form-select" name="program_id" id="program_id" required>
                        <option value="">اختر البرنامج</option>
                    </select>
                    <small class="text-muted" id="programStatus"></small>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">
                        <i class="fas fa-tag ms-1"></i> التخصص
                    </label>
                    <select class="form-select" name="specialization_id" id="specialization_id">
                        <option value="">جميع التخصصات</option>
                    </select>
                    <small class="text-muted" id="specializationStatus"></small>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-users ms-1"></i> الدفعة
                    </label>
                    <select class="form-select" name="batch_id" id="batch_id" required>
                        <option value="">اختر الدفعة</option>
                        <?php foreach ($batches as $batch): ?>
                            <option value="<?= (int)$batch['id'] ?>" 
                                <?= ($batch_id == $batch['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-calendar-alt ms-1"></i> الفصل الدراسي
                    </label>
                    <select class="form-select" name="semester_id" id="semester_id" required>
                        <option value="">اختر الفصل</option>
                        <?php foreach ($semesters as $semester): ?>
                            <option value="<?= (int)$semester['id'] ?>" 
                                <?= ($semester_id == $semester['id']) ? 'selected' : '' ?>>
                                الفصل <?= htmlspecialchars($semester['name'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-12">
                    <div class="d-flex gap-3 justify-content-end">
                        <a href="subject_grades.php" class="btn-reset">
                            <i class="fas fa-redo-alt ms-2"></i> إعادة تعيين
                        </a>
                        <button type="submit" class="btn-gradient">
                            <i class="fas fa-search ms-2"></i> بحث
                        </button>
                    </div>
                </div>
            </form>
            
            <!-- Active Filters Display -->
            <?php if ($college_id || $section_id || $program_id || $specialization_id || $batch_id || $semester_id): ?>
                <div class="active-filters mt-3">
                    <div class="d-flex align-items-center flex-wrap gap-2">
                        <span class="fw-bold text-secondary ms-2">
                            <i class="fas fa-filter ms-1"></i> الفلاتر النشطة:
                        </span>
                        <?php if ($college_id && !empty($colleges)): 
                            $collegeName = '';
                            foreach($colleges as $c) {
                                if($c['id'] == $college_id) {
                                    $collegeName = $c['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="filter-badge"><i class="fas fa-university"></i> <?= htmlspecialchars($collegeName, ENT_QUOTES, 'UTF-8') ?></span>
                        <?php endif; ?>
                        
                        <?php if ($section_id): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #28a745, #20c997);">
                                <i class="fas fa-layer-group"></i> القسم المحدد
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($program_id): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #ff6b6b, #ee5253);">
                                <i class="fas fa-graduation-cap"></i> البرنامج المحدد
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($specialization_id && $selected_specialization_name): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #f39c12, #e67e22);">
                                <i class="fas fa-tag"></i> <?= htmlspecialchars($selected_specialization_name, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($batch_id): 
                            $batchValue = '';
                            foreach($batches as $b) {
                                if($b['id'] == $batch_id) {
                                    $batchValue = $b['value'];
                                    break;
                                }
                            }
                        ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #9b59b6, #8e44ad);">
                                <i class="fas fa-users"></i> دفعة <?= htmlspecialchars($batchValue, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($semester_id): 
                            $semesterName = '';
                            foreach($semesters as $s) {
                                if($s['id'] == $semester_id) {
                                    $semesterName = $s['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #2596be, #2596be);">
                                <i class="fas fa-calendar-alt"></i> الفصل <?= htmlspecialchars($semesterName, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($college_id && $section_id && $program_id && $batch_id && $semester_id): ?>
            
            <!-- Subject Filter Section -->
            <?php if (!empty($subject_list)): ?>
                <div class="subject-filter-section">
                    <form method="get" class="row g-3 align-items-end">
                        <input type="hidden" name="college_id" value="<?= (int)$college_id ?>">
                        <input type="hidden" name="section_id" value="<?= (int)$section_id ?>">
                        <input type="hidden" name="program_id" value="<?= (int)$program_id ?>">
                        <input type="hidden" name="specialization_id" value="<?= (int)$specialization_id ?>">
                        <input type="hidden" name="batch_id" value="<?= (int)$batch_id ?>">
                        <input type="hidden" name="semester_id" value="<?= (int)$semester_id ?>">
                        
                        <div class="col-md-8">
                            <label class="form-label">
                                <i class="fas fa-filter ms-2"></i> تصفية حسب المادة
                            </label>
                            <select class="form-select" name="subject_filter" onchange="this.form.submit()">
                                <option value="">جميع المقررات (<?= count($subject_list) ?>)</option>
                                <?php foreach ($subject_list as $code => $info): ?>
                                    <option value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" <?= ($subject_filter == $code) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?> - <?= htmlspecialchars($info['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="d-flex gap-3">
                                <?php if (!empty($subject_filter)): ?>
                                    <a href="?<?= http_build_query([
                                        'college_id' => $college_id,
                                        'section_id' => $section_id,
                                        'program_id' => $program_id,
                                        'specialization_id' => $specialization_id,
                                        'batch_id' => $batch_id,
                                        'semester_id' => $semester_id
                                    ]) ?>" class="btn-reset w-50 text-center">
                                        <i class="fas fa-times ms-2"></i> إلغاء التصفية
                                    </a>
                                <?php endif; ?>
                                <button type="submit" class="btn-gradient w-50">
                                    <i class="fas fa-search ms-2"></i> تطبيق
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            <?php endif; ?>
            
            <!-- Grade Entry Form -->
            <form method="POST" action="" id="gradesForm">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                <input type="hidden" name="semester_id" value="<?= (int)$semester_id ?>">
                <input type="hidden" name="batch_id" value="<?= (int)$batch_id ?>">
                
                <?php if (!empty($enrolled_data)): ?>
                    <!-- Statistics Cards -->
                    <div class="row g-3 mb-4">
                        <div class="col-md-3 col-sm-6">
                            <div class="stat-card">
                                <div class="stat-icon"><i class="fas fa-users"></i></div>
                                <div class="stat-number"><?= count(array_unique(array_column($enrolled_data, 'student_id'))) ?></div>
                                <div class="stat-label">عدد الطلاب</div>
                            </div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="stat-card">
                                <div class="stat-icon"><i class="fas fa-book"></i></div>
                                <div class="stat-number"><?= count($subject_list) ?></div>
                                <div class="stat-label">عدد المقررات</div>
                            </div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="stat-card">
                                <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
                                <div class="stat-number"><?= count($enrolled_data) ?></div>
                                <div class="stat-label">إجمالي التسجيلات</div>
                            </div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="stat-card">
                                <div class="stat-icon"><i class="fas fa-percent"></i></div>
                                <div class="stat-number"><?php 
                                    $avg_degree = 0;
                                    $count_with_degree = 0;
                                    foreach ($enrolled_data as $d) {
                                        if ($d['current_degree'] > 0) {
                                            $avg_degree += $d['current_degree'];
                                            $count_with_degree++;
                                        }
                                    }
                                    $avg_degree = $count_with_degree > 0 ? round($avg_degree / $count_with_degree, 1) : 0;
                                    echo $avg_degree;
                                ?>%</div>
                                <div class="stat-label">متوسط الدرجات</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Information Card with Instructions -->
                    <div class="info-card">
                        <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                            <div>
                                <h5 class="fw-bold mb-3">
                                    <i class="fas fa-info-circle text-primary ms-2"></i>
                                    تعليمات إدخال الدرجات والتقديرات
                                </h5>
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <div class="d-flex align-items-center gap-2 mb-2">
                                            <span class="badge rounded-circle p-2" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">1</span>
                                            <span><strong>الدرجة:</strong> أدخل درجة من 0 إلى 100</span>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="d-flex align-items-center gap-2 mb-2">
                                            <span class="badge rounded-circle p-2" style="background: linear-gradient(135deg, #28a745, #20c997); color: white;">2</span>
                                            <span><strong>التقدير:</strong> اختر من القائمة المنسدلة</span>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="d-flex align-items-center gap-2 mb-2">
                                            <span class="badge rounded-circle p-2" style="background: linear-gradient(135deg, #ffc107, #ff9800); color: white;">⌨️</span>
                                            <span><strong>اختصارات لوحة المفاتيح:</strong></span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="keyboard-shortcuts">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="shortcut-item"><kbd>↑</kbd> <span>→ التنقل إلى الصف السابق</span></div>
                                            <div class="shortcut-item"><kbd>↓</kbd> <span>→ التنقل إلى الصف التالي</span></div>
                                            <div class="shortcut-item"><kbd>Enter</kbd> <span>→ الانتقال إلى الحقل التالي (الدرجة → التقدير → الصف التالي)</span></div>
                                            <div class="shortcut-item"><kbd>Tab</kbd> <span>→ التنقل بين الحقول (الدرجة ↔ التقدير)</span></div>
                                            <div class="shortcut-item"><kbd>Shift+Tab</kbd> <span>→ العودة للحقل السابق</span></div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="shortcut-item"><kbd>A</kbd> <span>→ A </span></div></br>
                                            <div class="shortcut-item"><kbd>B</kbd> <span>→ B (مرة أخرى → B+)</span></div>
                                            <div class="shortcut-item"><kbd>C</kbd> <span>→ C (مرة أخرى → C+)</span></div>
                                            <div class="shortcut-item"><kbd>D</kbd> <span>→ D (مرة أخرى → D+)</span></div>
                                            <div class="shortcut-item"><kbd>F</kbd> <span>→ F (مرة أخرى → F*, مرة ثالثة → F**)</span></div>
                                            <div class="shortcut-item"><kbd>Ctrl+S</kbd> <span>→ حفظ التقديرات</span></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="text-start">
                                <button type="submit" name="save_grades" class="btn-gradient" style="padding: 12px 35px;">
                                    <i class="fas fa-save ms-2"></i> حفظ الدرجات والتقديرات
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Grades Table -->
                    <div class="content-card">
                        <div class="content-card-header">
                            <h5>
                                <i class="fas fa-table ms-2"></i>
                                قائمة الدرجات والتقديرات
                                <?php if ($specialization_id > 0 && $selected_specialization_name): ?>
                                    <span class="filter-badge ms-2" style="background: linear-gradient(135deg, #f39c12, #e67e22);">
                                        <i class="fas fa-tag"></i> <?= htmlspecialchars($selected_specialization_name, ENT_QUOTES, 'UTF-8') ?>
                                    </span>
                                <?php endif; ?>
                            </h5>
                            <div class="d-flex align-items-center gap-3">
                                <span class="badge" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 6px 15px; border-radius: 50px;">
                                    <i class="fas fa-users ms-1"></i> <?= count(array_unique(array_column($enrolled_data, 'student_id'))) ?> طالب
                                </span>
                                <span class="badge" style="background: linear-gradient(135deg, #28a745, #20c997); color: white; padding: 6px 15px; border-radius: 50px;">
                                    <i class="fas fa-book ms-1"></i> <?= count($subject_list) ?> مادة
                                </span>
                            </div>
                        </div>
                        
                        <div class="scrollable-area">
                            <table class="grades-table" id="gradesTable">
                                <thead>
                                    <tr>
                                        <th width="50">#</th>
                                        <th width="130">رقم الطالب</th>
                                        <th>اسم الطالب</th>
                                        <th width="100">كود المادة</th>
                                        <th>اسم المادة</th>
                                        <th width="60">الساعات</th>
                                        <th width="100">الدرجة الحالية</th>
                                        <th width="100">الدرجة</th>
                                        <th width="100">التقدير الحالي</th>
                                        <th width="130">التقدير</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($enrolled_data as $index => $row): ?>
                                        <tr class="grade-row" data-row-index="<?= $index ?>">
                                            <td><span class="row-number"><?= $row['row_number'] ?></span></div>
                                            <td><code><?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?></code></div>
                                            <td><div style="text-align: right;"><?= htmlspecialchars($row['student_name'], ENT_QUOTES, 'UTF-8') ?></div></div>
                                            <td><strong><?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?></strong></div>
                                            <td><div style="text-align: right;"><?= htmlspecialchars($row['subjectname'], ENT_QUOTES, 'UTF-8') ?></div></div>
                                            <td><?= (int)$row['credit_hours'] ?></div>
                                            
                                            <!-- Current Degree -->
                                            <td>
                                                <?php if ($row['current_degree'] !== null && $row['current_degree'] > 0): ?>
                                                    <span class="badge bg-info rounded-pill"><?= number_format($row['current_degree'], 1) ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted">--</span>
                                                <?php endif; ?>
                                             </div>
                                            
                                            <!-- Degree Input -->
                                            <td>
                                                <input type="number" 
                                                       name="grades[<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>][<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>][degree]" 
                                                       class="degree-input degree-field"
                                                       data-row="<?= $index ?>"
                                                       value="<?= htmlspecialchars($row['current_degree'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                       step="0.5"
                                                       min="0"
                                                       max="100"
                                                       placeholder="الدرجة">
                                             </div>
                                            
                                            <!-- Current Grade -->
                                            <td>
                                                <?php if ($row['current_grade']): ?>
                                                    <?php $grade_class = ($row['current_weight'] > 0) ? 'grade-pass' : 'grade-fail'; ?>
                                                    <span class="grade-badge <?= $grade_class ?>"><?= htmlspecialchars($row['current_grade'], ENT_QUOTES, 'UTF-8') ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted">--</span>
                                                <?php endif; ?>
                                             </div>
                                            
                                            <!-- Grade Select -->
                                            <td>
                                                <select name="grades[<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>][<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>][grade_id]" 
                                                        class="grade-select grade-field"
                                                        data-row="<?= $index ?>"
                                                        data-student="<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>"
                                                        data-subject="<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>">
                                                    <option value="">-- اختر --</option>
                                                    <?php foreach ($grades as $grade): ?>
                                                        <?php
                                                        $weight = 0;
                                                        foreach ($grades_js as $g) {
                                                            if ($g['id'] == $grade['id']) {
                                                                $weight = $g['weight'];
                                                                break;
                                                            }
                                                        }
                                                        ?>
                                                        <option value="<?= (int)$grade['id'] ?>" data-weight="<?= $weight ?>"
                                                            <?= ($row['current_grade_id'] == $grade['id']) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($grade['grade'], ENT_QUOTES, 'UTF-8') ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                             </div>
                                         </tr>
                                    <?php endforeach; ?>
                                </tbody>
                             </table>
                        </div>
                    </div>
                    
                    <!-- Save Button (Bottom) -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="content-card">
                                <div class="text-center">
                                    <button type="submit" name="save_grades" class="btn-gradient" style="padding: 12px 50px;">
                                        <i class="fas fa-save ms-2"></i> حفظ الدرجات والتقديرات
                                    </button>
                                    <div class="mt-2 text-muted small">
                                        <i class="fas fa-lightbulb ms-1"></i>
                                        سيتم حفظ الدرجات والتقديرات الجديدة فقط
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                <?php else: ?>
                    <div class="content-card">
                        <div class="text-center py-5">
                            <i class="fas fa-graduation-cap fa-4x text-muted mb-3 opacity-50"></i>
                            <h4 class="fw-bold mb-3">لا توجد مواد مسجلة</h4>
                            <p class="text-muted mb-4">
                                <?php if (!empty($subject_filter)): ?>
                                    لا توجد مواد مسجلة للطلاب بناءً على المادة المحددة
                                <?php elseif ($specialization_id > 0): ?>
                                    لا توجد مواد مسجلة للطلاب في هذا التخصص
                                <?php else: ?>
                                    لا توجد مواد مسجلة للطلاب بناءً على معايير الترشيح المختارة
                                <?php endif; ?>
                            </p>
                            <a href="subject_enrollment.php" class="btn-gradient">
                                <i class="fas fa-user-graduate ms-2"></i> الذهاب لتسجيل المقررات
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </form>
            
        <?php else: ?>
            <div class="content-card">
                <div class="text-center py-5">
                    <i class="fas fa-filter fa-4x text-muted mb-3 opacity-50"></i>
                    <h4 class="fw-bold mb-3">اختر معايير الترشيح</h4>
                    <p class="text-muted mb-4">الرجاء اختيار الكلية، القسم، البرنامج، الدفعة، والفصل الدراسي للبدء</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
    <div class="mt-2 text-white">جاري حفظ البيانات...</div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Grade mapping from database
const gradeRanges = <?= $grades_json ?>;

// DOM elements
let degreeFields = [];
let gradeFields = [];
let currentRow = 0;
let currentFieldType = 'degree'; // 'degree' or 'grade'
let totalRows = 0;

// Track last pressed key for F* and F** cycling
let lastFKeyPressTime = 0;
let fPressCount = 0;

// Find grade by ID
function findGradeById(gradeId) {
    return gradeRanges.find(g => g.id == gradeId);
}

// Find grade by letter
function findGradeByLetter(letter) {
    const sortedGrades = [...gradeRanges].sort((a, b) => b.weight - a.weight);
    
    if (letter === 'F*') return sortedGrades.find(g => g.grade === 'F*');
    if (letter === 'F**') return sortedGrades.find(g => g.grade === 'F**');
    
    if (letter.includes('+')) {
        const baseLetter = letter.replace('+', '');
        return sortedGrades.find(g => g.grade === letter) || sortedGrades.find(g => g.grade === baseLetter);
    }
    return sortedGrades.find(g => g.grade === letter);
}

// Highlight current row
function highlightRow(rowIndex) {
    $('.grade-row').removeClass('active-row');
    $(`.grade-row[data-row-index="${rowIndex}"]`).addClass('active-row');
    
    // Scroll into view if needed
    const activeRow = $(`.grade-row[data-row-index="${rowIndex}"]`);
    if (activeRow.length) {
        const scrollArea = $('.scrollable-area');
        const rowTop = activeRow.offset().top - scrollArea.offset().top + scrollArea.scrollTop();
        const rowBottom = rowTop + activeRow.outerHeight();
        const scrollTop = scrollArea.scrollTop();
        const scrollBottom = scrollTop + scrollArea.innerHeight();
        
        if (rowTop < scrollTop) {
            scrollArea.scrollTop(rowTop - 30);
        } else if (rowBottom > scrollBottom) {
            scrollArea.scrollTop(rowBottom - scrollArea.innerHeight() + 30);
        }
    }
}

// Focus on current field
function focusOnCurrentField() {
    if (currentFieldType === 'degree') {
        if (degreeFields[currentRow]) {
            degreeFields[currentRow].focus();
            highlightRow(currentRow);
        }
    } else {
        if (gradeFields[currentRow]) {
            gradeFields[currentRow].focus();
            highlightRow(currentRow);
        }
    }
}

// Move to next field (degree -> grade -> next row degree)
function moveToNextField() {
    if (currentFieldType === 'degree') {
        // Move to grade field in same row
        currentFieldType = 'grade';
        focusOnCurrentField();
    } else {
        // Move to next row's degree field
        if (currentRow + 1 < totalRows) {
            currentRow++;
            currentFieldType = 'degree';
            focusOnCurrentField();
        } else {
            // At last row, last field
            if (totalRows > 0) {
                showToast('success', '🎉 لقد وصلت إلى نهاية القائمة!');
            }
        }
    }
}

// Move to previous field
function moveToPrevField() {
    if (currentFieldType === 'grade') {
        // Move to degree field in same row
        currentFieldType = 'degree';
        focusOnCurrentField();
    } else {
        // Move to previous row's grade field
        if (currentRow - 1 >= 0) {
            currentRow--;
            currentFieldType = 'grade';
            focusOnCurrentField();
        }
    }
}

// Move to next row (same field type)
function moveToNextRow() {
    if (currentRow + 1 < totalRows) {
        currentRow++;
        focusOnCurrentField();
    }
}

// Move to previous row (same field type)
function moveToPrevRow() {
    if (currentRow - 1 >= 0) {
        currentRow--;
        focusOnCurrentField();
    }
}

// Show toast message
function showToast(type, message) {
    const toastHtml = `
        <div class="alert alert-${type} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3" style="z-index: 9999; min-width: 300px; text-align: center; box-shadow: 0 5px 20px rgba(0,0,0,0.2);">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-info-circle'} ms-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    $('body').append(toastHtml);
    setTimeout(() => $('.alert.position-fixed').fadeOut(500, function() { $(this).remove(); }), 2000);
}

// Update grade display styling
function updateGradeStyle(selectElement) {
    const gradeId = selectElement.value;
    if (gradeId) {
        const gradeObj = findGradeById(gradeId);
        if (gradeObj) {
            if (gradeObj.weight > 0) {
                selectElement.style.backgroundColor = '#d4edda';
                selectElement.style.color = '#155724';
            } else {
                selectElement.style.backgroundColor = '#f8d7da';
                selectElement.style.color = '#721c24';
            }
            selectElement.style.fontWeight = 'bold';
        }
    } else {
        selectElement.style.backgroundColor = '';
        selectElement.style.color = '';
        selectElement.style.fontWeight = '';
    }
}

// Handle keyboard input for grade selection
function handleGradeKeyPress(e) {
    const activeElement = e.target;
    const isDegreeField = activeElement.classList && activeElement.classList.contains('degree-field');
    const isGradeField = activeElement.classList && activeElement.classList.contains('grade-field');
    
    if (!isDegreeField && !isGradeField) return;
    
    const key = e.key;
    const now = Date.now();
    
    // Update current position
    const rowIndex = parseInt(activeElement.dataset.row);
    if (!isNaN(rowIndex)) {
        currentRow = rowIndex;
        currentFieldType = isDegreeField ? 'degree' : 'grade';
        highlightRow(currentRow);
    }
    
    // Reset F press count
    if (key !== 'f' && key !== 'F') {
        fPressCount = 0;
    } else if (now - lastFKeyPressTime > 500) {
        fPressCount = 0;
    }
    
    // Arrow keys - navigate between rows
    if (key === 'ArrowUp') {
        e.preventDefault();
        moveToPrevRow();
        return;
    }
    
    if (key === 'ArrowDown') {
        e.preventDefault();
        moveToNextRow();
        return;
    }
    
    // Tab key - navigate between fields in same row
    if (key === 'Tab') {
        if (e.shiftKey) {
            e.preventDefault();
            moveToPrevField();
        } else {
            e.preventDefault();
            moveToNextField();
        }
        return;
    }
    
    // Enter key - move to next field
    if (key === 'Enter') {
        e.preventDefault();
        moveToNextField();
        return;
    }
    
    // Letter keys for grade selection (only for grade fields)
    if (isGradeField && (/^[a-zA-Z]$/.test(key) || key === '+' || key === '*')) {
        e.preventDefault();
        
        const currentValue = activeElement.value;
        const currentGrade = currentValue ? findGradeById(currentValue) : null;
        let newGrade = null;
        
        // Handle F cycling
        if (key.toUpperCase() === 'F') {
            fPressCount++;
            lastFKeyPressTime = now;
            if (fPressCount === 1) newGrade = findGradeByLetter('F');
            else if (fPressCount === 2) newGrade = findGradeByLetter('F*');
            else if (fPressCount >= 3) {
                newGrade = findGradeByLetter('F**');
                fPressCount = 0;
            }
        } else if (key === '*') {
            fPressCount = 0;
            if (currentGrade && currentGrade.grade === 'F') newGrade = findGradeByLetter('F*');
            else if (currentGrade && currentGrade.grade === 'F*') newGrade = findGradeByLetter('F**');
        } else if (key === '+') {
            fPressCount = 0;
            if (currentGrade) {
                const baseLetter = currentGrade.grade.replace('+', '').replace('*', '');
                const plusGrade = findGradeByLetter(baseLetter + '+');
                if (plusGrade) newGrade = plusGrade;
            }
        } else {
            fPressCount = 0;
            const upperKey = key.toUpperCase();
            if (currentGrade && currentGrade.grade === upperKey) {
                newGrade = findGradeByLetter(upperKey + '+');
            } else {
                newGrade = findGradeByLetter(upperKey);
            }
        }
        
        if (newGrade) {
            activeElement.value = newGrade.id;
            const event = new Event('change', { bubbles: true });
            activeElement.dispatchEvent(event);
            updateGradeStyle(activeElement);
        }
    }
}

$(document).ready(function() {
    // Initialize fields
    degreeFields = $('.degree-field').toArray();
    gradeFields = $('.grade-field').toArray();
    totalRows = degreeFields.length;
    
    // Focus on first field
    if (totalRows > 0) {
        currentRow = 0;
        currentFieldType = 'degree';
        focusOnCurrentField();
    }
    
    // Add focus handlers
    $('.degree-field').on('focus', function() {
        const row = parseInt($(this).data('row'));
        if (!isNaN(row)) {
            currentRow = row;
            currentFieldType = 'degree';
            highlightRow(currentRow);
        }
    });
    
    $('.grade-field').on('focus', function() {
        const row = parseInt($(this).data('row'));
        if (!isNaN(row)) {
            currentRow = row;
            currentFieldType = 'grade';
            highlightRow(currentRow);
        }
    }).on('change', function() {
        updateGradeStyle(this);
    });
    
    // Initialize grade styles
    $('.grade-field').each(function() { updateGradeStyle(this); });
    
    // Keyboard event listener
    document.addEventListener('keydown', handleGradeKeyPress);
    
    // Load sections when college changes
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        if (collegeId) {
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(sections) {
                    let options = '<option value="">اختر القسم</option>';
                    sections.forEach(section => {
                        options += `<option value="${section.id}">${section.name}</option>`;
                    });
                    $('#section_id').html(options).prop('disabled', false);
                    $('#sectionStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + sections.length + ' قسم</span>');
                    loadPrograms(collegeId);
                },
                error: function() {
                    $('#section_id').html('<option value="">خطأ في تحميل الأقسام</option>').prop('disabled', false);
                    $('#sectionStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
                }
            });
        }
    });
    
    function loadPrograms(collegeId) {
        $.ajax({
            url: 'ajax/get_programs.php',
            method: 'GET',
            data: { college_id: collegeId },
            dataType: 'json',
            success: function(programs) {
                let options = '<option value="">اختر البرنامج</option>';
                programs.forEach(program => {
                    options += `<option value="${program.id}">${program.name}</option>`;
                });
                $('#program_id').html(options).prop('disabled', false);
                $('#programStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + programs.length + ' برنامج</span>');
            },
            error: function() {
                $('#program_id').html('<option value="">خطأ في تحميل البرامج</option>').prop('disabled', false);
                $('#programStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
            }
        });
    }
    
    function loadSpecializations() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { section_id: sectionId, program_id: programId },
                dataType: 'json',
                success: function(specializations) {
                    let options = '<option value="">جميع التخصصات</option>';
                    specializations.forEach(spec => {
                        options += `<option value="${spec.specialization_id}">${spec.specialization_name_ar}</option>`;
                    });
                    $('#specialization_id').html(options).prop('disabled', false);
                    $('#specializationStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + specializations.length + ' تخصص</span>');
                },
                error: function() {
                    $('#specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                    $('#specializationStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
                }
            });
        }
    }
    
    <?php if ($section_id && $program_id): ?> loadSpecializations(); <?php endif; ?>
    <?php if ($college_id): ?> $('#college_id').trigger('change'); <?php endif; ?>
    
    $('#section_id, #program_id').on('change', function() { loadSpecializations(); });
    
    // Form submission
    $('#gradesForm').on('submit', function(e) {
        let hasData = false;
        $('.degree-field').each(function() {
            if ($(this).val() !== '' && parseFloat($(this).val()) > 0) hasData = true;
        });
        $('.grade-field').each(function() {
            if ($(this).val() !== '') hasData = true;
        });
        
        if (!hasData) {
            if (!confirm('⚠️ لم تقم بإدخال أي درجات أو تقديرات جديدة. هل تريد الاستمرار؟')) {
                e.preventDefault();
                return false;
            }
        } else {
            if (!confirm('═══════════════════════════════════════\n📋 تأكيد حفظ البيانات\n═══════════════════════════════════════\n\n🤔 هل أنت متأكد من حفظ الدرجات والتقديرات؟')) {
                e.preventDefault();
                return false;
            }
        }
        $('#loadingOverlay').fadeIn(200);
        return true;
    });
    
    // Ctrl+S to save
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            $('button[name="save_grades"]').click();
        }
    });
    
    // Auto-hide alerts
    setTimeout(() => $('.alert').fadeOut(500, function() { $(this).remove(); }), 5000);
    
    console.log('✅ تم تحميل صفحة إدخال التقديرات بنجاح');
    console.log('✅ التنقل: ↑ ↓ للصفوف، Tab بين الحقول، Enter للحقل التالي');
});
</script>

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