<?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_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 = '';
$search_term = validateString($_GET['search_term'] ?? '');
$search_type = validateString($_GET['search_type'] ?? 'id'); // id or name

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

// Pagination
$page = validateInt($_GET['page'] ?? 1);
$per_page = 12;
$offset = ($page - 1) * $per_page;

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

// If a specific student is selected (via student_id parameter)
$selected_student_id = validateString($_GET['student_id'] ?? '');
$selected_student = null;
$student_subjects = [];
$available_semesters = [];

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
    if ($selected_student && $semester_filter > 0) {
        $subjectQuery = "
            SELECT 
                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
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode AND sub.deleted_at IS NULL
            JOIN semesters s ON ss.semester_id = s.id AND s.deleted_at IS NULL
            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 = ?
            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'] ? (float)$row['degree'] : null,
                    '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
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;
                
                // Skip if no grade selected
                if ($grade_id <= 0) {
                    $skipped_count++;
                    continue;
                }
                
                // Get grade information
                $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 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();
                
                if ($checkResult->num_rows > 0) {
                    // Update existing record
                    $updateStmt = $mysqli1->prepare("
                        UPDATE studentsubjects 
                        SET grade = ?, grade_id = ?, weight = ?, updated_at = NOW()
                        WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
                    ");
                    
                    if ($updateStmt) {
                        $updateStmt->bind_param(
                            'sidssi',
                            $final_grade,
                            $final_grade_id,
                            $final_weight,
                            $student_id,
                            $subjectcode,
                            $semester_id
                        );
                        
                        if ($updateStmt->execute()) {
                            $success_count++;
                        } else {
                            $error_count++;
                        }
                        $updateStmt->close();
                    } else {
                        $error_count++;
                    }
                } else {
                    // Get batch_id from existing record or use default
                    $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();
                    
                    // Insert new record
                    $insertStmt = $mysqli1->prepare("
                        INSERT INTO studentsubjects 
                        (student_id, subjectcode, semester_id, batch_id, grade, weight, grade_id, created_at, updated_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                    ");
                    
                    if ($insertStmt) {
                        $insertStmt->bind_param(
                            'ssissdi',
                            $student_id,
                            $subjectcode,
                            $semester_id,
                            $batch_id,
                            $final_grade,
                            $final_weight,
                            $final_grade_id
                        );
                        
                        if ($insertStmt->execute()) {
                            $success_count++;
                        } else {
                            $error_count++;
                        }
                        $insertStmt->close();
                    } else {
                        $error_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 مادة)";
                }
            } 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, #fc6767, #ec008c);
        --info-gradient: linear-gradient(135deg, #667eea, #764ba2);
        --search-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 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;
    }

    .search-card {
        background: white;
        border-radius: 30px;
        padding: 30px;
        margin-bottom: 30px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
    }

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

    .results-card {
        background: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        max-height: 500px;
        overflow-y: auto;
    }

    .results-card::-webkit-scrollbar {
        width: 8px;
    }

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

    .results-card::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #f093fb, #f5576c);
        border-radius: 10px;
    }

    .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: #f5576c;
        box-shadow: 0 0 0 4px rgba(245, 87, 108, 0.1);
        outline: none;
    }

    .btn-search {
        background: linear-gradient(135deg, #f093fb, #f5576c);
        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);
        width: 100%;
    }

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

    .student-card {
        background: white;
        border-radius: 25px;
        padding: 20px;
        margin-bottom: 15px;
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        border: 2px solid transparent;
        transition: all 0.3s ease;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .student-card:hover {
        border-color: #f5576c;
        transform: translateY(-3px);
        box-shadow: 0 10px 30px rgba(245, 87, 108, 0.2);
    }

    .student-card.selected {
        border-color: #f5576c;
        background: linear-gradient(135deg, #fff5f5, #fff);
    }

    .student-card::before {
        content: '\f007';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        position: absolute;
        bottom: -10px;
        left: -10px;
        font-size: 80px;
        opacity: 0.03;
        color: #f5576c;
        transform: rotate(-5deg);
    }

    .student-id-badge {
        background: linear-gradient(135deg, #f093fb, #f5576c);
        color: white;
        padding: 5px 15px;
        border-radius: 50px;
        font-size: 0.9rem;
        font-weight: 600;
        display: inline-block;
    }

    .student-name {
        font-size: 1.2rem;
        font-weight: 700;
        color: #2d3748;
        margin-bottom: 5px;
    }

    .student-info {
        color: #718096;
        font-size: 0.9rem;
        margin-bottom: 5px;
    }

    .student-stats {
        display: flex;
        gap: 15px;
        margin-top: 10px;
    }

    .stat-item {
        background: #f7fafc;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        color: #4a5568;
    }

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

    .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, #f093fb, #f5576c);
        color: white;
    }

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

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

    .keyboard-shortcuts {
        background: #f8f9fa;
        border-radius: 20px;
        padding: 15px;
        margin-top: 15px;
    }

    .shortcut-item {
        display: inline-block;
        margin-left: 20px;
        margin-bottom: 10px;
    }

    kbd {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 8px;
        padding: 5px 12px;
        font-size: 0.9rem;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    .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 #f5576c;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    .loading-small {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #f5576c;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 10px;
    }

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

    @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;
        }
    }
</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 Form -->
        <div class="search-card">
            <form method="get" action="" id="searchForm">
                <div class="row g-4">
                    <!-- Basic Search -->
                    <div class="col-md-8">
                        <label class="form-label">
                            <i class="fas fa-search ms-1"></i>
                            بحث بالرقم الجامعي أو الاسم
                        </label>
                        <div class="input-group">
                            <select class="form-select" name="search_type" id="search_type" style="max-width: 130px; border-radius: 15px 0 0 15px;">
                                <option value="id" <?= $search_type === 'id' ? 'selected' : '' ?>>بالرقم</option>
                                <option value="name" <?= $search_type === 'name' ? 'selected' : '' ?>>بالاسم</option>
                            </select>
                            <input type="text" 
                                   class="form-control" 
                                   name="search_term" 
                                   id="search_term"
                                   value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>"
                                   placeholder="أدخل الرقم الجامعي أو اسم الطالب..."
                                   style="border-radius: 0 15px 15px 0;">
                        </div>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="submit" class="btn-search" id="searchBtn">
                            <i class="fas fa-search ms-2"></i>
                            بحث
                        </button>
                    </div>
                </div>

                <!-- Advanced Filters Toggle -->
                <div class="text-center mt-4">
                    <button type="button" class="btn btn-link text-decoration-none" onclick="$('#advancedFilters').slideToggle()">
                        <i class="fas fa-chevron-down ms-1"></i>
                        فلاتر البحث المتقدم
                    </button>
                </div>

                <!-- Advanced Filters -->
                <div id="advancedFilters" style="display: <?= (!empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter)) ? 'block' : 'none' ?>;" class="mt-4">
                    <div class="filter-card">
                        <h6 class="fw-bold mb-3">
                            <i class="fas fa-filter ms-2" style="color: #f5576c;"></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>
                                    <?php if (!empty($section_filter)): ?>
                                        <?php
                                        $sectionStmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE id = ? AND deleted_at IS NULL");
                                        if ($sectionStmt) {
                                            $sectionStmt->bind_param('s', $section_filter);
                                            $sectionStmt->execute();
                                            $sectionResult = $sectionStmt->get_result();
                                            if ($sectionRow = $sectionResult->fetch_assoc()) {
                                                echo '<option value="' . htmlspecialchars($section_filter, ENT_QUOTES, 'UTF-8') . '" selected>' . htmlspecialchars($sectionRow['name'], ENT_QUOTES, 'UTF-8') . '</option>';
                                            }
                                            $sectionStmt->close();
                                        }
                                        ?>
                                    <?php endif; ?>
                                </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>
                                    <?php if (!empty($program_filter)): ?>
                                        <?php
                                        $programStmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE id = ? AND deleted_at IS NULL");
                                        if ($programStmt) {
                                            $programStmt->bind_param('s', $program_filter);
                                            $programStmt->execute();
                                            $programResult = $programStmt->get_result();
                                            if ($programRow = $programResult->fetch_assoc()) {
                                                echo '<option value="' . htmlspecialchars($program_filter, ENT_QUOTES, 'UTF-8') . '" selected>' . htmlspecialchars($programRow['name'], ENT_QUOTES, 'UTF-8') . '</option>';
                                            }
                                            $programStmt->close();
                                        }
                                        ?>
                                    <?php endif; ?>
                                </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>
                                    <?php if ($specialization_filter > 0): ?>
                                        <?php
                                        $specStmt = $mysqli1->prepare("SELECT specialization_name_ar FROM specializations WHERE specialization_id = ? AND deleted_at IS NULL");
                                        if ($specStmt) {
                                            $specStmt->bind_param('i', $specialization_filter);
                                            $specStmt->execute();
                                            $specResult = $specStmt->get_result();
                                            if ($specRow = $specResult->fetch_assoc()) {
                                                echo '<option value="' . (int)$specialization_filter . '" selected>' . htmlspecialchars($specRow['specialization_name_ar'], ENT_QUOTES, 'UTF-8') . '</option>';
                                            }
                                            $specStmt->close();
                                        }
                                        ?>
                                    <?php endif; ?>
                                </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>
                </div>
            </form>
        </div>

        <!-- Search Results Container -->
        <div id="searchResults"></div>

        <!-- 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">
                        <button class="btn btn-light rounded-pill px-4" onclick="window.history.back()">
                            <i class="fas fa-arrow-right ms-2"></i>
                            عودة للنتائج
                        </button>
                    </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="search_term" value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="search_type" value="<?= htmlspecialchars($search_type, 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') ?>">
                        
                        <div class="row g-3 align-items-center">
                            <div class="col-md-6">
                                <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-6">
                                <?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 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 ?>">
                        
                        <!-- 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>
                        
                        <!-- Instructions Card -->
                        <div class="content-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-6">
                                            <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;"></span>
                                                <span><strong>اختيار التقدير:</strong> اختر من القائمة المنسدلة</span>
                                            </div>
                                            <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;">✓</span>
                                                <span><strong>التقديرات الناجحة:</strong> تظهر باللون الأخضر</span>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="keyboard-shortcuts">
                                                <strong class="d-block mb-2">
                                                    <i class="fas fa-keyboard ms-1"></i>
                                                    اختصارات لوحة المفاتيح:
                                                </strong>
                                                <div class="shortcut-item">
                                                    <kbd>A</kbd> <span class="text-muted">→</span> A
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>A</kbd> + <kbd>A</kbd> <span class="text-muted">→</span> A+
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>B</kbd> <span class="text-muted">→</span> B
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>B</kbd> + <kbd>B</kbd> <span class="text-muted">→</span> B+
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>C</kbd> <span class="text-muted">→</span> C
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>C</kbd> + <kbd>C</kbd> <span class="text-muted">→</span> C+
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>D</kbd> <span class="text-muted">→</span> D
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>D</kbd> + <kbd>D</kbd> <span class="text-muted">→</span> D+
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>F</kbd> <span class="text-muted">→</span> F
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>Enter</kbd> <span class="text-muted">→</span> التقدير التالي
                                                </div>
                                                <div class="shortcut-item">
                                                    <kbd>Ctrl</kbd> + <kbd>S</kbd> <span class="text-muted">→</span> حفظ
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="text-start">
                                    <button type="submit" name="update_grades" class="btn-gradient" style="padding: 15px 40px;">
                                        <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>
                                    مواد الفصل <?= 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="60">#</th>
                                            <th width="120">كود المادة</th>
                                            <th>اسم المادة</th>
                                            <th width="80">الساعات</th>
                                            <th width="100">الدفعة</th>
                                            <th width="100">التقدير الحالي</th>
                                            <th width="150">التقدير الجديد</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">
                                                <?= htmlspecialchars($subject['subjectnamea'], ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary"><?= (int)$subject['credit_hours'] ?></span>
                                            </td>
                                            <td>
                                                <span class="batch-badge">
                                                    <?= htmlspecialchars($subject['batch_name'], ENT_QUOTES, 'UTF-8') ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($subject['grade']): ?>
                                                    <?php
                                                    $grade_class = ($subject['weight'] > 0) ? 'grade-pass' : 'grade-fail';
                                                    ?>
                                                    <span class="grade-badge <?= $grade_class ?>">
                                                        <?= htmlspecialchars($subject['grade'], ENT_QUOTES, 'UTF-8') ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="text-muted">--</span>
                                                <?php endif; ?>
                                            </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'] ?? '' ?>">
                                                    <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>
                        
                        <!-- Save Button (Bottom) -->
                        <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-3 text-muted small">
                                            <i class="fas fa-lightbulb 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>
                            <h4>لا توجد مواد</h4>
                            <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): ?>
                <!-- No semester selected message -->
                <div class="content-card">
                    <div class="no-results">
                        <i class="fas fa-calendar-alt"></i>
                        <h4>اختر الفصل الدراسي</h4>
                        <p class="text-muted mb-4">الرجاء اختيار الفصل الدراسي لعرض المقررات</p>
                    </div>
                </div>
            <?php endif; ?>
            
        <?php endif; ?>
    </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);
        }
    });
}

