<?php
// instructor_assessments.php - COMPLETE WITH GRADE CALCULATION
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('max_input_vars', 5000);

require 'db.php';
require 'helpers.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$success_message = '';
$error_message = '';
$csrf_token = csrf_token();
$instructor_id = 1;

// Get filter parameters
$college_id = isset($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$section_id = isset($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
$program_id = isset($_GET['program_id']) ? (int)$_GET['program_id'] : 0;
$batch_id = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
$semester_id = isset($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
$selected_subject = isset($_GET['subject_code']) ? $_GET['subject_code'] : '';
$has_search = isset($_GET['search']) && $_GET['search'] == 1;

// Load colleges
$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[] = $row;
    }
}

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

// Load semesters
$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()) {
        $semesters[] = $row;
    }
}

// Load programs
$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[] = $row;
    }
}

// Load sections for selected college
$sections = [];
if ($college_id > 0) {
    $sec_result = $mysqli1->query("SELECT id, name FROM sections WHERE parent = $college_id AND deleted_at IS NULL ORDER BY name");
    if ($sec_result) {
        while ($row = $sec_result->fetch_assoc()) {
            $sections[] = $row;
        }
    }
}

// Get grades from tblgrade for calculation
$grades_list = [];
$result = $mysqli1->query("SELECT id, grade, weight, xmin, xmax FROM tblgrade ORDER BY weight DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $grades_list[] = [
            'id' => (int)$row['id'],
            'grade' => $row['grade'],
            'weight' => (float)$row['weight'],
            'xmin' => $row['xmin'] !== null ? (float)$row['xmin'] : null,
            'xmax' => $row['xmax'] !== null ? (float)$row['xmax'] : null
        ];
    }
}

// Get subjects - simple query from studentsubjects
$subjects_list = [];
if ($batch_id > 0 && $semester_id > 0) {
    $subj_query = "
        SELECT DISTINCT 
            subjectcode
        FROM studentsubjects 
        WHERE batch_id = $batch_id 
        AND semester_id = $semester_id
        ORDER BY subjectcode
    ";
    
    $subj_result = $mysqli1->query($subj_query);
    if ($subj_result && $subj_result->num_rows > 0) {
        while ($row = $subj_result->fetch_assoc()) {
            $subject_name = $row['subjectcode'];
            $name_query = "SELECT subjectnamea FROM subjects WHERE subjectcode = '{$row['subjectcode']}' LIMIT 1";
            $name_result = $mysqli1->query($name_query);
            if ($name_result && $name_result->num_rows > 0) {
                $name_row = $name_result->fetch_assoc();
                $subject_name = $name_row['subjectnamea'] ?: $row['subjectcode'];
            }
            $subjects_list[$row['subjectcode']] = $subject_name;
        }
    }
}

// Get assessment types
$assessment_types = [];
$result = $mysqli1->query("SELECT id, assessment_name as name FROM assessmentstype ORDER BY id");
if ($result) {
    $arabic_names = [
        1 => 'اختبار نهائي',
        2 => 'اختبار نصف الفصل',
        3 => 'أعمال سنة',
        4 => 'ورش',
        5 => 'عملي'
    ];
    while ($row = $result->fetch_assoc()) {
        $row['name_ar'] = $arabic_names[$row['id']] ?? $row['name'];
        $assessment_types[] = $row;
    }
}

// Get existing assessment configs
$assessment_configs = [];
$total_weight = 0;
if ($selected_subject && $semester_id > 0) {
    $config_query = "
        SELECT sac.*, at.assessment_name as name
        FROM subject_assessment_config sac
        INNER JOIN assessmentstype at ON sac.assessment_id = at.id
        WHERE sac.subjectcode = ?
        AND (sac.semester_id = ? OR sac.semester_id IS NULL)
    ";
    $config_stmt = $mysqli1->prepare($config_query);
    if ($config_stmt) {
        $config_stmt->bind_param("si", $selected_subject, $semester_id);
        $config_stmt->execute();
        $config_result = $config_stmt->get_result();
        $arabic_names = [
            1 => 'اختبار نهائي',
            2 => 'اختبار نصف الفصل',
            3 => 'أعمال سنة',
            4 => 'ورش',
            5 => 'عملي'
        ];
        while ($row = $config_result->fetch_assoc()) {
            $row['name_ar'] = $arabic_names[$row['assessment_id']] ?? $row['name'];
            $assessment_configs[] = $row;
            $total_weight += $row['weight'];
        }
        $config_stmt->close();
    }
}

// Get students for selected subject
$students_data = [];
if ($has_search && $selected_subject && !empty($assessment_configs) && $batch_id > 0 && $semester_id > 0) {
    $students_query = "
        SELECT DISTINCT 
            ss.student_id,
            COALESCE(s.student_name, ss.student_id) as student_name
        FROM studentsubjects ss
        LEFT JOIN students s ON ss.student_id = s.student_id AND s.deleted_at IS NULL
        WHERE ss.subjectcode = '" . $mysqli1->real_escape_string($selected_subject) . "'
        AND ss.batch_id = $batch_id
        AND ss.semester_id = $semester_id
        ORDER BY ss.student_id
    ";
    
    $students_result = $mysqli1->query($students_query);
    if ($students_result && $students_result->num_rows > 0) {
        while ($row = $students_result->fetch_assoc()) {
            $students_data[$row['student_id']] = [
                'student_id' => $row['student_id'],
                'student_name' => $row['student_name'] ?: $row['student_id'],
                'assessments' => []
            ];
        }
    }
    
    // Get existing assessments
    if (!empty($students_data)) {
        $student_ids = array_keys($students_data);
        $ids_placeholder = implode(',', array_fill(0, count($student_ids), '?'));
        $assess_query = "
            SELECT student_id, assessment_id, degree, max_degree, is_locked
            FROM student_subject_assessments
            WHERE subjectcode = ?
            AND semester_id = ?
            AND batch_id = ?
            AND student_id IN ($ids_placeholder)
        ";
        $assess_stmt = $mysqli1->prepare($assess_query);
        if ($assess_stmt) {
            $types = "sii" . str_repeat('s', count($student_ids));
            $params = array_merge([$selected_subject, $semester_id, $batch_id], $student_ids);
            $assess_stmt->bind_param($types, ...$params);
            $assess_stmt->execute();
            $assess_result = $assess_stmt->get_result();
            while ($row = $assess_result->fetch_assoc()) {
                $students_data[$row['student_id']]['assessments'][$row['assessment_id']] = [
                    'degree' => $row['degree'] ? (int)$row['degree'] : null,
                    'max_degree' => (int)$row['max_degree'],
                    'is_locked' => $row['is_locked']
                ];
            }
            $assess_stmt->close();
        }
    }
}

