<?php
// student_grades.php - Insert/Edit grades for a specific student with advanced search
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require 'functions/academic_stats.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;
}

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

// Initialize variables
$errors = [];
$success_message = '';
$info_message = '';

// Filter variables
$college_filter = validateString($_GET['college_id'] ?? '');
$section_filter = validateString($_GET['section_id'] ?? '');
$program_filter = validateString($_GET['program_id'] ?? '');
$specialization_filter = validateInt($_GET['specialization_id'] ?? 0);
$batch_filter = validateString($_GET['batch_id'] ?? '');
$semester_filter = validateInt($_GET['semester_id'] ?? 0);
$search_term = validateString($_GET['search_term'] ?? '');
$search_type = validateString($_GET['search_type'] ?? 'id');

// Selected student
$selected_student_id = validateString($_GET['student_id'] ?? '');
$selected_student = null;
$student_subjects = [];
$available_semesters = [];

// Get ALL grades from tblgrade for dropdown
$grades = [];
$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[] = [
            'id' => (int)$row['id'],
            'grade' => validateString($row['grade']),
            'weight' => (float)$row['weight']
        ];
        $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 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' => validateString($row['id']),
            'name' => validateString($row['name'])
        ];
    }
}

$sections = [];
$result = $mysqli1->query("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $sections[] = [
            'id' => validateString($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' => validateString($row['id']),
            'name' => validateString($row['name'])
        ];
    }
}

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

$all_semesters = [];
$result = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $all_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;
    });
    // Force college filter to committee's college
    if (empty($college_filter)) {
        $college_filter = $scopeCollege;
    }
}

// Get students list based on filters and search
$students_list = [];
if (!empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter) || !empty($search_term)) {
    
    $query = "
        SELECT 
            s.student_id,
            s.student_name,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            spec.specialization_name_ar as specialization_name,
            b.value as batch_name,
            (SELECT COUNT(*) FROM studentsubjects WHERE student_id = s.student_id) as subjects_count
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations spec ON s.specialization_id = spec.specialization_id AND spec.deleted_at IS NULL
        LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
        WHERE s.deleted_at IS NULL
    ";
    
    $conditions = [];
    $params = [];
    $types = "";
    
    // Add committee restriction
    if (!$canAll && $scopeCollege !== null) {
        $conditions[] = "s.college_id = ?";
        $params[] = $scopeCollege;
        $types .= "s";
    }
    
    // Add search term
    if (!empty($search_term)) {
        if ($search_type === 'id') {
            $conditions[] = "s.student_id LIKE ?";
            $params[] = "%$search_term%";
            $types .= "s";
        } else {
            $conditions[] = "s.student_name LIKE ?";
            $params[] = "%$search_term%";
            $types .= "s";
        }
    }
    
    // Add filters
    if (!empty($college_filter)) {
        $conditions[] = "s.college_id = ?";
        $params[] = $college_filter;
        $types .= "s";
    }
    
    if (!empty($section_filter)) {
        $conditions[] = "s.section_id = ?";
        $params[] = $section_filter;
        $types .= "s";
    }
    
    if (!empty($program_filter)) {
        $conditions[] = "s.program_id = ?";
        $params[] = $program_filter;
        $types .= "s";
    }
    
    if ($specialization_filter > 0) {
        $conditions[] = "s.specialization_id = ?";
        $params[] = $specialization_filter;
        $types .= "i";
    }
    
    if (!empty($batch_filter)) {
        $conditions[] = "s.batch_id = ?";
        $params[] = $batch_filter;
        $types .= "s";
    }
    
    if (!empty($conditions)) {
        $query .= " AND " . implode(" AND ", $conditions);
    }
    
    $query .= " ORDER BY s.student_name LIMIT 100";
    
    $stmt = $mysqli1->prepare($query);
    if ($stmt) {
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $students_list[] = [
                'student_id' => validateString($row['student_id']),
                'student_name' => validateString($row['student_name']),
                'college_name' => validateString($row['college_name'] ?? ''),
                'section_name' => validateString($row['section_name'] ?? ''),
                'program_name' => validateString($row['program_name'] ?? ''),
                'batch_name' => validateString($row['batch_name'] ?? ''),
                'subjects_count' => (int)$row['subjects_count']
            ];
        }
        $stmt->close();
    }
}