// Live search function
// Live search function
function performSearch() {
    const searchTerm = $('#search_term').val();
    const searchType = $('#search_type').val();
    const collegeId = $('#college_id').val();
    const sectionId = $('#section_id').val();
    const programId = $('#program_id').val();
    const specializationId = $('#specialization_id').val();
    const batchId = $('#batch_id').val();
    
    // Don't search if all filters are empty
    if (!searchTerm && !collegeId && !sectionId && !programId && !specializationId && !batchId) {
        $('#searchResults').empty();
        return;
    }
    
    $('#searchResults').html('<div class="text-center p-5"><div class="loading-spinner" style="width: 40px; height: 40px;"></div><p class="mt-3">جاري البحث...</p></div>');
    
    $.ajax({
        url: 'ajax/search_students.php',
        method: 'GET',
        data: {
            search_term: searchTerm,
            search_type: searchType,
            college_id: collegeId || '',
            section_id: sectionId || '',
            program_id: programId || '',
            specialization_id: specializationId || '',
            batch_id: batchId || ''
        },
        dataType: 'json',
        timeout: 10000, // 10 seconds timeout
        success: function(response) {
            if (response.error) {
                $('#searchResults').html('<div class="alert alert-danger">' + response.error + '</div>');
            } else {
                displaySearchResults(response);
            }
        },
        error: function(xhr, status, error) {
            console.error('Search error:', status, error);
            console.error('Response:', xhr.responseText);
            $('#searchResults').html('<div class="alert alert-danger">حدث خطأ في البحث: ' + error + '</div>');
        }
    });
}