// Function to calculate grade based on percentage
function calculateGrade($percentage, $grades_list) {
    if ($percentage === null || $percentage === '') return null;
    
    $percentage = (float)$percentage;
    
    foreach ($grades_list as $grade) {
        if ($grade['xmin'] !== null && $grade['xmax'] !== null) {
            if ($percentage >= $grade['xmin'] && $percentage <= $grade['xmax']) {
                return $grade;
            }
        }
    }
    return null;
}

// Handle POST: Save configs
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    if (!verify_csrf($_POST['csrf_token'] ?? '')) {
        $error_message = 'طلب غير مصرح به';
    } else {
        $post_subject = $_POST['subject_code'];
        $post_semester_id = !empty($_POST['semester_id_config']) ? (int)$_POST['semester_id_config'] : null;
        $assessments = $_POST['assessments_config'] ?? [];
        
        $mysqli1->begin_transaction();
        
        try {
            $delete = $mysqli1->prepare("DELETE FROM subject_assessment_config WHERE subjectcode = ? AND (semester_id = ? OR (semester_id IS NULL AND ? IS NULL))");
            $delete->bind_param("sii", $post_subject, $post_semester_id, $post_semester_id);
            $delete->execute();
            $delete->close();
            
            foreach ($assessments as $assessment_id => $data) {
                if (empty($data['weight']) || $data['weight'] <= 0) continue;
                
                $weight = (float)$data['weight'];
                $max_degree = !empty($data['max_degree']) ? (int)$data['max_degree'] : 100;
                
                $insert = $mysqli1->prepare("INSERT INTO subject_assessment_config (subjectcode, semester_id, assessment_id, weight, max_degree, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                $insert->bind_param("siidi", $post_subject, $post_semester_id, $assessment_id, $weight, $max_degree);
                $insert->execute();
                $insert->close();
            }
            
            $mysqli1->commit();
            $success_message = "✅ تم حفظ أنظمة التقييم بنجاح";
            
            header("Location: instructor_assessments.php?college_id=$college_id&section_id=$section_id&program_id=$program_id&batch_id=$batch_id&semester_id=$semester_id&subject_code=$post_subject&search=1");
            exit();
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            $error_message = "❌ خطأ: " . $e->getMessage();
        }
    }
}

// Handle POST: Save assessments
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_assessments'])) {
    if (!verify_csrf($_POST['csrf_token'] ?? '')) {
        $error_message = 'طلب غير مصرح به';
    } else {
        $post_semester_id = (int)$_POST['semester_id'];
        $post_batch_id = (int)$_POST['batch_id'];
        $post_subject = $_POST['subject_code'];
        $post_assessments = $_POST['assessments'] ?? [];
        
        $mysqli1->begin_transaction();
        $saved_count = 0;
        
        try {
            foreach ($post_assessments as $student_id => $assessments_data) {
                foreach ($assessments_data as $assessment_id => $data) {
                    $degree = !empty($data['degree']) ? (int)$data['degree'] : null;
                    $max_degree = !empty($data['max_degree']) ? (int)$data['max_degree'] : 100;
                    
                    if ($degree === null || $degree === '') continue;
                    
                    $percentage = $max_degree > 0 ? ($degree / $max_degree) * 100 : 0;
                    
                    $weight = 0;
                    foreach ($assessment_configs as $config) {
                        if ($config['assessment_id'] == $assessment_id) {
                            $weight = (float)$config['weight'];
                            break;
                        }
                    }
                    
                    $check = $mysqli1->prepare("SELECT id FROM student_subject_assessments WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ? AND assessment_id = ?");
                    $check->bind_param("ssiii", $student_id, $post_subject, $post_semester_id, $post_batch_id, $assessment_id);
                    $check->execute();
                    $exists = $check->get_result()->num_rows > 0;
                    $check->close();
                    
                    if ($exists) {
                        $update = $mysqli1->prepare("UPDATE student_subject_assessments SET degree = ?, max_degree = ?, percentage = ?, weight = ?, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ? AND assessment_id = ?");
                        $update->bind_param("iiddssiii", $degree, $max_degree, $percentage, $weight, $student_id, $post_subject, $post_semester_id, $post_batch_id, $assessment_id);
                        $update->execute();
                        $update->close();
                    } else {
                        $insert = $mysqli1->prepare("INSERT INTO student_subject_assessments (student_id, subjectcode, semester_id, batch_id, assessment_id, degree, max_degree, percentage, weight, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                        $insert->bind_param("ssiiiiddd", $student_id, $post_subject, $post_semester_id, $post_batch_id, $assessment_id, $degree, $max_degree, $percentage, $weight);
                        $insert->execute();
                        $insert->close();
                    }
                    $saved_count++;
                }
            }
            
            $mysqli1->commit();
            $success_message = "✅ تم حفظ $saved_count تقييم بنجاح";
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            $error_message = "❌ خطأ: " . $e->getMessage();
        }
    }
}