// If a specific student is selected
if (!empty($selected_student_id)) {
    // Get student basic info
    $studentQuery = "
        SELECT 
            s.id,
            s.student_id,
            s.student_name,
            s.email,
            s.phone_number,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            spec.specialization_name_ar as specialization_name,
            b.value as batch_name
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations spec ON s.specialization_id = spec.specialization_id AND spec.deleted_at IS NULL
        LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
        WHERE s.student_id = ? AND s.deleted_at IS NULL
        LIMIT 1
    ";
    
    $stmt = $mysqli1->prepare($studentQuery);
    if ($stmt) {
        $stmt->bind_param('s', $selected_student_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $selected_student = [
                'id' => (int)$row['id'],
                'student_id' => validateString($row['student_id']),
                'student_name' => validateString($row['student_name']),
                'email' => validateString($row['email'] ?? ''),
                'phone' => validateString($row['phone_number'] ?? ''),
                'college_id' => validateString($row['college_id'] ?? ''),
                'college_name' => validateString($row['college_name'] ?? ''),
                'section_id' => validateString($row['section_id'] ?? ''),
                'section_name' => validateString($row['section_name'] ?? ''),
                'program_id' => validateString($row['program_id'] ?? ''),
                'program_name' => validateString($row['program_name'] ?? ''),
                'specialization_id' => (int)$row['specialization_id'],
                'specialization_name' => validateString($row['specialization_name'] ?? ''),
                'batch_id' => validateString($row['batch_id'] ?? ''),
                'batch_name' => validateString($row['batch_name'] ?? '')
            ];
            
            // Check committee permissions
            if (!$canAll && $scopeCollege !== null && $row['college_id'] != $scopeCollege) {
                die('غير مصرح لك بالوصول لبيانات هذا الطالب');
            }
            
            // Get available semesters for this student
            $semesterQuery = "
                SELECT DISTINCT 
                    ss.semester_id,
                    s.name as semester_name
                FROM studentsubjects ss
                JOIN semesters s ON ss.semester_id = s.id AND s.deleted_at IS NULL
                WHERE ss.student_id = ?
                ORDER BY ss.semester_id DESC
            ";
            
            $semesterStmt = $mysqli1->prepare($semesterQuery);
            if ($semesterStmt) {
                $semesterStmt->bind_param('s', $selected_student_id);
                $semesterStmt->execute();
                $semesterResult = $semesterStmt->get_result();
                
                while ($row = $semesterResult->fetch_assoc()) {
                    $available_semesters[] = [
                        'id' => (int)$row['semester_id'],
                        'name' => validateString($row['semester_name'])
                    ];
                }
                $semesterStmt->close();
            }
        }
        $stmt->close();
    }
    
    // Get student subjects for selected semester
// Get student subjects for selected semester - FIXED for duplicates
// Get student subjects for selected semester - FIXED for duplicates with degree
if ($selected_student && $semester_filter > 0) {
    $subjectQuery = "
        SELECT DISTINCT
            ss.subjectcode,
            ss.semester_id,
            ss.batch_id,
            ss.grade,
            ss.grade_id,
            ss.weight,
            ss.degree,
            ss.created_at,
            ss.updated_at,
            sub.subjectnamea,
            sub.credit_hours,
            s.name as semester_name,
            b.value as batch_name,
            g.grade as grade_name
        FROM studentsubjects ss
        INNER JOIN subjects sub ON ss.subjectcode = sub.subjectcode AND sub.deleted_at IS NULL
        INNER JOIN semesters s ON ss.semester_id = s.id AND s.deleted_at IS NULL
        INNER JOIN batches b ON ss.batch_id = b.id AND b.deleted_at IS NULL
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE ss.student_id = ? 
        AND ss.semester_id = ?
        AND ss.deleted_at IS NULL
        GROUP BY ss.subjectcode, ss.semester_id
        ORDER BY sub.subjectcode
    ";
    
    $stmt = $mysqli1->prepare($subjectQuery);
    if ($stmt) {
        $stmt->bind_param('si', $selected_student_id, $semester_filter);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $student_subjects[] = [
                'subjectcode' => validateString($row['subjectcode']),
                'subjectnamea' => validateString($row['subjectnamea']),
                'credit_hours' => (float)$row['credit_hours'],
                'semester_id' => (int)$row['semester_id'],
                'semester_name' => validateString($row['semester_name']),
                'batch_id' => validateString($row['batch_id']),
                'batch_name' => validateString($row['batch_name']),
                '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'] !== null ? (float)$row['degree'] : null,  // Added degree
                'grade_name' => $row['grade_name'] ? validateString($row['grade_name']) : null,
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at']
            ];
        }
        $stmt->close();
    }
}
}