// Display search results
function displaySearchResults(students) {
    if (!students || students.length === 0) {
        $('#searchResults').html(`
            <div class="no-results">
                <i class="fas fa-user-slash"></i>
                <h4>لا توجد نتائج</h4>
                <p class="text-muted">لم يتم العثور على طلاب تطابق معايير البحث</p>
            </div>
        `);
        return;
    }
    
    let html = '<div class="results-card"><h5 class="fw-bold mb-4"><i class="fas fa-users ms-2" style="color: #f5576c;"></i> نتائج البحث (' + students.length + ')</h5><div class="row">';
    
    students.forEach(function(student) {
        // Get current filter values for maintaining search context
        const searchTerm = encodeURIComponent($('#search_term').val());
        const searchType = $('#search_type').val();
        const collegeId = $('#college_id').val();
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        const specializationId = $('#specialization_id').val();
        const batchId = $('#batch_id').val();
        
        const url = '?student_id=' + encodeURIComponent(student.student_id) + 
                    '&search_term=' + searchTerm + 
                    '&search_type=' + searchType + 
                    '&college_id=' + (collegeId || '') + 
                    '&section_id=' + (sectionId || '') + 
                    '&program_id=' + (programId || '') + 
                    '&specialization_id=' + (specializationId || '') + 
                    '&batch_id=' + (batchId || '');
        
        html += `
            <div class="col-md-6 col-lg-4">
                <div class="student-card" onclick="window.location.href='${url}'">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <span class="student-id-badge">
                            <i class="fas fa-id-card ms-1"></i>
                            ${escapeHtml(student.student_id)}
                        </span>
                        <span class="badge bg-light text-dark">
                            <i class="fas fa-book ms-1"></i>
                            ${student.subjects_count || 0} مادة
                        </span>
                    </div>
                    <div class="student-name">
                        ${escapeHtml(student.student_name)}
                    </div>
                    <div class="student-info">
                        <i class="fas fa-university ms-1" style="width: 20px;"></i>
                        ${escapeHtml(student.college_name || 'غير محدد')}
                    </div>
                    <div class="student-info">
                        <i class="fas fa-layer-group ms-1" style="width: 20px;"></i>
                        ${escapeHtml(student.section_name || 'غير محدد')}
                    </div>
                    <div class="student-stats">
                        <span class="stat-item">
                            <i class="fas fa-check-circle text-success ms-1"></i>
                            ${student.graded_count || 0} مقيم
                        </span>
                        <span class="stat-item">
                            <i class="fas fa-hourglass-half text-warning ms-1"></i>
                            ${(student.subjects_count || 0) - (student.graded_count || 0)} غير مقيم
                        </span>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div></div>';
    $('#searchResults').html(html);
}

// Escape HTML to prevent XSS
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return String(unsafe)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// Live search on typing with debounce
let searchTimeout;
$('#search_term').on('keyup', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        performSearch();
    }, 500); // Wait 500ms after user stops typing
});

// Search on filter changes
$('#college_id, #section_id, #program_id, #specialization_id, #batch_id, #search_type').on('change', function() {
    performSearch();
});

// Prevent form submission for AJAX search
$('#searchForm').on('submit', function(e) {
    e.preventDefault();
    performSearch();
});
// Display search results
function displaySearchResults(students) {
    if (!students || students.length === 0) {
        $('#searchResults').html(`
            <div class="no-results">
                <i class="fas fa-user-slash"></i>
                <h4>لا توجد نتائج</h4>
                <p class="text-muted">لم يتم العثور على طلاب تطابق معايير البحث</p>
            </div>
        `);
        return;
    }
    
    let html = '<div class="results-card"><h5 class="fw-bold mb-4"><i class="fas fa-users ms-2" style="color: #f5576c;"></i> نتائج البحث</h5><div class="row">';
    
    students.forEach(function(student) {
        html += `
            <div class="col-md-6 col-lg-4">
                <div class="student-card" onclick="window.location.href='?student_id=${encodeURIComponent(student.student_id)}&search_term=${encodeURIComponent($('#search_term').val())}&search_type=${$('#search_type').val()}&college_id=${$('#college_id').val()}&section_id=${$('#section_id').val()}&program_id=${$('#program_id').val()}&specialization_id=${$('#specialization_id').val()}&batch_id=${$('#batch_id').val()}'">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <span class="student-id-badge">
                            <i class="fas fa-id-card ms-1"></i>
                            ${escapeHtml(student.student_id)}
                        </span>
                        <span class="badge bg-light text-dark">
                            <i class="fas fa-book ms-1"></i>
                            ${student.subjects_count || 0} مادة
                        </span>
                    </div>
                    <div class="student-name">
                        ${escapeHtml(student.student_name)}
                    </div>
                    <div class="student-info">
                        <i class="fas fa-university ms-1" style="width: 20px;"></i>
                        ${escapeHtml(student.college_name || 'غير محدد')}
                    </div>
                    <div class="student-info">
                        <i class="fas fa-layer-group ms-1" style="width: 20px;"></i>
                        ${escapeHtml(student.section_name || 'غير محدد')}
                    </div>
                    <div class="student-stats">
                        <span class="stat-item">
                            <i class="fas fa-check-circle text-success ms-1"></i>
                            ${student.graded_count || 0} مقيم
                        </span>
                        <span class="stat-item">
                            <i class="fas fa-hourglass-half text-warning ms-1"></i>
                            ${(student.subjects_count || 0) - (student.graded_count || 0)} غير مقيم
                        </span>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div></div>';
    $('#searchResults').html(html);
}

// Escape HTML to prevent XSS
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

$(document).ready(function() {
    // Initialize dependent dropdowns
    const collegeId = $('#college_id').val();
    if (collegeId) {
        loadSections(collegeId, '<?= $section_filter ?>');
        loadPrograms(collegeId, '<?= $program_filter ?>');
    }
    
    // College change event
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        loadSections(collegeId, '');
        loadPrograms(collegeId, '');
        $('#specialization_id').html('<option value="">جميع التخصصات</option>');
        performSearch(); // Live search on filter change
    });
    
    // Section change event
    $('#section_id').on('change', function() {
        const sectionId = $(this).val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            loadSpecializations(sectionId, programId, 0);
        }
        performSearch(); // Live search on filter change
    });
    
    // Program change event
    $('#program_id').on('change', function() {
        const programId = $(this).val();
        const sectionId = $('#section_id').val();
        if (sectionId && programId) {
            loadSpecializations(sectionId, programId, 0);
        }
        performSearch(); // Live search on filter change
    });
    
    // Specialization change event
    $('#specialization_id').on('change', function() {
        performSearch(); // Live search on filter change
    });
    
    // Batch change event
    $('#batch_id').on('change', function() {
        performSearch(); // Live search on filter change
    });
    
    // Live search on typing
    let searchTimeout;
    $('#search_term').on('keyup', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            performSearch();
        }, 500); // Wait 500ms after user stops typing
    });
    
    // Search type change
    $('#search_type').on('change', function() {
        performSearch();
    });
    
    // Prevent form submission for AJAX search
    $('#searchForm').on('submit', function(e) {
        e.preventDefault();
        performSearch();
    });
    
    // 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);
    
    // Advanced filters toggle icon
    $('.btn-link').on('click', function() {
        const icon = $(this).find('i');
        icon.toggleClass('fa-chevron-down fa-chevron-up');
    });
    
    // Initial search if there are parameters
    <?php if (!empty($search_term) || !empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter)): ?>
        performSearch();
    <?php endif; ?>
});
</script>

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