// Handle POST: Admit grades
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admit_grades'])) {
    if (!verify_csrf($_POST['csrf_token'] ?? '')) {
        $error_message = 'طلب غير مصرح به';
    } else {
        $post_semester_id = (int)$_POST['semester_id'];
        $post_batch_id = (int)$_POST['batch_id'];
        $post_subject = $_POST['subject_code'];
        
        $mysqli1->begin_transaction();
        
        try {
            $calc_query = "
                SELECT 
                    ssa.student_id,
                    SUM((ssa.degree / ssa.max_degree) * ssa.weight) as weighted_percentage
                FROM student_subject_assessments ssa
                WHERE ssa.subjectcode = ?
                AND ssa.semester_id = ?
                AND ssa.batch_id = ?
                GROUP BY ssa.student_id
            ";
            
            $calc_stmt = $mysqli1->prepare($calc_query);
            $calc_stmt->bind_param("sii", $post_subject, $post_semester_id, $post_batch_id);
            $calc_stmt->execute();
            $calc_result = $calc_stmt->get_result();
            
            while ($row = $calc_result->fetch_assoc()) {
                $student_id = $row['student_id'];
                $total_percentage = $row['weighted_percentage'];
                
                // Calculate grade based on percentage
                $grade_info = calculateGrade($total_percentage, $grades_list);
                $grade = $grade_info ? $grade_info['grade'] : 'F';
                $grade_id = $grade_info ? $grade_info['id'] : null;
                $grade_weight = $grade_info ? $grade_info['weight'] : 0;
                
                // Update studentsubjects table
                $update = $mysqli1->prepare("
                    UPDATE studentsubjects 
                    SET degree = ?, grade = ?, grade_id = ?, weight = ?, isapproved = ?, updated_at = NOW()
                    WHERE student_id = ? 
                    AND subjectcode = ? 
                    AND semester_id = ? 
                    AND batch_id = ?
                ");
                $degree_value = round($total_percentage, 2);
                $isapproved = ($grade_weight >= 2) ? 1 : 0; // Assuming weight >= 2 is pass
                $update->bind_param("dsiddssii", $degree_value, $grade, $grade_id, $grade_weight, $isapproved, $student_id, $post_subject, $post_semester_id, $post_batch_id);
                $update->execute();
                $update->close();
            }
            $calc_stmt->close();
            
            // Lock all assessments for this subject
            $lock = $mysqli1->prepare("
                UPDATE student_subject_assessments 
                SET is_locked = 1, approved_by = ?, approved_at = NOW()
                WHERE subjectcode = ? AND semester_id = ? AND batch_id = ?
            ");
            $lock->bind_param("isii", $instructor_id, $post_subject, $post_semester_id, $post_batch_id);
            $lock->execute();
            $lock->close();
            
            $mysqli1->commit();
            $success_message = "✅ تم اعتماد الدرجات النهائية بنجاح";
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            $error_message = "❌ خطأ: " . $e->getMessage();
        }
    }
}

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>نظام تقييم المواد - جامعة المناقل</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        * {
            font-family: 'Cairo', 'Tahoma', 'Segoe UI', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #667eea20 0%, #764ba220 100%);
            min-height: 100vh;
            direction: rtl;
        }
        
        /* Main Header */
        .main-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 30px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            position: relative;
            overflow: hidden;
        }
        
        .main-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: pulse 4s ease-in-out infinite;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 0.5; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
        
        .main-header h2 {
            font-weight: 800;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }
        
        .main-header p {
            opacity: 0.95;
            position: relative;
            z-index: 1;
        }
        
        .back-link {
            position: relative;
            z-index: 1;
            display: inline-block;
            color: rgba(255,255,255,0.9);
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .back-link:hover {
            color: white;
            transform: translateX(-5px);
        }
        
        /* Cards */
        .step-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }
        
        .step-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.15);
        }
        
        .step-title {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 15px 25px;
            margin: -25px -25px 25px -25px;
            border-radius: 20px 20px 0 0;
            font-weight: 700;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .step-title i {
            font-size: 1.4rem;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            font-size: 0.9rem;
        }
        
        .form-control, .form-select {
            border-radius: 12px;
            border: 2px solid #e1e5ed;
            padding: 10px 15px;
            transition: all 0.3s ease;
            font-size: 0.95rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        /* Buttons */
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            border-radius: 12px;
            padding: 12px 35px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            border: none;
            border-radius: 12px;
            padding: 12px 35px;
            font-weight: 600;
        }
        
        .btn-save {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            border: none;
            border-radius: 12px;
            padding: 12px 35px;
            font-weight: 700;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 176, 155, 0.4);
        }
        
        .btn-admit {
            background: linear-gradient(135deg, #f093fb, #f5576c);
            border: none;
            border-radius: 12px;
            padding: 12px 35px;
            font-weight: 700;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-admit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(245, 87, 108, 0.4);
        }
        
        .btn-config {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            border-radius: 12px;
            padding: 12px 35px;
            font-weight: 700;
            color: white;
        }
        
        .btn-dashboard {
            background: linear-gradient(135deg, #11998e, #38ef7d);
            border: none;
            border-radius: 12px;
            padding: 10px 25px;
            font-weight: 600;
            color: white;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }
        
        .btn-dashboard:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(56, 239, 125, 0.4);
            color: white;
        }
        
        /* Badges */
        .weight-badge {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            display: inline-block;
            margin-top: 5px;
        }
        
        .grade-badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 700;
            min-width: 50px;
            text-align: center;
        }
        
        .grade-A { background: linear-gradient(135deg, #28a745, #20c997); color: white; }
        .grade-B { background: linear-gradient(135deg, #17a2b8, #00bcd4); color: white; }
        .grade-C { background: linear-gradient(135deg, #ffc107, #ff9800); color: #333; }
        .grade-D { background: linear-gradient(135deg, #fd7e14, #f39c12); color: white; }
        .grade-F { background: linear-gradient(135deg, #dc3545, #c82333); color: white; }
        
        /* Tables */
        .table {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .table thead th {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            font-weight: 600;
            padding: 12px;
            border: none;
            font-size: 14px;
        }
        
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(102, 126, 234, 0.05);
        }
        
        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.85);
            backdrop-filter: blur(5px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-content {
            background: white;
            padding: 30px 50px;
            border-radius: 20px;
            text-align: center;
            animation: fadeInUp 0.3s ease;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .spinner-custom {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Alert customization */
        .alert {
            border-radius: 15px;
            border: none;
            padding: 15px 20px;
        }
        
        .alert-info {
            background: linear-gradient(135deg, #d1ecf1, #bee5eb);
            color: #0c5460;
        }
        
        .alert-warning {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            color: #856404;
        }
        
        /* Required field star */
        .required::after {
            content: " *";
            color: #dc3545;
            font-weight: bold;
        }
        
        /* Filter group */
        .filter-group {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        .filter-group:hover {
            background: #f1f3f5;
        }
        
        /* Degree input */
        .degree-input {
            width: 80px;
            text-align: center;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
        }
        
        /* Total cell */
        .total-cell {
            font-size: 16px;
            font-weight: 800;
            border-radius: 10px;
            transition: all 0.3s ease;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .degree-input {
                width: 60px;
                font-size: 12px;
            }
            
            .btn-save, .btn-admit, .btn-config {
                padding: 8px 20px;
                font-size: 14px;
            }
            
            .step-title {
                font-size: 1rem;
            }
            
            .table thead th {
                font-size: 11px;
                padding: 8px;
            }
        }
        
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
        }
        
        kbd {
            background: linear-gradient(135deg, #2d3748, #1a202c);
            border-radius: 5px;
            padding: 3px 8px;
            font-size: 11px;
            font-weight: 700;
            color: white;
            box-shadow: 0 1px 2px rgba(0,0,0,0.2);
            display: inline-block;
            min-width: 28px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="spinner-custom"></div>
            <p class="mt-3 mb-0 fw-bold">جاري المعالجة...</p>
            <p class="text-muted small">يرجى الانتظار</p>
        </div>
    </div>

    <div class="container-fluid py-4">
        <!-- Main Header -->
        <div class="main-header">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2><i class="fas fa-chalkboard-teacher me-2"></i> نظام تقييم المواد</h2>
                    <p class="mb-0">إدارة أنظمة التقييم ودرجات المواد الدراسية بكل سهولة واحترافية</p>
                </div>
                <a href="admin_dashboard.php" class="btn-dashboard">
                    <i class="fas fa-tachometer-alt me-2"></i>
                    الذهاب إلى لوحة التحكم
                </a>
            </div>
        </div>

        <!-- Filter Section - Step by Step -->
        <div class="step-card">
            <div class="step-title">
                <i class="fas fa-filter"></i>
                <span>فلتر البحث - حدد البيانات التالية خطوة بخطوة</span>
            </div>
            
            <form method="GET" id="filterForm" class="mt-3">
                <input type="hidden" name="search" value="1">
                
                <!-- Step 1: College -->
                <div class="filter-group">
                    <label class="form-label required mb-2">
                        <i class="fas fa-university text-primary me-1"></i> الخطوة 1: الكلية
                    </label>
                    <select name="college_id" class="form-select" id="college_id" required>
                        <option value="">-- اختر الكلية --</option>
                        <?php foreach($colleges as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= $college_id == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Step 2: Section -->
                <div class="filter-group" id="sectionGroup" style="<?= !$college_id ? 'display:none' : '' ?>">
                    <label class="form-label required mb-2">
                        <i class="fas fa-building text-success me-1"></i> الخطوة 2: القسم
                    </label>
                    <select name="section_id" class="form-select" id="section_id" required>
                        <option value="">-- اختر القسم --</option>
                        <?php foreach($sections as $sec): ?>
                            <option value="<?= $sec['id'] ?>" <?= $section_id == $sec['id'] ? 'selected' : '' ?>><?= htmlspecialchars($sec['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Step 3: Program -->
                <div class="filter-group" id="programGroup" style="<?= !$section_id ? 'display:none' : '' ?>">
                    <label class="form-label required mb-2">
                        <i class="fas fa-graduation-cap text-info me-1"></i> الخطوة 3: البرنامج
                    </label>
                    <select name="program_id" class="form-select" id="program_id" required>
                        <option value="">-- اختر البرنامج --</option>
                        <?php foreach($programs as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= $program_id == $p['id'] ? 'selected' : '' ?>><?= htmlspecialchars($p['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Step 4: Batch & Semester -->
                <div class="row" id="batchSemesterGroup" style="<?= !$program_id ? 'display:none' : '' ?>">
                    <div class="col-md-6">
                        <div class="filter-group">
                            <label class="form-label required mb-2">
                                <i class="fas fa-calendar-alt text-warning me-1"></i> الخطوة 4: الدفعة
                            </label>
                            <select name="batch_id" class="form-select" id="batch_id" required>
                                <option value="">-- اختر الدفعة --</option>
                                <?php foreach($batches as $b): ?>
                                    <option value="<?= $b['id'] ?>" <?= $batch_id == $b['id'] ? 'selected' : '' ?>><?= htmlspecialchars($b['value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="filter-group">
                            <label class="form-label required mb-2">
                                <i class="fas fa-calendar-week text-danger me-1"></i> الفصل الدراسي
                            </label>
                            <select name="semester_id" class="form-select" id="semester_id" required>
                                <option value="">-- اختر الفصل --</option>
                                <?php foreach($semesters as $s): ?>
                                    <option value="<?= $s['id'] ?>" <?= $semester_id == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Step 5: Subject -->
                <div class="filter-group" id="subjectGroup" style="<?= (!$batch_id || !$semester_id) ? 'display:none' : '' ?>">
                    <label class="form-label required mb-2">
                        <i class="fas fa-book text-dark me-1"></i> الخطوة 5: المادة
                    </label>
                    <select name="subject_code" class="form-select" id="subject_code" required>
                        <option value="">-- اختر المادة --</option>
                        <?php foreach($subjects_list as $code => $name): ?>
                            <option value="<?= htmlspecialchars($code) ?>" <?= $selected_subject == $code ? 'selected' : '' ?>>
                                <?= htmlspecialchars($code) ?> - <?= htmlspecialchars($name) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if($batch_id && $semester_id && empty($subjects_list)): ?>
                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-exclamation-triangle me-2"></i> 
                            لا توجد مواد مسجلة للدفعة <?= $batch_id ?> والفصل <?= $semester_id ?>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg px-5" id="searchBtn" <?= empty($subjects_list) ? 'disabled' : '' ?>>
                        <i class="fas fa-search me-2"></i> عرض التقييمات
                    </button>
                    <a href="instructor_assessments.php" class="btn btn-secondary btn-lg px-5 ms-3">
                        <i class="fas fa-redo me-2"></i> إعادة تعيين
                    </a>
                </div>
            </form>
        </div>

        <?php if ($selected_subject && $has_search && !empty($subjects_list)): ?>
        
        <!-- Assessment Configuration Section -->
        <div class="step-card">
            <div class="step-title">
                <i class="fas fa-cog"></i>
                <span>إعداد أنظمة التقييم للمادة: <?= htmlspecialchars($selected_subject) ?></span>
            </div>
            <p class="text-muted mb-4">
                <i class="fas fa-info-circle me-1"></i> 
                قم بتحديد نسب وأوزان كل نوع من أنواع التقييم (يجب أن يكون المجموع 100%)
            </p>
            
            <form method="POST" id="configForm">
                <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                <input type="hidden" name="subject_code" value="<?= htmlspecialchars($selected_subject) ?>">
                <input type="hidden" name="save_config" value="1">
                <input type="hidden" name="semester_id_config" value="<?= $semester_id ?>">
                
                <div class="table-responsive">
                    <table class="table table-bordered align-middle">
                        <thead>
                            <tr style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">
                                <th width="40%">نوع التقييم</th>
                                <th width="30%">النسبة المئوية (%)</th>
                                <th width="30%">الدرجة العظمى</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($assessment_types as $type): ?>
                                <?php 
                                $config = null;
                                foreach($assessment_configs as $cfg) {
                                    if($cfg['assessment_id'] == $type['id']) { 
                                        $config = $cfg; 
                                        break; 
                                    }
                                }
                                ?>
                                <tr>
                                    <td>
                                        <i class="fas fa-check-circle text-success me-2"></i>
                                        <strong><?= htmlspecialchars($type['name_ar']) ?></strong>
                                        <br><small class="text-muted"><?= htmlspecialchars($type['name']) ?></small>
                                    </td>
                                    <td>
                                        <div class="input-group" style="width: 150px; margin: 0 auto;">
                                            <input type="number" 
                                                   name="assessments_config[<?= $type['id'] ?>][weight]" 
                                                   class="form-control text-center weight-input" 
                                                   value="<?= $config['weight'] ?? 0 ?>" 
                                                   step="0.5" 
                                                   min="0" 
                                                   max="100">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="input-group" style="width: 150px; margin: 0 auto;">
                                            <input type="number" 
                                                   name="assessments_config[<?= $type['id'] ?>][max_degree]" 
                                                   class="form-control text-center" 
                                                   value="<?= $config['max_degree'] ?? 100 ?>" 
                                                   step="1" 
                                                   min="0">
                                            <span class="input-group-text">درجة</span>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="table-info">
                                <td colspan="2" class="text-end fw-bold">
                                    <i class="fas fa-calculator me-1"></i> المجموع الكلي للنسب:
                                </td>
                                <td class="fw-bold">
                                    <span id="totalWeightDisplay" class="badge bg-secondary fs-6 px-3 py-2">0%</span>
                                    <span id="weightWarning" class="text-danger ms-2" style="display: none;">
                                        <i class="fas fa-exclamation-circle"></i> يجب أن يكون المجموع 100%
                                    </span>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                
                <div class="text-center mt-3">
                    <button type="submit" class="btn btn-config btn-lg px-5" onclick="return validateWeights()">
                        <i class="fas fa-save me-2"></i> حفظ أنظمة التقييم
                    </button>
                </div>
            </form>
        </div>

        <!-- Student Assessments Section -->
        <?php if (!empty($assessment_configs) && !empty($students_data)): ?>
        <div class="step-card">
            <div class="step-title">
                <i class="fas fa-edit"></i>
                <span>إدخال درجات الطلاب</span>
            </div>
            
            <div class="alert alert-info mb-4">
                <i class="fas fa-users me-2"></i>
                عدد الطلاب المسجلين: <strong><?= count($students_data) ?></strong> طالب
                <i class="fas fa-book me-3"></i>
                المادة: <strong><?= htmlspecialchars($selected_subject) ?></strong>
                <i class="fas fa-calendar me-3"></i>
                الفصل: <strong><?= $semester_id ?></strong>
            </div>
            
            <form method="POST" id="assessmentForm">
                <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                <input type="hidden" name="semester_id" value="<?= $semester_id ?>">
                <input type="hidden" name="batch_id" value="<?= $batch_id ?>">
                <input type="hidden" name="subject_code" value="<?= htmlspecialchars($selected_subject) ?>">
                
                <div class="table-responsive" style="max-height: 600px; overflow-y: auto; border-radius: 15px;">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">
                                <th rowspan="2" width="5%">#</th>
                                <th rowspan="2" width="15%">رقم الطالب</th>
                                <th rowspan="2" width="20%">اسم الطالب</th>
                                <?php foreach($assessment_configs as $config): ?>
                                    <th colspan="2" class="text-center">
                                        <?= htmlspecialchars($config['name_ar']) ?>
                                        <span class="weight-badge"><?= $config['weight'] ?>%</span>
                                    </th>
                                <?php endforeach; ?>
                                <th rowspan="2" width="12%">النسبة النهائية</th>
                                <th rowspan="2" width="10%">التقدير</th>
                            </tr>
                            <tr style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">
                                <?php foreach($assessment_configs as $config): ?>
                                    <th width="10%">الدرجة</th>
                                    <th width="10%">العظمى</th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach($students_data as $student): ?>
                                <?php 
                                $is_locked = false;
                                foreach($student['assessments'] as $assess) {
                                    if (!empty($assess['is_locked'])) $is_locked = true;
                                }
                                
                                // Calculate final percentage for display
                                $final_percentage = 0;
                                $total_weight_used = 0;
                                foreach($assessment_configs as $config) {
                                    $saved = $student['assessments'][$config['assessment_id']] ?? null;
                                    if ($saved && $saved['degree'] !== null && $saved['degree'] > 0) {
                                        $degree = (int)$saved['degree'];
                                        $max_degree = (int)($saved['max_degree'] ?? $config['max_degree']);
                                        $percentage = $max_degree > 0 ? ($degree / $max_degree) * 100 : 0;
                                        $weight = (float)$config['weight'];
                                        $final_percentage += ($percentage * $weight) / 100;
                                        $total_weight_used += $weight;
                                    }
                                }
                                $final_percentage = $total_weight_used > 0 ? round($final_percentage) : 0;
                                $grade_info = calculateGrade($final_percentage, $grades_list);
                                $grade_display = $grade_info ? $grade_info['grade'] : '--';
                                $grade_class = '';
                                if ($grade_display == 'A+' || $grade_display == 'A') $grade_class = 'grade-A';
                                elseif ($grade_display == 'B+' || $grade_display == 'B') $grade_class = 'grade-B';
                                elseif ($grade_display == 'C+' || $grade_display == 'C') $grade_class = 'grade-C';
                                elseif ($grade_display == 'D+' || $grade_display == 'D') $grade_class = 'grade-D';
                                elseif ($grade_display == 'F') $grade_class = 'grade-F';
                                ?>
                                <tr class="<?= $is_locked ? 'table-secondary' : '' ?>">
                                    <td><strong><?= $counter++ ?></strong></td>
                                    <td><?= htmlspecialchars($student['student_id']) ?></td>
                                    <td class="text-end fw-bold"><?= htmlspecialchars($student['student_name']) ?></td>
                                    <?php foreach($assessment_configs as $config): ?>
                                        <?php 
                                        $saved = $student['assessments'][$config['assessment_id']] ?? null;
                                        $degree = $saved['degree'] ?? '';
                                        $max_degree = (int)($saved['max_degree'] ?? $config['max_degree']);
                                        $locked = $saved['is_locked'] ?? 0;
                                        ?>
                                        <td>
                                            <input type="number" 
                                                   name="assessments[<?= $student['student_id'] ?>][<?= $config['assessment_id'] ?>][degree]"
                                                   class="form-control degree-input degree-field text-center"
                                                   value="<?= $degree ?>"
                                                   step="1"
                                                   min="0"
                                                   max="<?= $max_degree ?>"
                                                   data-max="<?= $max_degree ?>"
                                                   data-weight="<?= $config['weight'] ?>"
                                                   data-student="<?= $student['student_id'] ?>"
                                                   data-assessment="<?= $config['assessment_id'] ?>"
                                                   <?= ($locked || $is_locked) ? 'disabled readonly' : '' ?>
                                                   oninput="calculateStudentTotal(this)">
                                        </td>
                                        <td>
                                            <input type="number" 
                                                   class="form-control text-center"
                                                   value="<?= $max_degree ?>"
                                                   step="1"
                                                   min="0"
                                                   style="width: 70px;"
                                                   <?= ($locked || $is_locked) ? 'disabled' : '' ?>
                                                   onchange="updateMaxDegree(this, '<?= $student['student_id'] ?>', '<?= $config['assessment_id'] ?>')">
                                        </td>
                                    <?php endforeach; ?>
                                    <td class="total-weighted fw-bold text-center total-cell" style="font-size: 18px;"><?= $final_percentage ?>%</td>
                                    <td class="text-center">
                                        <span class="grade-badge <?= $grade_class ?>"><?= $grade_display ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <div class="text-center mt-4">
                    <button type="submit" name="save_assessments" class="btn-save btn-lg px-5" id="saveBtn">
                        <i class="fas fa-save me-2"></i> حفظ التقييمات
                    </button>
                    <button type="button" class="btn-admit btn-lg px-5 ms-3" id="admitBtn" onclick="confirmAdmit()">
                        <i class="fas fa-check-circle me-2"></i> اعتماد الدرجات النهائية
                    </button>
                </div>
            </form>
        </div>
        
        <div class="alert alert-info">
            <i class="fas fa-lightbulb me-2"></i>
            <strong>إرشادات مهمة:</strong>
            <ul class="mb-0 mt-2">
                <li>تأكد من أن مجموع النسب المئوية = 100% قبل حفظ التقييمات</li>
                <li>يتم احتساب النسبة النهائية وتقدير المادة تلقائياً عند إدخال الدرجات</li>
                <li>يمكنك استخدام مفتاح <kbd>Ctrl + S</kbd> لحفظ التقييمات بسرعة</li>
                <li>بعد الاعتماد، سيتم قفل التقييمات ولن يمكن تعديلها</li>
                <li>التقدير يتم حسابه بناءً على النسبة المئوية وفقاً لنظام التقييم المعتمد</li>
            </ul>
        </div>
        
        <?php elseif (!empty($assessment_configs) && empty($students_data)): ?>
        <div class="alert alert-warning text-center py-5">
            <i class="fas fa-users-slash fa-4x mb-3 d-block"></i>
            <h4 class="mb-2">لا يوجد طلاب مسجلين في هذه المادة</h4>
            <p class="mb-0">يرجى التأكد من أن الطلاب مسجلين للمادة في هذا الفصل الدراسي</p>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

    <script>
    // Grade ranges from database
    const gradeRanges = <?= json_encode($grades_list) ?>;
    
    // Function to calculate grade based on percentage
    function calculateGradeByPercentage(percentage) {
        if (percentage === null || percentage === '' || isNaN(percentage)) return null;
        
        const percentNum = parseFloat(percentage);
        
        for (let grade of gradeRanges) {
            if (grade.xmin !== null && grade.xmax !== null) {
                if (percentNum >= grade.xmin && percentNum <= grade.xmax) {
                    return grade;
                }
            }
        }
        return null;
    }
    
    // Load sections based on college
    $('#college_id').on('change', function() {
        var collegeId = $(this).val();
        if (collegeId) {
            $('#loadingOverlay').fadeIn();
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(data) {
                    var options = '<option value="">-- اختر القسم --</option>';
                    if (data && data.length > 0) {
                        $.each(data, function(i, section) {
                            options += '<option value="' + section.id + '">' + section.name + '</option>';
                        });
                        $('#section_id').prop('disabled', false);
                        $('#sectionGroup').fadeIn();
                    } else {
                        options += '<option value="" disabled>لا توجد أقسام</option>';
                        $('#section_id').prop('disabled', true);
                        $('#sectionGroup').fadeIn();
                    }
                    $('#section_id').html(options);
                    $('#loadingOverlay').fadeOut();
                },
                error: function() {
                    $('#section_id').html('<option value="">خطأ في تحميل الأقسام</option>');
                    $('#section_id').prop('disabled', false);
                    $('#loadingOverlay').fadeOut();
                }
            });
        } else {
            $('#sectionGroup, #programGroup, #batchSemesterGroup, #subjectGroup').hide();
            $('#section_id').html('<option value="">-- اختر القسم --</option>');
        }
        
        // Reset dependent fields
        $('#program_id').val('');
        $('#batch_id').val('');
        $('#semester_id').val('');
        $('#subject_code').html('<option value="">-- اختر المادة --</option>');
        $('#searchBtn').prop('disabled', true);
    });
    
    // Show program group when section is selected
    $('#section_id').on('change', function() {
        if ($(this).val()) {
            $('#programGroup').fadeIn();
        } else {
            $('#programGroup, #batchSemesterGroup, #subjectGroup').hide();
        }
    });
    
    // Show batch/semester group when program is selected
    $('#program_id').on('change', function() {
        if ($(this).val()) {
            $('#batchSemesterGroup').fadeIn();
        } else {
            $('#batchSemesterGroup, #subjectGroup').hide();
        }
    });
    
    // Auto-submit when batch and semester are selected to load subjects
    $('#batch_id, #semester_id').on('change', function() {
        var batch = $('#batch_id').val();
        var semester = $('#semester_id').val();
        var college = $('#college_id').val();
        var section = $('#section_id').val();
        var program = $('#program_id').val();
        
        if (batch && semester && college && section && program) {
            $('#loadingOverlay').fadeIn();
            window.location.href = 'instructor_assessments.php?college_id=' + college + 
                '&section_id=' + section + 
                '&program_id=' + program + 
                '&batch_id=' + batch + 
                '&semester_id=' + semester;
        }
    });
    
    // Enable search button when subject is selected
    $('#subject_code').on('change', function() {
        if ($(this).val()) {
            $('#searchBtn').prop('disabled', false);
        } else {
            $('#searchBtn').prop('disabled', true);
        }
    });
    
    // Calculate total weight
    function updateTotalWeight() {
        var total = 0;
        $('input[name$="[weight]"]').each(function() {
            total += parseFloat($(this).val()) || 0;
        });
        var displaySpan = $('#totalWeightDisplay');
        if (total == 100) {
            displaySpan.removeClass('bg-danger').addClass('bg-success').text(total + '%');
            $('#weightWarning').fadeOut();
            $('#saveBtn, #admitBtn').prop('disabled', false);
        } else {
            displaySpan.removeClass('bg-success').addClass('bg-danger').text(total + '%');
            $('#weightWarning').fadeIn();
            $('#saveBtn, #admitBtn').prop('disabled', true);
        }
        return total;
    }
    
    // Validate weights before saving config
    function validateWeights() {
        var total = updateTotalWeight();
        if (total != 100) {
            alert('⚠️ مجموع النسب المئوية يجب أن يكون 100% (الحالي: ' + total + '%)');
            return false;
        }
        $('#loadingOverlay').fadeIn();
        return true;
    }
    
    // Calculate student total and update grade
    function calculateStudentTotal(input) {
        var row = $(input).closest('tr');
        var totalWeighted = 0;
        var totalWeight = 0;
        
        row.find('.degree-field').each(function() {
            var degree = parseInt($(this).val()) || 0;
            var maxDegree = parseInt($(this).data('max')) || 100;
            var weight = parseFloat($(this).data('weight')) || 0;
            var percentage = maxDegree > 0 ? (degree / maxDegree) * 100 : 0;
            totalWeighted += (percentage * weight) / 100;
            totalWeight += weight;
        });
        
        var finalPercentage = totalWeight > 0 ? Math.round(totalWeighted) : 0;
        var totalCell = row.find('.total-weighted');
        totalCell.text(finalPercentage + '%');
        
        // Calculate grade
        var gradeInfo = calculateGradeByPercentage(finalPercentage);
        var gradeDisplay = gradeInfo ? gradeInfo.grade : '--';
        var gradeCell = row.find('.grade-badge');
        
        if (gradeCell.length) {
            gradeCell.text(gradeDisplay);
            // Update grade class
            gradeCell.removeClass('grade-A grade-B grade-C grade-D grade-F');
            if (gradeDisplay == 'A+' || gradeDisplay == 'A') gradeCell.addClass('grade-A');
            else if (gradeDisplay == 'B+' || gradeDisplay == 'B') gradeCell.addClass('grade-B');
            else if (gradeDisplay == 'C+' || gradeDisplay == 'C') gradeCell.addClass('grade-C');
            else if (gradeDisplay == 'D+' || gradeDisplay == 'D') gradeCell.addClass('grade-D');
            else if (gradeDisplay == 'F') gradeCell.addClass('grade-F');
        }
        
        // Color coding based on percentage
        if (finalPercentage >= 60) {
            totalCell.css({'background': '#d4edda', 'color': '#155724'});
        } else if (finalPercentage >= 50) {
            totalCell.css({'background': '#fff3cd', 'color': '#856404'});
        } else {
            totalCell.css({'background': '#f8d7da', 'color': '#721c24'});
        }
    }
    
    // Update max degree
    function updateMaxDegree(input, studentId, assessmentId) {
        var newMax = parseInt($(input).val()) || 100;
        var row = $(input).closest('tr');
        var degreeInput = row.find('.degree-field').filter(function() {
            return $(this).data('assessment') == assessmentId;
        });
        degreeInput.data('max', newMax);
        degreeInput.attr('max', newMax);
        
        var currentDegree = parseInt(degreeInput.val()) || 0;
        if (currentDegree > newMax) degreeInput.val(newMax);
        calculateStudentTotal(degreeInput[0]);
    }
    
    // Confirm admit
    function confirmAdmit() {
        var totalWeight = updateTotalWeight();
        if (totalWeight != 100) {
            alert('⚠️ لا يمكن اعتماد الدرجات لأن مجموع النسب المئوية (' + totalWeight + '%) لا يساوي 100%');
            return false;
        }
        
        if (confirm('⚠️ تأكيد احتساب واعتماد الدرجات النهائية\n\nسيتم:\n• حساب النسبة المئوية المرجحة لكل طالب\n• احتساب التقدير المناسب وفقاً لنظام التقييم\n• تحديث جدول studentsubjects\n• قفل التقييمات لمنع التعديل\n\nهل أنت متأكد؟')) {
            $('#loadingOverlay').fadeIn();
            $('<input>').attr({type: 'hidden', name: 'admit_grades', value: '1'}).appendTo('#assessmentForm');
            $('#assessmentForm').submit();
        }
    }
    
    $(document).ready(function() {
        updateTotalWeight();
        
        $('input[name$="[weight]"]').on('input', updateTotalWeight);
        
        $('.degree-field').each(function() { 
            calculateStudentTotal(this); 
        });
        
        // Show/hide groups based on selected values
        <?php if($college_id): ?>
            $('#sectionGroup').show();
            <?php if($section_id): ?>
                $('#programGroup').show();
                <?php if($program_id): ?>
                    $('#batchSemesterGroup').show();
                    <?php if($batch_id && $semester_id): ?>
                        $('#subjectGroup').show();
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif; ?>
        <?php endif; ?>
        
        // Form submit handlers
        $('#configForm').on('submit', function() {
            if (!validateWeights()) return false;
            $('#loadingOverlay').fadeIn();
        });
        
        $('#assessmentForm').on('submit', function() {
            if (updateTotalWeight() != 100) {
                alert('⚠️ يجب أن يكون مجموع النسب المئوية 100% قبل حفظ التقييمات');
                return false;
            }
            $('#loadingOverlay').fadeIn();
        });
        
        // Ctrl+S shortcut
        $(document).on('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                if ($('.degree-field').length > 0 && confirm('حفظ التقييمات؟')) {
                    $('button[name="save_assessments"]').click();
                }
            }
        });
    });
    </script>
    
    <?php if ($success_message): ?>
    <script>
        alert('<?= addslashes($success_message) ?>');
        <?php if (strpos($success_message, 'اعتماد') !== false): ?>
        setTimeout(function() { location.reload(); }, 2000);
        <?php endif; ?>
    </script>
    <?php endif; ?>
    <?php if ($error_message): ?>
    <script>alert('<?= addslashes($error_message) ?>');</script>
    <?php endif; ?>
</body>
</html>