<?php
// instructor_assessments.php - COMPACT FILTER VERSION
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 
            ss.subjectcode,
            sub.subjectnamea as subject_name
        FROM studentsubjects ss
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        WHERE ss.batch_id = $batch_id 
        AND ss.semester_id = $semester_id
        ORDER BY sub.subjectnamea, ss.subjectcode
    ";
    
    $subj_result = $mysqli1->query($subj_query);
    if ($subj_result && $subj_result->num_rows > 0) {
        while ($row = $subj_result->fetch_assoc()) {
            $display_name = !empty($row['subject_name']) ? $row['subject_name'] : $row['subjectcode'];
            $subjects_list[$row['subjectcode']] = $display_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;
                $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: 20px 30px;
            border-radius: 15px;
            margin-bottom: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .main-header h2 {
            font-weight: 800;
            margin-bottom: 5px;
            font-size: 1.5rem;
        }
        
        .main-header p {
            opacity: 0.9;
            font-size: 0.85rem;
            margin-bottom: 0;
        }
        
        /* Filter Bar - Compact */
        .filter-bar {
            background: white;
            border-radius: 15px;
            padding: 15px 20px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        }
        
        .filter-label {
            font-size: 0.75rem;
            font-weight: 600;
            color: #6c757d;
            margin-bottom: 4px;
            display: block;
        }
        
        .filter-select {
            font-size: 0.85rem;
            padding: 6px 10px;
            border-radius: 10px;
            border: 1px solid #dee2e6;
            width: 100%;
            background-color: white;
        }
        
        .filter-select:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }
        
        /* Cards */
        .content-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        }
        
        .card-title {
            font-weight: 700;
            font-size: 1.1rem;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
            display: inline-block;
        }
        
        /* Buttons */
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            border-radius: 10px;
            padding: 8px 20px;
            font-weight: 600;
            font-size: 0.85rem;
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            border: none;
            border-radius: 10px;
            padding: 8px 20px;
            font-weight: 600;
            font-size: 0.85rem;
        }
        
        .btn-save {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            border: none;
            border-radius: 10px;
            padding: 10px 25px;
            font-weight: 700;
            color: white;
            font-size: 0.85rem;
        }
        
        .btn-admit {
            background: linear-gradient(135deg, #f093fb, #f5576c);
            border: none;
            border-radius: 10px;
            padding: 10px 25px;
            font-weight: 700;
            color: white;
            font-size: 0.85rem;
        }
        
        .btn-config {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            border-radius: 10px;
            padding: 8px 20px;
            font-weight: 600;
            font-size: 0.85rem;
            color: white;
        }
        
        .btn-dashboard {
            background: linear-gradient(135deg, #11998e, #38ef7d);
            border: none;
            border-radius: 10px;
            padding: 8px 18px;
            font-weight: 600;
            font-size: 0.8rem;
            color: white;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        
        .btn-dashboard:hover {
            color: white;
            transform: translateY(-1px);
        }
        
        /* Weight Badge */
        .weight-badge {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 3px 8px;
            border-radius: 15px;
            font-size: 10px;
            font-weight: 600;
            display: inline-block;
            margin-top: 3px;
        }
        
        /* Grade Badge */
        .grade-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 700;
            min-width: 45px;
            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 {
            font-size: 0.8rem;
        }
        
        .table thead th {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            font-weight: 600;
            padding: 10px 8px;
            font-size: 0.75rem;
            white-space: nowrap;
        }
        
        .table td {
            padding: 8px;
            vertical-align: middle;
        }
        
        /* Degree Input */
        .degree-input {
            width: 65px;
            text-align: center;
            border-radius: 8px;
            border: 1px solid #dee2e6;
            padding: 4px;
            font-size: 0.75rem;
        }
        
        .total-cell {
            font-weight: 800;
            font-size: 0.85rem;
        }
        
        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-content {
            background: white;
            padding: 20px 40px;
            border-radius: 15px;
            text-align: center;
        }
        
        .spinner-custom {
            width: 40px;
            height: 40px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Alert */
        .alert {
            border-radius: 12px;
            padding: 12px 20px;
            font-size: 0.85rem;
        }
        
        /* Responsive */
        @media (max-width: 992px) {
            .filter-bar .row > div {
                margin-bottom: 10px;
            }
        }
        
        kbd {
            background: #2d3748;
            border-radius: 4px;
            padding: 2px 6px;
            font-size: 10px;
            font-weight: 700;
            color: white;
        }
        
        .table-responsive {
            border-radius: 12px;
        }
        
        .small-text {
            font-size: 0.7rem;
        }
    </style>
</head>
<body>
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="spinner-custom"></div>
            <p class="mb-0 fw-bold">جاري المعالجة...</p>
        </div>
    </div>

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

        <!-- Compact Filter Bar -->
        <div class="filter-bar">
            <form method="GET" id="filterForm">
                <input type="hidden" name="search" value="1">
                <div class="row g-2 align-items-end">
                    <div class="col-md-2 col-sm-6">
                        <label class="filter-label"><i class="fas fa-university"></i> الكلية</label>
                        <select name="college_id" class="filter-select" id="college_id">
                            <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>
                    <div class="col-md-2 col-sm-6">
                        <label class="filter-label"><i class="fas fa-building"></i> القسم</label>
                        <select name="section_id" class="filter-select" id="section_id">
                            <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>
                    <div class="col-md-2 col-sm-6">
                        <label class="filter-label"><i class="fas fa-graduation-cap"></i> البرنامج</label>
                        <select name="program_id" class="filter-select" id="program_id">
                            <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>
                    <div class="col-md-2 col-sm-6">
                        <label class="filter-label"><i class="fas fa-calendar"></i> الدفعة</label>
                        <select name="batch_id" class="filter-select" id="batch_id">
                            <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 class="col-md-2 col-sm-6">
                        <label class="filter-label"><i class="fas fa-calendar-week"></i> الفصل</label>
                        <select name="semester_id" class="filter-select" id="semester_id">
                            <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 class="col-md-2 col-sm-12">
                        <label class="filter-label"><i class="fas fa-book"></i> المادة</label>
                        <div class="d-flex gap-2">
                             <select name="subject_code" class="filter-select" id="subject_code" style="flex:1">
    <option value="">المادة</option>
    <?php foreach($subjects_list as $code => $name): ?>
        <option value="<?= htmlspecialchars($code) ?>" <?= $selected_subject == $code ? 'selected' : '' ?>>
            <?= htmlspecialchars($name) ?> (<?= htmlspecialchars($code) ?>)
        </option>
    <?php endforeach; ?>
</select>
                            <button type="submit" class="btn btn-primary" id="searchBtn" style="padding: 6px 15px; white-space: nowrap;">
                                <i class="fas fa-search"></i>
                            </button>
                            <a href="instructor_assessments.php" class="btn btn-secondary" style="padding: 6px 15px; white-space: nowrap;">
                                <i class="fas fa-redo"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <?php if ($selected_subject && $has_search && !empty($subjects_list)): ?>
        
        <!-- Assessment Configuration Section -->
        <div class="content-card">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                <h5 class="card-title mb-0"><i class="fas fa-cog"></i> إعداد التقييم: <?= htmlspecialchars($selected_subject) ?></h5>
                <span class="small-text text-muted">يجب أن يكون مجموع النسب 100%</span>
            </div>
            
            <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 table-sm">
                        <thead>
                            <tr>
                                <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>
                                        <?= htmlspecialchars($type['name_ar']) ?>
                                        <br><small class="text-muted"><?= htmlspecialchars($type['name']) ?></small>
                                    </td>
                                    <td>
                                        <div class="input-group" style="width: 120px;">
                                            <input type="number" name="assessments_config[<?= $type['id'] ?>][weight]" class="form-control form-control-sm 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: 120px;">
                                            <input type="number" name="assessments_config[<?= $type['id'] ?>][max_degree]" class="form-control form-control-sm 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">المجموع: </td>
                                <td class="fw-bold">
                                    <span id="totalWeightDisplay" class="badge bg-secondary">0%</span>
                                    <span id="weightWarning" class="text-danger ms-1 small" style="display: none;">يجب أن يكون 100%</span>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                
                <div class="text-center mt-3">
                    <button type="submit" class="btn btn-config" onclick="return validateWeights()">
                        <i class="fas fa-save me-1"></i> حفظ الإعدادات
                    </button>
                </div>
            </form>
        </div>

        <!-- Student Assessments Section -->
        <?php if (!empty($assessment_configs) && !empty($students_data)): ?>
        <div class="content-card">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                <h5 class="card-title mb-0"><i class="fas fa-edit"></i> درجات الطلاب</h5>
                <div class="small-text">
                    <span class="badge bg-info"><?= count($students_data) ?> طالب</span>
                    <span class="badge bg-secondary ms-1">المادة: <?= htmlspecialchars($selected_subject) ?></span>
                </div>
            </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: 500px; overflow-y: auto;">
                    <table class="table table-bordered table-sm table-striped">
                        <thead class="table-dark">
                            <tr>
                                <th rowspan="2" width="40">#</th>
                                <th rowspan="2" width="100">رقم الطالب</th>
                                <th rowspan="2">اسم الطالب</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="70">النسبة</th>
                                <th rowspan="2" width="60">التقدير</th>
                            </tr>
                            <tr>
                                <?php foreach($assessment_configs as $config): ?>
                                    <th width="70">الدرجة</th>
                                    <th width="60">العظمى</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;
                                }
                                
                                $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 (in_array($grade_display, ['A+', 'A'])) $grade_class = 'grade-A';
                                elseif (in_array($grade_display, ['B+', 'B'])) $grade_class = 'grade-B';
                                elseif (in_array($grade_display, ['C+', 'C'])) $grade_class = 'grade-C';
                                elseif (in_array($grade_display, ['D+', 'D'])) $grade_class = 'grade-D';
                                elseif ($grade_display == 'F') $grade_class = 'grade-F';
                                ?>
                                <tr class="<?= $is_locked ? 'table-secondary' : '' ?>">
                                    <td><?= $counter++ ?></td>
                                    <td><?= htmlspecialchars($student['student_id']) ?></td>
                                    <td class="text-end"><?= 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'] ?>"
                                                   <?= ($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: 55px; font-size: 0.7rem;"
                                                   <?= ($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"><?= $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-3">
                    <button type="submit" name="save_assessments" class="btn-save" id="saveBtn">
                        <i class="fas fa-save me-1"></i> حفظ التقييمات
                    </button>
                    <button type="button" class="btn-admit ms-2" id="admitBtn" onclick="confirmAdmit()">
                        <i class="fas fa-check-circle me-1"></i> اعتماد الدرجات
                    </button>
                </div>
            </form>
        </div>
        
        <div class="alert alert-info small">
            <i class="fas fa-lightbulb me-1"></i>
            <strong>إرشادات:</strong> مجموع النسب = 100% | <kbd>Ctrl+S</kbd> حفظ سريع | التقدير يحسب تلقائياً
        </div>
        
        <?php elseif (!empty($assessment_configs) && empty($students_data)): ?>
        <div class="content-card text-center py-4">
            <i class="fas fa-users-slash fa-3x text-muted mb-2"></i>
            <h6>لا يوجد طلاب مسجلين في هذه المادة</h6>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

    <script>
    // Grade ranges from database
    const gradeRanges = <?= json_encode($grades_list) ?>;
    
    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').html(options);
                    $('#loadingOverlay').fadeOut();
                },
                error: function() {
                    $('#section_id').html('<option value="">خطأ</option>');
                    $('#loadingOverlay').fadeOut();
                }
            });
        }
    });
    
    // Auto-submit when all filters are selected
    function checkAndSubmit() {
        var college = $('#college_id').val();
        var section = $('#section_id').val();
        var program = $('#program_id').val();
        var batch = $('#batch_id').val();
        var semester = $('#semester_id').val();
        
        if (college && section && program && batch && semester) {
            $('#loadingOverlay').fadeIn();
            window.location.href = 'instructor_assessments.php?college_id=' + college + 
                '&section_id=' + section + 
                '&program_id=' + program + 
                '&batch_id=' + batch + 
                '&semester_id=' + semester;
        }
    }
    
    $('#section_id, #program_id, #batch_id, #semester_id').on('change', checkAndSubmit);
    
    // Calculate total weight
    function updateTotalWeight() {
        var total = 0;
        $('input[name$="[weight]"]').each(function() {
            total += parseFloat($(this).val()) || 0;
        });
        $('#totalWeightDisplay').text(total + '%').removeClass('bg-success bg-danger').addClass(total == 100 ? 'bg-success' : 'bg-danger');
        $('#weightWarning').toggle(total != 100);
        $('#saveBtn, #admitBtn').prop('disabled', total != 100);
        return total;
    }
    
    function validateWeights() {
        if (updateTotalWeight() != 100) {
            alert('⚠️ مجموع النسب المئوية يجب أن يكون 100%');
            return false;
        }
        $('#loadingOverlay').fadeIn();
        return true;
    }
    
    // Calculate student total
    function calculateStudentTotal(input) {
        var row = $(input).closest('tr');
        var totalWeighted = 0, 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;
        row.find('.total-weighted').text(finalPercentage + '%');
        
        var gradeInfo = calculateGradeByPercentage(finalPercentage);
        var gradeDisplay = gradeInfo ? gradeInfo.grade : '--';
        var gradeSpan = row.find('.grade-badge');
        gradeSpan.text(gradeDisplay);
        gradeSpan.removeClass('grade-A grade-B grade-C grade-D grade-F');
        if (gradeDisplay == 'A+' || gradeDisplay == 'A') gradeSpan.addClass('grade-A');
        else if (gradeDisplay == 'B+' || gradeDisplay == 'B') gradeSpan.addClass('grade-B');
        else if (gradeDisplay == 'C+' || gradeDisplay == 'C') gradeSpan.addClass('grade-C');
        else if (gradeDisplay == 'D+' || gradeDisplay == 'D') gradeSpan.addClass('grade-D');
        else if (gradeDisplay == 'F') gradeSpan.addClass('grade-F');
    }
    
    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).attr('name').indexOf('[' + assessmentId + ']') > -1;
        });
        degreeInput.data('max', newMax).attr('max', newMax);
        if (parseInt(degreeInput.val()) > newMax) degreeInput.val(newMax);
        calculateStudentTotal(degreeInput[0]);
    }
    
    function confirmAdmit() {
        if (updateTotalWeight() != 100) {
            alert('⚠️ مجموع النسب المئوية يجب أن يكون 100%');
            return;
        }
        if (confirm('⚠️ تأكيد اعتماد الدرجات النهائية؟\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); });
        
        $('#configForm').on('submit', function() { if (!validateWeights()) return false; });
        $('#assessmentForm').on('submit', function() { if (updateTotalWeight() != 100) { alert('⚠️ مجموع النسب يجب أن يكون 100%'); return false; } });
        
        $(document).on('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                if ($('.degree-field').length && confirm('حفظ التقييمات؟')) $('button[name="save_assessments"]').click();
            }
        });
        
        <?php if($college_id): ?>
            $('#college_id').trigger('change');
            <?php if($section_id && $program_id && $batch_id && $semester_id): ?>
                // Set values if they exist
            <?php endif; ?>
        <?php endif; ?>
    });
    </script>
    
</body>
</html>