// Handle grade update
// Handle grade update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_grades'])) {
    // Verify CSRF token
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    }
    
    $student_id = validateString($_POST['student_id'] ?? '');
    $semester_id = validateInt($_POST['semester_id'] ?? 0);
    $grades_data = $_POST['grades'] ?? [];
    
    // Validate
    if (empty($student_id)) {
        $errors[] = 'رقم الطالب مطلوب';
    }
    
    if (empty($semester_id)) {
        $errors[] = 'الرجاء اختيار الفصل الدراسي';
    }
    
    if (empty($grades_data) || !is_array($grades_data)) {
        $errors[] = 'لم يتم إرسال أي تقديرات';
    }
    
    if (empty($errors)) {
        $success_count = 0;
        $error_count = 0;
        $skipped_count = 0;
        
        // Begin transaction
        $mysqli1->begin_transaction();
        
        try {
            foreach ($grades_data as $subjectcode => $grade_info) {
                $subjectcode = validateString($subjectcode);
                $grade_id = isset($grade_info['grade_id']) ? validateInt($grade_info['grade_id']) : 0;
                $degree = isset($grade_info['degree']) && $grade_info['degree'] !== '' ? (float)$grade_info['degree'] : null;
                
                // Skip if no grade selected and no degree entered (leave as is)
                if ($grade_id <= 0 && ($degree === null || $degree === '')) {
                    $skipped_count++;
                    continue;
                }
                
                $final_grade = null;
                $final_weight = null;
                $final_grade_id = null;
                
                // Get grade information if grade_id is selected
                if ($grade_id > 0) {
                    $gradeQuery = $mysqli1->prepare("SELECT grade, weight FROM tblgrade WHERE id = ?");
                    if (!$gradeQuery) {
                        $error_count++;
                        continue;
                    }
                    
                    $gradeQuery->bind_param('i', $grade_id);
                    $gradeQuery->execute();
                    $gradeResult = $gradeQuery->get_result();
                    
                    if ($gradeResult->num_rows == 0) {
                        $gradeQuery->close();
                        $skipped_count++;
                        continue;
                    }
                    
                    $gradeRow = $gradeResult->fetch_assoc();
                    $final_grade = validateString($gradeRow['grade']);
                    $final_weight = (float)$gradeRow['weight'];
                    $final_grade_id = $grade_id;
                    $gradeQuery->close();
                }
                
                // Check if record exists
                $checkStmt = $mysqli1->prepare("
                    SELECT id, grade_id, degree FROM studentsubjects 
                    WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
                ");
                
                if (!$checkStmt) {
                    $error_count++;
                    continue;
                }
                
                $checkStmt->bind_param('ssi', $student_id, $subjectcode, $semester_id);
                $checkStmt->execute();
                $checkResult = $checkStmt->get_result();
                
                // Check if there are changes
                $hasChanges = false;
                $existingDegree = null;
                
                if ($checkResult->num_rows > 0) {
                    $row = $checkResult->fetch_assoc();
                    $existingDegree = $row['degree'] !== null ? (float)$row['degree'] : null;
                    
                    if (($grade_id > 0 && $row['grade_id'] != $final_grade_id) || 
                        ($degree !== null && $existingDegree != $degree)) {
                        $hasChanges = true;
                    }
                } else {
                    $hasChanges = true; // New record
                }
                
                if ($hasChanges) {
                    if ($checkResult->num_rows > 0) {
                        // Update existing record
                        $updateFields = [];
                        $updateParams = [];
                        $updateTypes = "";
                        
                        if ($grade_id > 0) {
                            $updateFields[] = "grade = ?, grade_id = ?, weight = ?";
                            $updateParams[] = $final_grade;
                            $updateParams[] = $final_grade_id;
                            $updateParams[] = $final_weight;
                            $updateTypes .= "sdi";
                        }
                        
                        if ($degree !== null && $degree !== '') {
                            $updateFields[] = "degree = ?";
                            $updateParams[] = $degree;
                            $updateTypes .= "d";
                        }
                        
                        $updateFields[] = "updated_at = NOW()";
                        
                        $updateSql = "UPDATE studentsubjects SET " . implode(", ", $updateFields) . 
                                     " WHERE student_id = ? AND subjectcode = ? AND semester_id = ?";
                        $updateParams[] = $student_id;
                        $updateParams[] = $subjectcode;
                        $updateParams[] = $semester_id;
                        $updateTypes .= "ssi";
                        
                        $updateStmt = $mysqli1->prepare($updateSql);
                        if ($updateStmt) {
                            $updateStmt->bind_param($updateTypes, ...$updateParams);
                            if ($updateStmt->execute()) {
                                $success_count++;
                            } else {
                                $error_count++;
                            }
                            $updateStmt->close();
                        } else {
                            $error_count++;
                        }
                    } else {
                        // Insert new record
                        $batchQuery = $mysqli1->prepare("SELECT batch_id FROM students WHERE student_id = ?");
                        $batchQuery->bind_param('s', $student_id);
                        $batchQuery->execute();
                        $batchResult = $batchQuery->get_result();
                        $batchRow = $batchResult->fetch_assoc();
                        $batch_id = $batchRow['batch_id'] ?? '';
                        $batchQuery->close();
                        
                        $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(
                                'ssissdid',
                                $student_id,
                                $subjectcode,
                                $semester_id,
                                $batch_id,
                                $final_grade,
                                $final_weight,
                                $final_grade_id,
                                $degree
                            );
                            
                            if ($insertStmt->execute()) {
                                $success_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 ($error_count > 0) {
                    $success_message .= " (فشل في $error_count حالة)";
                }
                if ($skipped_count > 0) {
                    $success_message .= " (تم تخطي $skipped_count مادة - لم تتغير)";
                }
                
                // Refresh the page to show updated grades
                echo "<meta http-equiv='refresh' content='1;url=?student_id=" . urlencode($student_id) . "&semester_id=$semester_id&college_id=" . urlencode($college_filter) . "&section_id=" . urlencode($section_filter) . "&program_id=" . urlencode($program_filter) . "&specialization_id=$specialization_filter&batch_id=" . urlencode($batch_filter) . "&search_term=" . urlencode($search_term) . "&search_type=$search_type'>";
            } else {
                if ($skipped_count > 0) {
                    $errors[] = "لم يتم تحديث أي مواد - جميع البيانات بدون تغيير";
                } else {
                    $errors[] = "لم يتم تحديث أي مواد";
                }
            }
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            error_log("Grade update error: " . $e->getMessage());
            $errors[] = "حدث خطأ أثناء تحديث التقديرات";
        }
    }
}
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, #1e3c72, #2a5298);
        --info-gradient: linear-gradient(135deg, #667eea, #764ba2);
        --search-gradient: linear-gradient(135deg, #667eea 0%, #2a5298 100%);
    }

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

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

    .search-header {
        background: var(--search-gradient);
        border-radius: 30px;
        padding: 40px;
        margin-bottom: 30px;
        box-shadow: 0 20px 60px rgba(240, 147, 251, 0.3);
        position: relative;
        overflow: hidden;
        color: white;
    }

    .search-header::before {
        content: '\f002';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        position: absolute;
        bottom: -20px;
        left: -20px;
        font-size: 200px;
        opacity: 0.1;
        color: white;
        transform: rotate(-10deg);
    }

    .search-header h1 {
        font-size: 2.5rem;
        font-weight: 800;
        margin-bottom: 10px;
        text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
    }

    .search-header p {
        font-size: 1.1rem;
        opacity: 0.95;
        margin-bottom: 0;
    }

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

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

    .students-list-box {
        max-height: 400px;
        overflow-y: auto;
        border: 2px solid #e2e8f0;
        border-radius: 20px;
        padding: 10px;
    }

    .students-list-box::-webkit-scrollbar {
        width: 8px;
    }

    .students-list-box::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }

    .students-list-box::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #667eea, #2a5298);
        border-radius: 10px;
    }

    .student-item {
        padding: 12px 15px;
        margin-bottom: 5px;
        background: #f8fafc;
        border-radius: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
        border: 2px solid transparent;
    }

    .student-item:hover {
        background: linear-gradient(135deg, #667eea, #2a5298);
        color: white;
        transform: translateX(-5px);
    }

    .student-item:hover .student-item-id,
    .student-item:hover .student-item-name,
    .student-item:hover .student-item-info {
        color: white;
    }

    .student-item.selected {
        background: linear-gradient(135deg, #667eea, #2a5298);
        color: white;
        border-color: #2a5298;
    }

    .student-item.selected .student-item-id,
    .student-item.selected .student-item-name,
    .student-item.selected .student-item-info {
        color: white;
    }

    .student-item-id {
        font-size: 0.85rem;
        color: #718096;
        font-family: monospace;
    }

    .student-item-name {
        font-weight: 600;
        color: #2d3748;
    }

    .student-item-info {
        font-size: 0.8rem;
        color: #718096;
    }

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

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

    .form-control:focus, .form-select:focus {
        border-color: #2a5298;
        box-shadow: 0 0 0 4px rgba(245, 87, 108, 0.1);
        outline: none;
    }

    .btn-search {
        background: linear-gradient(135deg, #667eea, #2a5298);
        border: none;
        color: white;
        padding: 12px 35px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(245, 87, 108, 0.4);
    }

    .btn-search:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(245, 87, 108, 0.6);
        color: white;
    }

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

    .btn-reset:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 10px rgba(75, 85, 99, 0.4);
        color: white;
    }

    .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;
    }

    .selected-student-header {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        position: relative;
        overflow: hidden;
    }

    .selected-student-header::before {
        content: '\f007';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        position: absolute;
        bottom: -20px;
        left: -20px;
        font-size: 150px;
        opacity: 0.1;
        color: white;
        transform: rotate(-5deg);
    }

    .semester-filter-card {
        background: white;
        border-radius: 30px;
        padding: 20px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        border-right: 5px solid #2a5298;
    }

    .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;
    }

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

    .stat-card {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        border-radius: 25px;
        padding: 25px 20px;
        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(-5px);
        box-shadow: 0 15px 30px rgba(102, 126, 234, 0.2);
    }

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

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

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

    .grades-table {
        font-size: 0.95rem;
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
    }

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

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

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

    .grade-select {
        width: 120px;
        padding: 8px 12px;
        border: 2px solid #e2e8f0;
        border-radius: 15px;
        font-size: 0.9rem;
        text-align: center;
        transition: all 0.3s ease;
    }

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

    .grade-badge {
        display: inline-block;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 600;
    }

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

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

    .semester-badge {
        background: linear-gradient(135deg, #6c757d, #495057);
        color: white;
        padding: 8px 15px;
        border-radius: 50px;
        font-size: 0.9rem;
        font-weight: 600;
        display: inline-block;
    }

    .batch-badge {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 600;
    }

    .date-badge {
        background: linear-gradient(135deg, #ff6b6b, #ee5253);
        color: white;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.8rem;
        font-weight: 600;
    }

    .badge-filter {
        background: #edf2f7;
        color: #4a5568;
        padding: 8px 15px;
        border-radius: 50px;
        font-size: 0.9rem;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .badge-filter.active {
        background: linear-gradient(135deg, #667eea, #2a5298);
        color: white;
    }

    .no-results {
        text-align: center;
        padding: 40px 20px;
        background: #f8fafc;
        border-radius: 30px;
    }

    .no-results i {
        font-size: 3rem;
        color: #cbd5e0;
        margin-bottom: 15px;
    }

    .students-count {
        background: linear-gradient(135deg, #667eea, #2a5298);
        color: white;
        padding: 5px 15px;
        border-radius: 50px;
        font-size: 0.9rem;
        font-weight: 600;
    }

    .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;
        backdrop-filter: blur(5px);
    }

    .loading-spinner {
        width: 60px;
        height: 60px;
        border: 6px solid #f3f3f3;
        border-top: 6px solid #2a5298;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

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

    .search-section {
        background: linear-gradient(135deg, #667eea, #2a5298);
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 20px;
        color: white;
    }

    .search-section .form-label {
        color: white;
    }

    .search-section .form-control,
    .search-section .form-select {
        background: rgba(255, 255, 255, 0.9);
        border: none;
    }

    @media (max-width: 768px) {
        .search-header {
            padding: 25px;
        }
        .search-header h1 {
            font-size: 1.8rem;
        }
        .grades-table {
            font-size: 0.85rem;
        }
        .grade-select {
            width: 100px;
        }
    }
    
    /* تغيير اتجاه أسهم القوائم المنسدلة إلى اليسار */
.filter-card .form-select,

.semester-filter-card .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;
}

/* تعديل اتجاه النص داخل القوائم المنسدلة */
.filter-card .form-select option,
.search-section .form-select option {
    text-align: right;
}
</style>

<div class="main-wrapper" dir="rtl">
    <div class="container-fluid px-4">
        <!-- Search Header -->
        <div class="search-header">
            <div class="row align-items-center">
                <div class="col-lg-8">
                    <h1>
                        <i class="fas fa-search ms-3"></i>
                        إدارة تقديرات الطلاب
                    </h1>
                    <p>يمكنك البحث بالرقم الجامعي أو الاسم، أو استخدام الفلاتر لعرض قائمة الطلاب</p>
                </div>
                <div class="col-lg-4 text-lg-start text-center mt-3 mt-lg-0">
                    <a href="subject_grades.php" class="btn btn-light rounded-pill px-4 py-2">
                        <i class="fas fa-chart-bar ms-2"></i>
                        إدخال تقديرات (حسب المادة)
                    </a>
                </div>
            </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; ?>

        <!-- Search and Filters Form -->
        <form method="get" action="" id="filterForm">
            <!-- Quick Search Section -->
            <div class="search-section">
                <div class="row g-3 align-items-center">
                    <div class="col-md-2">
                        <label class="form-label">بحث بـ</label>
                        <select class="form-select" name="search_type" id="search_type">
                            <option value="id" <?= $search_type === 'id' ? 'selected' : '' ?>>الرقم الجامعي</option>
                            <option value="name" <?= $search_type === 'name' ? 'selected' : '' ?>>الاسم</option>
                        </select>
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">كلمة البحث</label>
                        <input type="text" 
                               class="form-control" 
                               name="search_term" 
                               id="search_term"
                               value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="أدخل الرقم الجامعي أو اسم الطالب...">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-light w-100 rounded-pill">
                            <i class="fas fa-search ms-2"></i>
                            بحث
                        </button>
                    </div>
                </div>
            </div>

            <!-- Advanced Filters -->
            <div class="filter-card">
                <h6 class="fw-bold mb-3">
                    <i class="fas fa-filter ms-2" style="color: #2a5298;"></i>
                    فلاتر إضافية
                </h6>
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">الكلية</label>
                        <select class="form-select" name="college_id" id="college_id">
                            <option value="">جميع الكليات</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?= htmlspecialchars($college['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($college_filter == $college['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">القسم</label>
                        <select class="form-select" name="section_id" id="section_id">
                            <option value="">جميع الأقسام</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">البرنامج</label>
                        <select class="form-select" name="program_id" id="program_id">
                            <option value="">جميع البرامج</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">التخصص</label>
                        <select class="form-select" name="specialization_id" id="specialization_id">
                            <option value="">جميع التخصصات</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">الدفعة</label>
                        <select class="form-select" name="batch_id" id="batch_id">
                            <option value="">جميع الدفعات</option>
                            <?php foreach ($batches as $batch): ?>
                                <option value="<?= htmlspecialchars($batch['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($batch_filter == $batch['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3 d-flex align-items-end">
                        <a href="student_grades.php" class="btn-reset w-100">
                            <i class="fas fa-redo-alt ms-2"></i>
                            إعادة تعيين
                        </a>
                    </div>
                </div>
            </div>
        </form>

        <!-- Students List -->
        <?php if (!empty($students_list)): ?>
            <div class="students-list-card">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold mb-0">
                        <i class="fas fa-users ms-2" style="color: #2a5298;"></i>
                        قائمة الطلاب
                    </h5>
                    <span class="students-count">
                        <i class="fas fa-user-graduate ms-1"></i>
                        <?= count($students_list) ?> طالب
                    </span>
                </div>
                
                <div class="students-list-box">
                    <?php foreach ($students_list as $student): ?>
                        <div class="student-item <?= ($selected_student_id == $student['student_id']) ? 'selected' : '' ?>" 
                             onclick="window.location.href='?student_id=<?= urlencode($student['student_id']) ?>&college_id=<?= urlencode($college_filter) ?>&section_id=<?= urlencode($section_filter) ?>&program_id=<?= urlencode($program_filter) ?>&specialization_id=<?= $specialization_filter ?>&batch_id=<?= urlencode($batch_filter) ?>&search_term=<?= urlencode($search_term) ?>&search_type=<?= $search_type ?>'">
                            <div class="row">
                                <div class="col-8">
                                    <div class="student-item-name">
                                        <?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                    <div class="student-item-id">
                                        <i class="fas fa-id-card ms-1"></i>
                                        <?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </div>
                                <div class="col-4 text-start">
                                    <div class="student-item-info">
                                        <span class="badge bg-light text-dark"><?= $student['subjects_count'] ?> مواد</span>
                                    </div>
                                    <div class="student-item-info">
                                        <?= htmlspecialchars($student['batch_name'] ?: '', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php elseif (!empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter) || !empty($search_term)): ?>
            <div class="students-list-card">
                <div class="no-results">
                    <i class="fas fa-user-slash"></i>
                    <h5>لا يوجد طلاب</h5>
                    <p class="text-muted">لم يتم العثور على طلاب تطابق معايير البحث</p>
                </div>
            </div>
        <?php endif; ?>

        <!-- Selected Student Details -->
        <?php if ($selected_student): ?>
            <div class="selected-student-header">
                <div class="row align-items-center">
                    <div class="col-lg-8">
                        <h4 class="mb-2">
                            <i class="fas fa-user-graduate ms-2"></i>
                            <?= htmlspecialchars($selected_student['student_name'], ENT_QUOTES, 'UTF-8') ?>
                        </h4>
                        <div class="d-flex flex-wrap gap-3">
                            <span>
                                <i class="fas fa-id-card ms-1"></i>
                                <?= htmlspecialchars($selected_student['student_id'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span>
                                <i class="fas fa-university ms-1"></i>
                                <?= htmlspecialchars($selected_student['college_name'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span>
                                <i class="fas fa-layer-group ms-1"></i>
                                <?= htmlspecialchars($selected_student['section_name'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span>
                                <i class="fas fa-graduation-cap ms-1"></i>
                                <?= htmlspecialchars($selected_student['program_name'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <?php if ($selected_student['specialization_name']): ?>
                                <span>
                                    <i class="fas fa-tag ms-1"></i>
                                    <?= htmlspecialchars($selected_student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($selected_student['batch_name']): ?>
                                <span>
                                    <i class="fas fa-users ms-1"></i>
                                    دفعة <?= htmlspecialchars($selected_student['batch_name'], ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="col-lg-4 text-lg-start text-center mt-3 mt-lg-0">
                        <a href="?college_id=<?= urlencode($college_filter) ?>&section_id=<?= urlencode($section_filter) ?>&program_id=<?= urlencode($program_filter) ?>&specialization_id=<?= $specialization_filter ?>&batch_id=<?= urlencode($batch_filter) ?>&search_term=<?= urlencode($search_term) ?>&search_type=<?= $search_type ?>" class="btn btn-light rounded-pill px-4">
                            <i class="fas fa-arrow-right ms-2"></i>
                            عودة للقائمة
                        </a>
                    </div>
                </div>
            </div>

            <!-- Semester Filter -->
            <?php if (!empty($available_semesters)): ?>
                <div class="semester-filter-card">
                    <form method="get" action="" id="semesterForm">
                        <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="college_id" value="<?= htmlspecialchars($college_filter, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="section_id" value="<?= htmlspecialchars($section_filter, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="program_id" value="<?= htmlspecialchars($program_filter, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="specialization_id" value="<?= (int)$specialization_filter ?>">
                        <input type="hidden" name="batch_id" value="<?= htmlspecialchars($batch_filter, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="search_term" value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="search_type" value="<?= htmlspecialchars($search_type, ENT_QUOTES, 'UTF-8') ?>">
                        
                        <div class="row g-3 align-items-center">
                            <div class="col-md-8">
                                <label class="form-label">
                                    <i class="fas fa-calendar-alt ms-1"></i>
                                    اختر الفصل الدراسي
                                </label>
                                <select class="form-select" name="semester_id" id="semesterSelect" onchange="this.form.submit()">
                                    <option value="">-- اختر الفصل --</option>
                                    <?php foreach ($available_semesters as $sem): ?>
                                        <option value="<?= (int)$sem['id'] ?>" <?= ($semester_filter == $sem['id']) ? 'selected' : '' ?>>
                                            الفصل <?= htmlspecialchars($sem['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <?php if ($semester_filter > 0): ?>
                                    <div class="semester-badge mt-4">
                                        <i class="fas fa-check-circle ms-1"></i>
                                        عرض مواد الفصل <?= htmlspecialchars($available_semesters[array_search($semester_filter, array_column($available_semesters, 'id'))]['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
            <?php elseif ($selected_student): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle ms-2"></i>
                    لا توجد مواد مسجلة لهذا الطالب في أي فصل دراسي
                </div>
            <?php endif; ?>

            <!-- Grades Section -->
            <?php if ($semester_filter > 0): ?>
                <?php if (!empty($student_subjects)): ?>
                    <form method="POST" action="" id="gradesForm">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="semester_id" value="<?= (int)$semester_filter ?>">
                        
                   
                        
                        <!-- Grades Table -->
                        <div class="content-card">
                            <div class="content-card-header">
                                <h5>
                                    <i class="fas fa-table ms-2"></i>
                                    مواد الفصل <?= htmlspecialchars($available_semesters[array_search($semester_filter, array_column($available_semesters, 'id'))]['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                </h5>
                                <span class="badge bg-info rounded-pill">
                                    <i class="fas fa-clock ms-1"></i>
                                    <?= date('Y-m-d H:i') ?>
                                </span>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="grades-table">
                                    <thead>
    <tr>
        <th width="50">#</th>
        <th width="120">كود المادة</th>
        <th width="300">اسم المادة</th>
        <th width="70">الساعات</th>
        <th width="100">الدرجة</th>
        <th width="120">التقدير</th>
        <th width="150">آخر تحديث</th>
    </tr>
</thead>
<tbody>
    <?php $counter = 1; ?>
    <?php foreach ($student_subjects as $subject): ?>
    <tr>
        <td>
            <span class="badge rounded-circle p-2" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; width: 35px; height: 35px; display: inline-flex; align-items: center; justify-content: center;">
                <?= $counter++ ?>
            </span>
        </td>
        <td>
            <code><?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?></code>
        </td>
        <td class="text-start text-center">
            <?= htmlspecialchars($subject['subjectnamea'], ENT_QUOTES, 'UTF-8') ?>
        </td>
        <td>
            <span class="badge bg-secondary"><?= (int)$subject['credit_hours'] ?></span>
        </td>
        <td>
            <input type="number" 
                   name="grades[<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>][degree]"
                   class="form-control degree-input"
                   value="<?= htmlspecialchars($subject['degree'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                   step="0.5"
                   min="0"
                   max="100"
                   style="width: 100px; margin: 0 auto; text-align: center; border-radius: 12px;"
                   placeholder="الدرجة">
        </td>
        <td>
            <select name="grades[<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>][grade_id]" 
                    class="grade-select grade-select-input"
                    data-subject="<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>"
                    data-original="<?= $subject['grade_id'] ?? '' ?>"
                    style="width: 110px;">
                <option value="">-- بدون تعديل --</option>
                <?php foreach ($grades as $grade): ?>
                    <option value="<?= (int)$grade['id'] ?>" 
                            data-weight="<?= (float)$grade['weight'] ?>"
                        <?= ($subject['grade_id'] == $grade['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($grade['grade'], ENT_QUOTES, 'UTF-8') ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <!-- Hidden field to store weight -->
            <input type="hidden" 
                   name="grades[<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>][weight]" 
                   class="weight-input"
                   value="<?= htmlspecialchars($subject['weight'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
        </td>
        <td>
            <?php if ($subject['updated_at']): ?>
                <span class="date-badge">
                    <i class="fas fa-clock ms-1"></i>
                    <?= date('Y-m-d', strtotime($subject['updated_at'])) ?>
                </span>
                <br>
                <small class="text-muted"><?= date('H:i', strtotime($subject['updated_at'])) ?></small>
            <?php else: ?>
                <span class="text-muted">--</span>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
</tbody>
                                </table>
                            </div>
                        </div>
 
                        
<?php if ($semester_filter > 0 && !empty($student_subjects)): 
    // Calculate statistics for this semester
    $stats = calculateStudentStats($mysqli1, $selected_student_id, $semester_filter);
    
    // Get semester name
    $semester_name = '';
    foreach ($available_semesters as $sem) {
        if ($sem['id'] == $semester_filter) {
            $semester_name = $sem['name'];
            break;
        }
    }
    
    // Display the complete statistics card with status
    echo renderAcademicStatsCard($mysqli1, $selected_student_id, $stats, $semester_name, $semester_filter);
    
endif; ?>
                        <!-- Save Button -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="content-card">
                                    <div class="text-center">
                                        <button type="submit" name="update_grades" class="btn-gradient" style="padding: 15px 60px;">
                                            <i class="fas fa-save ms-2"></i>
                                            حفظ التغييرات
                                        </button>
                                        <div class="mt-2 text-muted small">
                                            <i class="fas fa-info-circle ms-1"></i>
                                            المقررات التي لم يتم تعديلها ستبقى كما هي
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                    </form>
                    
                <?php else: ?>
                    <!-- No subjects message -->
                    <div class="content-card">
                        <div class="no-results">
                            <i class="fas fa-book-open"></i>
                            <h5>لا توجد مواد</h5>
                            <p class="text-muted mb-4">
                                لا توجد مواد مسجلة للطالب في هذا الفصل الدراسي
                            </p>
                            <a href="subject_enrollment.php?student_id=<?= urlencode($selected_student_id) ?>" class="btn-gradient">
                                <i class="fas fa-plus-circle ms-2"></i>
                                تسجيل مواد للطالب
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            <?php elseif ($selected_student && !empty($available_semesters)): ?>
                <!-- No semester selected message -->
                <div class="content-card">
                    <div class="no-results">
                        <i class="fas fa-calendar-alt"></i>
                        <h5>اختر الفصل الدراسي</h5>
                        <p class="text-muted mb-4">الرجاء اختيار الفصل الدراسي لعرض المقررات</p>
                    </div>
                </div>
            <?php endif; ?>
            
        <?php elseif (empty($students_list) && empty($selected_student) && (empty($college_filter) && empty($section_filter) && empty($program_filter) && empty($specialization_filter) && empty($batch_filter) && empty($search_term))): ?>
            <!-- Initial State -->
            <div class="content-card">
                <div class="no-results">
                    <i class="fas fa-search"></i>
                    <h5>ابحث عن طالب</h5>
                    <p class="text-muted">يمكنك البحث بالرقم الجامعي أو الاسم، أو استخدام الفلاتر لعرض قائمة الطلاب</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>
     <!-- Statistics Cards -->
                        <div class="row g-4 mb-4">
                            <?php
                            $total_subjects = count($student_subjects);
                            $passed = 0;
                            $failed = 0;
                            $pending = 0;
                            $total_hours = 0;
                            
                            foreach ($student_subjects as $subj) {
                                $total_hours += $subj['credit_hours'];
                                if ($subj['grade']) {
                                    if ($subj['weight'] > 0) {
                                        $passed++;
                                    } else {
                                        $failed++;
                                    }
                                } else {
                                    $pending++;
                                }
                            }
                            ?>
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-book"></i>
                                    </div>
                                    <div class="stat-number"><?= $total_subjects ?></div>
                                    <div class="stat-label">إجمالي المقررات</div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-check-circle text-success"></i>
                                    </div>
                                    <div class="stat-number"><?= $passed ?></div>
                                    <div class="stat-label">مواد ناجح</div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-times-circle text-danger"></i>
                                    </div>
                                    <div class="stat-number"><?= $failed ?></div>
                                    <div class="stat-label">مواد راسب</div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-hourglass-half text-warning"></i>
                                    </div>
                                    <div class="stat-number"><?= $pending ?></div>
                                    <div class="stat-label">بدون تقدير</div>
                                </div>
                            </div>
                        </div>
<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></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 ?>;

// Store all grade select elements
let gradeSelects = [];

// 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.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);
}

// Update weight field and highlight
function updateWeightFromGrade(select) {
    const subject = select.dataset.subject;
    const selectedOption = select.options[select.selectedIndex];
    const weight = selectedOption.dataset.weight;
    const weightInput = document.querySelector(`.weight-input[name="grades[${subject}][weight]"]`);
    
    if (weightInput && weight) {
        weightInput.value = weight;
    }
    
    // Highlight based on grade
    highlightGradeDisplay(select);
}

// Highlight grade display
function highlightGradeDisplay(selectElement) {
    const gradeId = selectElement.value;
    if (gradeId) {
        const gradeObj = findGradeById(gradeId);
        if (gradeObj) {
            if (gradeObj.weight > 0) {
                selectElement.style.backgroundColor = '#d4edda';
                selectElement.style.borderColor = '#c3e6cb';
                selectElement.style.color = '#155724';
            } else {
                selectElement.style.backgroundColor = '#f8d7da';
                selectElement.style.borderColor = '#f5c6cb';
                selectElement.style.color = '#721c24';
            }
            selectElement.style.fontWeight = 'bold';
        }
    } else {
        selectElement.style.backgroundColor = '';
        selectElement.style.borderColor = '#e2e8f0';
        selectElement.style.color = '';
        selectElement.style.fontWeight = '';
    }
}

// Handle keyboard input
function handleGradeKeyPress(e) {
    const activeElement = document.activeElement;
    
    if (!activeElement.classList.contains('grade-select-input')) {
        return;
    }
    
    const key = e.key;
    
    // Handle Enter key
    if (key === 'Enter') {
        e.preventDefault();
        
        const currentIndex = gradeSelects.indexOf(activeElement);
        if (currentIndex >= 0 && currentIndex < gradeSelects.length - 1) {
            const nextSelect = gradeSelects[currentIndex + 1];
            nextSelect.focus();
            nextSelect.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
        return;
    }
    
    // Handle letter keys
    if (/^[a-zA-Z]$/.test(key) || key === '+') {
        e.preventDefault();
        
        const currentValue = activeElement.value;
        const currentGrade = currentValue ? findGradeById(currentValue) : null;
        
        let newGrade = null;
        
        if (key === '+') {
            if (currentGrade) {
                const baseLetter = currentGrade.grade.replace('+', '');
                const plusGrade = findGradeByLetter(baseLetter + '+');
                if (plusGrade) {
                    newGrade = plusGrade;
                }
            }
        } else {
            const upperKey = key.toUpperCase();
            
            if (currentGrade && currentGrade.grade === upperKey) {
                const plusGrade = findGradeByLetter(upperKey + '+');
                if (plusGrade) {
                    newGrade = plusGrade;
                }
            } else {
                newGrade = findGradeByLetter(upperKey);
            }
        }
        
        if (newGrade) {
            activeElement.value = newGrade.id;
            const event = new Event('change', { bubbles: true });
            activeElement.dispatchEvent(event);
            updateWeightFromGrade(activeElement);
        }
    }
}

// Load sections based on college
function loadSections(collegeId, selectedSection = '') {
    if (!collegeId) {
        $('#section_id').html('<option value="">جميع الأقسام</option>');
        return;
    }
    
    $.ajax({
        url: 'ajax/get_sections.php',
        method: 'GET',
        data: { college_id: collegeId },
        dataType: 'json',
        success: function(sections) {
            let options = '<option value="">جميع الأقسام</option>';
            sections.forEach(function(section) {
                const selected = (section.id == selectedSection) ? 'selected' : '';
                options += `<option value="${section.id}" ${selected}>${section.name}</option>`;
            });
            $('#section_id').html(options);
        },
        error: function(xhr, status, error) {
            console.error('Error loading sections:', error);
        }
    });
}

// Load programs based on college
function loadPrograms(collegeId, selectedProgram = '') {
    if (!collegeId) {
        $('#program_id').html('<option value="">جميع البرامج</option>');
        return;
    }
    
    $.ajax({
        url: 'ajax/get_programs.php',
        method: 'GET',
        data: { college_id: collegeId },
        dataType: 'json',
        success: function(programs) {
            let options = '<option value="">جميع البرامج</option>';
            programs.forEach(function(program) {
                const selected = (program.id == selectedProgram) ? 'selected' : '';
                options += `<option value="${program.id}" ${selected}>${program.name}</option>`;
            });
            $('#program_id').html(options);
        },
        error: function(xhr, status, error) {
            console.error('Error loading programs:', error);
        }
    });
}

// Load specializations based on section and program
function loadSpecializations(sectionId, programId, selectedSpecialization = 0) {
    if (!sectionId || !programId) {
        $('#specialization_id').html('<option value="">جميع التخصصات</option>');
        return;
    }
    
    $.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(function(spec) {
                const selected = (spec.specialization_id == selectedSpecialization) ? 'selected' : '';
                options += `<option value="${spec.specialization_id}" ${selected}>${spec.specialization_name_ar}</option>`;
            });
            $('#specialization_id').html(options);
        },
        error: function(xhr, status, error) {
            console.error('Error loading specializations:', error);
        }
    });
}

// Auto-submit form when any filter changes
function setupAutoSubmit() {
    $('#college_id, #section_id, #program_id, #specialization_id, #batch_id, #search_type').on('change', function() {
        $('#filterForm').submit();
    });
    
    // Debounced search for text input
    let searchTimeout;
    $('#search_term').on('keyup', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            $('#filterForm').submit();
        }, 700); // Wait 700ms after user stops typing
    });
}

$(document).ready(function() {
    // Initialize dependent dropdowns
    const collegeId = $('#college_id').val();
    if (collegeId) {
        loadSections(collegeId, '<?= $section_filter ?>');
        loadPrograms(collegeId, '<?= $program_filter ?>');
        
        // Load specializations if both section and program are selected
        const sectionId = '<?= $section_filter ?>';
        const programId = '<?= $program_filter ?>';
        if (sectionId && programId) {
            loadSpecializations(sectionId, programId, <?= $specialization_filter ?>);
        }
    }
    
    // College change event - updates sections and programs
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        loadSections(collegeId, '');
        loadPrograms(collegeId, '');
        $('#specialization_id').html('<option value="">جميع التخصصات</option>');
    });
    
    // Section and Program change events - update specializations
    $('#section_id, #program_id').on('change', function() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            loadSpecializations(sectionId, programId, 0);
        }
    });
    
    // Setup auto-submit for filters
    setupAutoSubmit();
    
    // Initialize grade selects
    function updateGradeSelectsArray() {
        gradeSelects = Array.from(document.querySelectorAll('.grade-select-input'));
    }
    
    // Add event listeners to grade selects
    document.querySelectorAll('.grade-select-input').forEach(select => {
        select.addEventListener('change', function() {
            updateWeightFromGrade(this);
        });
        
        select.addEventListener('focus', function() {
            this.style.transform = 'scale(1.02)';
            this.style.boxShadow = '0 0 0 4px rgba(245, 87, 108, 0.2)';
        });
        
        select.addEventListener('blur', function() {
            this.style.transform = 'scale(1)';
            this.style.boxShadow = 'none';
        });
        
        // Initial highlight
        if (select.value) {
            highlightGradeDisplay(select);
        }
    });
    
    // Add keyboard listener
    document.addEventListener('keydown', handleGradeKeyPress);
    
    // Update grade selects array
    updateGradeSelectsArray();
    
    // Form submission
    $('#gradesForm').on('submit', function(e) {
        let hasChanges = false;
        
        document.querySelectorAll('.grade-select-input').forEach(select => {
            if (select.value !== select.dataset.original) {
                hasChanges = true;
            }
        });
        
        if (!hasChanges) {
            if (!confirm('لم تقم بإجراء أي تغييرات. هل تريد المتابعة؟')) {
                e.preventDefault();
                return false;
            }
        } else {
            if (!confirm('هل أنت متأكد من حفظ التغييرات؟')) {
                e.preventDefault();
                return false;
            }
        }
        
        $('#loadingOverlay').fadeIn();
        return true;
    });
    
    // Ctrl+S to save
    $(document).on('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            $('button[name="update_grades"]').click();
        }
    });
    
    // Auto-hide alerts
    setTimeout(function() {
        $('.alert').fadeOut(500, function() {
            $(this).remove();
        });
    }, 5000);
});
</script>

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