<?php
// instructor_mangement.php - Complete CRUD for instructors with subject assignment
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check if user is logged in (using your existing session system)
if (!isset($_SESSION['committee_id']) && !isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Validation functions
function validateInt($input, $default = 0) {
    return isset($input) && ctype_digit((string)$input) ? (int)$input : $default;
}

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

// Handle AJAX requests
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    
    // Get subjects by college
    if ($_GET['ajax'] == 'get_subjects_by_college' && isset($_GET['college_id'])) {
        $college_id = validateInt($_GET['college_id']);
        $subjects = [];
        
        $query = "SELECT subjectcode, subjectnamea, credit_hours 
                  FROM subjects 
                  WHERE college_id = ? AND deleted_at IS NULL 
                  ORDER BY subjectcode";
        $stmt = $mysqli1->prepare($query);
        if ($stmt) {
            $stmt->bind_param("i", $college_id);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $subjects[] = $row;
            }
            $stmt->close();
        }
        echo json_encode(['success' => true, 'subjects' => $subjects]);
        exit;
    }
    
    // Get assigned subjects for instructor
    if ($_GET['ajax'] == 'get_assigned_subjects' && isset($_GET['instructor_id'])) {
        $instructor_id = validateInt($_GET['instructor_id']);
        $assigned = [];
        
        $query = "SELECT isub.*, s.subjectnamea, s.subjectnamee, s.credit_hours, c.name as college_name
                  FROM instructor_subjects isub
                  JOIN subjects s ON isub.subjectcode = s.subjectcode
                  JOIN colleges c ON s.college_id = c.id
                  WHERE isub.instructor_id = ?
                  ORDER BY c.name, s.subjectcode";
        $stmt = $mysqli1->prepare($query);
        if ($stmt) {
            $stmt->bind_param("i", $instructor_id);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $assigned[] = $row;
            }
            $stmt->close();
        }
        echo json_encode(['success' => true, 'assigned' => $assigned]);
        exit;
    }
    
    // Get students for grade entry
    if ($_GET['ajax'] == 'get_students_for_grades' && isset($_GET['subjectcode']) && isset($_GET['batch_id']) && isset($_GET['semester_id'])) {
        $subjectcode = validateString($_GET['subjectcode']);
        $batch_id = validateInt($_GET['batch_id']);
        $semester_id = validateInt($_GET['semester_id']);
        $students = [];
        
        $query = "SELECT s.student_id, s.student_name, ss.degree, ss.grade, ss.regrade, ss.reregrade, ss.isapproved,
                         ss.id as grade_id
                  FROM students s
                  LEFT JOIN studentsubjects ss ON s.student_id = ss.student_id 
                      AND ss.subjectcode = ? AND ss.batch_id = ? AND ss.semester_id = ?
                  WHERE s.batch_id = ? AND s.deleted_at IS NULL
                  ORDER BY s.student_name";
        $stmt = $mysqli1->prepare($query);
        if ($stmt) {
            $stmt->bind_param("siii", $subjectcode, $batch_id, $semester_id, $batch_id);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $students[] = $row;
            }
            $stmt->close();
        }
        echo json_encode(['success' => true, 'students' => $students]);
        exit;
    }
    
    // Save grades
    if ($_GET['ajax'] == 'save_grades') {
        $data = json_decode(file_get_contents('php://input'), true);
        $subjectcode = validateString($data['subjectcode']);
        $batch_id = validateInt($data['batch_id']);
        $semester_id = validateInt($data['semester_id']);
        $grades = $data['grades'];
        
        $success_count = 0;
        $error_count = 0;
        
        foreach ($grades as $grade_data) {
            $student_id = validateString($grade_data['student_id']);
            $degree = $grade_data['degree'] !== '' ? (float)$grade_data['degree'] : null;
            $grade = $grade_data['grade'];
            
            // Check if record exists
            $check_query = "SELECT id FROM studentsubjects 
                           WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
            $check_stmt = $mysqli1->prepare($check_query);
            $check_stmt->bind_param("ssii", $student_id, $subjectcode, $batch_id, $semester_id);
            $check_stmt->execute();
            $check_result = $check_stmt->get_result();
            
            if ($check_result->num_rows > 0) {
                // Update existing
                $update_query = "UPDATE studentsubjects SET degree = ?, grade = ?, updated_at = NOW() 
                                WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
                $update_stmt = $mysqli1->prepare($update_query);
                $update_stmt->bind_param("dsssii", $degree, $grade, $student_id, $subjectcode, $batch_id, $semester_id);
                if ($update_stmt->execute()) {
                    $success_count++;
                } else {
                    $error_count++;
                }
                $update_stmt->close();
            } else {
                // Insert new
                $insert_query = "INSERT INTO studentsubjects (student_id, subjectcode, degree, grade, batch_id, semester_id) 
                                VALUES (?, ?, ?, ?, ?, ?)";
                $insert_stmt = $mysqli1->prepare($insert_query);
                $insert_stmt->bind_param("ssdsii", $student_id, $subjectcode, $degree, $grade, $batch_id, $semester_id);
                if ($insert_stmt->execute()) {
                    $success_count++;
                } else {
                    $error_count++;
                }
                $insert_stmt->close();
            }
            $check_stmt->close();
        }
        
        echo json_encode(['success' => true, 'updated' => $success_count, 'errors' => $error_count]);
        exit;
    }
}

// Get all instructors
$instructors = [];
$query = "SELECT i.*, u.email, u.username 
          FROM instructors i 
          LEFT JOIN users u ON i.user_id = u.id 
          WHERE i.deleted_at IS NULL 
          ORDER BY i.name";
$result = $mysqli1->query($query);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $instructors[] = $row;
    }
}

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

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

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

include 'header.php';
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <title>إدارة المدرسين - Instructor Management</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">
    <style>
        body {
            background: #f5f7fb;
            font-family: 'Cairo', 'Tahoma', 'Segoe UI', Arial, sans-serif;
        }
        .content-wrapper {
            padding: 20px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        .card-header {
            background: linear-gradient(135deg, #1a5d1a, #2e8b57);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 15px 20px;
            font-weight: bold;
        }
        .btn-primary {
            background: linear-gradient(135deg, #1a5d1a, #2e8b57);
            border: none;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(26, 93, 26, 0.4);
        }
        .table th {
            background: #f8f9fa;
            text-align: center;
        }
        .table td {
            text-align: center;
            vertical-align: middle;
        }
        .modal-content {
            border-radius: 15px;
        }
        .modal-header {
            background: linear-gradient(135deg, #1a5d1a, #2e8b57);
            color: white;
            border-radius: 15px 15px 0 0;
        }
        .assigned-badge {
            background-color: #4caf50;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 11px;
            margin: 2px;
            display: inline-block;
        }
        .grade-input {
            width: 80px;
            text-align: center;
        }
        .grade-select {
            width: 70px;
        }
        .status-approved {
            color: #4caf50;
            font-weight: bold;
        }
        .status-pending {
            color: #ff9800;
            font-weight: bold;
        }
        .scrollable-table {
            max-height: 500px;
            overflow-y: auto;
        }
        .btn-remove-subject {
            background: rgba(255,255,255,0.3);
            border-radius: 50%;
            width: 20px;
            height: 20px;
            line-height: 18px;
            margin-left: 5px;
            border: none;
            color: white;
            cursor: pointer;
        }
        .btn-remove-subject:hover {
            background: rgba(255,255,255,0.5);
        }
    </style>
</head>
<body>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2><i class="fas fa-chalkboard-user"></i> إدارة المدرسين</h2>
                <p class="text-muted">إضافة، تعديل، وحذف المدرسين - تعيين المواد - إدارة الدرجات</p>
            </div>
            <div>
                <a href="admin_dashboard.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-right"></i> العودة للوحة التحكم
                </a>
                <button class="btn btn-primary ms-2" data-bs-toggle="modal" data-bs-target="#instructorModal" onclick="resetInstructorForm()">
                    <i class="fas fa-plus"></i> إضافة مدرس جديد
                </button>
            </div>
        </div>

        <!-- Instructors Table -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-users"></i> قائمة المدرسين
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover" id="instructorsTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>الاسم</th>
                                <th>البريد الإلكتروني</th>
                                <th>رقم الهاتف</th>
                                <th>التخصص</th>
                                <th>الكلية</th>
                                <th>المواد المسندة</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($instructors as $index => $instructor): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($instructor['name']) ?></td>
                                <td><?= htmlspecialchars($instructor['email'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($instructor['phone'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($instructor['specialization'] ?? '-') ?></td>
                                <td><?php 
                                    $college_name = '';
                                    $col_q = $mysqli1->query("SELECT name FROM colleges WHERE id = " . $instructor['college_id']);
                                    if ($col_q && $row = $col_q->fetch_assoc()) {
                                        $college_name = $row['name'];
                                    }
                                    echo htmlspecialchars($college_name);
                                ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info assign-subjects" data-id="<?= $instructor['id'] ?>" data-name="<?= htmlspecialchars($instructor['name']) ?>">
                                        <i class="fas fa-book"></i> تعيين مواد
                                    </button>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-warning edit-instructor" data-id="<?= $instructor['id'] ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger delete-instructor" data-id="<?= $instructor['id'] ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($instructors)): ?>
                            <tr>
                                <td colspan="8" class="text-center">لا توجد بيانات</td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Grade Entry Section -->
        <div class="card mt-4">
            <div class="card-header">
                <i class="fas fa-pen"></i> إدخال الدرجات
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <label class="form-label">المدرس</label>
                        <select class="form-select" id="grade_instructor_id">
                            <option value="">اختر المدرس</option>
                            <?php foreach ($instructors as $instructor): ?>
                                <option value="<?= $instructor['id'] ?>"><?= htmlspecialchars($instructor['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">المادة</label>
                        <select class="form-select" id="grade_subjectcode" disabled>
                            <option value="">اختر المادة</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">الدفعة</label>
                        <select class="form-select" id="grade_batch_id">
                            <option value="">اختر الدفعة</option>
                            <?php foreach ($batches as $batch): ?>
                                <option value="<?= $batch['id'] ?>"><?= htmlspecialchars($batch['value']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">الفصل الدراسي</label>
                        <select class="form-select" id="grade_semester_id">
                            <option value="">اختر الفصل</option>
                            <?php foreach ($semesters as $semester): ?>
                                <option value="<?= $semester['id'] ?>">الفصل <?= htmlspecialchars($semester['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <button class="btn btn-primary" id="loadGradesBtn" disabled>
                            <i class="fas fa-download"></i> تحميل الطلاب
                        </button>
                    </div>
                </div>
                <div id="gradesContainer" class="mt-4" style="display: none;">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> يمكنك إدخال الدرجات. الملاحظة: الدرجات المعتمدة (Approved) لا يمكن تعديلها.
                    </div>
                    <div class="table-responsive scrollable-table">
                        <table class="table table-bordered" id="gradesTable">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>رقم الطالب</th>
                                    <th>اسم الطالب</th>
                                    <th>الدرجة</th>
                                    <th>التقدير</th>
                                    <th>الحالة</th>
                                </tr>
                            </thead>
                            <tbody id="gradesTableBody">
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">
                        <button class="btn btn-success" id="saveGradesBtn">
                            <i class="fas fa-save"></i> حفظ الدرجات
                        </button>
                        <span id="saveResult" class="ms-3"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Instructor Modal -->
<div class="modal fade" id="instructorModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="instructorModalTitle">إضافة مدرس جديد</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="instructorForm">
                    <input type="hidden" id="instructor_id" name="instructor_id">
                    <div class="mb-3">
                        <label class="form-label">الاسم الكامل</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">رقم الهاتف</label>
                        <input type="text" class="form-control" id="phone" name="phone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">التخصص</label>
                        <input type="text" class="form-control" id="specialization" name="specialization">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الكلية</label>
                        <select class="form-select" id="college_id" name="college_id" required>
                            <option value="">اختر الكلية</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?= $college['id'] ?>"><?= htmlspecialchars($college['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3" id="passwordField">
                        <label class="form-label">كلمة المرور</label>
                        <input type="password" class="form-control" id="password" name="password">
                        <small class="text-muted">اتركها فارغة للحفاظ على كلمة المرور الحالية (عند التعديل)</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="button" class="btn btn-primary" id="saveInstructorBtn">حفظ</button>
            </div>
        </div>
    </div>
</div>

<!-- Assign Subjects Modal -->
<div class="modal fade" id="assignSubjectsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">تعيين مواد للمدرس</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="assignInstructorName"></div>
                <input type="hidden" id="assign_instructor_id">
                <div class="row mt-3">
                    <div class="col-md-6">
                        <label class="form-label">الكلية</label>
                        <select class="form-select" id="assign_college_id">
                            <option value="">اختر الكلية</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?= $college['id'] ?>"><?= htmlspecialchars($college['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">المواد المتاحة</label>
                        <select class="form-select" id="available_subjects" multiple size="8">
                        </select>
                        <button type="button" class="btn btn-sm btn-primary mt-2" id="assignSubjectBtn">
                            <i class="fas fa-arrow-left"></i> تعيين المادة
                        </button>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <label class="form-label">المواد المسندة</label>
                        <div id="assignedSubjectsList" class="border rounded p-2" style="min-height: 150px;">
                            <p class="text-muted text-center">لا توجد مواد مسندة</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    // Grade entry - load subjects when instructor selected
    $('#grade_instructor_id').on('change', function() {
        var instructorId = $(this).val();
        if (instructorId) {
            $.ajax({
                url: window.location.pathname,
                type: 'GET',
                data: { ajax: 'get_assigned_subjects', instructor_id: instructorId },
                dataType: 'json',
                success: function(response) {
                    var $subjectSelect = $('#grade_subjectcode');
                    $subjectSelect.empty().append('<option value="">اختر المادة</option>');
                    if (response.success && response.assigned && response.assigned.length > 0) {
                        $.each(response.assigned, function(i, subj) {
                            $subjectSelect.append('<option value="' + subj.subjectcode + '">' + subj.subjectcode + ' - ' + subj.subjectnamea + '</option>');
                        });
                        $subjectSelect.prop('disabled', false);
                    } else {
                        $subjectSelect.append('<option value="">لا توجد مواد مسندة</option>');
                        $subjectSelect.prop('disabled', true);
                    }
                },
                error: function() {
                    $('#grade_subjectcode').empty().append('<option value="">خطأ في التحميل</option>').prop('disabled', true);
                }
            });
        } else {
            $('#grade_subjectcode').empty().append('<option value="">اختر المادة</option>').prop('disabled', true);
        }
        $('#gradesContainer').hide();
    });
    
    // Load students for grade entry
    $('#loadGradesBtn').on('click', function() {
        var instructorId = $('#grade_instructor_id').val();
        var subjectcode = $('#grade_subjectcode').val();
        var batchId = $('#grade_batch_id').val();
        var semesterId = $('#grade_semester_id').val();
        
        if (!instructorId || !subjectcode || !batchId || !semesterId) {
            alert('الرجاء اختيار جميع المعايير');
            return;
        }
        
        $('#loadGradesBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> جاري التحميل...');
        
        $.ajax({
            url: window.location.pathname,
            type: 'GET',
            data: {
                ajax: 'get_students_for_grades',
                subjectcode: subjectcode,
                batch_id: batchId,
                semester_id: semesterId
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    displayGradesTable(response.students);
                    $('#gradesContainer').show();
                } else {
                    alert('خطأ في تحميل البيانات');
                }
            },
            error: function() {
                alert('حدث خطأ في تحميل البيانات');
            },
            complete: function() {
                $('#loadGradesBtn').prop('disabled', false).html('<i class="fas fa-download"></i> تحميل الطلاب');
            }
        });
    });
    
    function displayGradesTable(students) {
        var html = '';
        $.each(students, function(i, student) {
            var isApproved = student.isapproved == 1;
            var readonlyAttr = isApproved ? 'readonly' : '';
            var disabledAttr = isApproved ? 'disabled' : '';
            
            var degreeValue = student.degree !== null ? student.degree : '';
            var gradeValue = student.grade || '';
            
            html += '<tr>';
            html += '<td>' + (i + 1) + '</td>';
            html += '<td>' + escapeHtml(student.student_id) + '</td>';
            html += '<td class="text-right">' + escapeHtml(student.student_name) + '</td>';
            html += '<td><input type="number" class="form-control grade-input" data-student="' + student.student_id + '" value="' + degreeValue + '" ' + readonlyAttr + ' min="0" max="100" step="0.5"></td>';
            html += '<td>';
            html += '<select class="form-select grade-select" data-student="' + student.student_id + '" ' + disabledAttr + '>';
            html += '<option value="">--</option>';
            html += '<option value="A" ' + (gradeValue == 'A' ? 'selected' : '') + '>A</option>';
            html += '<option value="B+" ' + (gradeValue == 'B+' ? 'selected' : '') + '>B+</option>';
            html += '<option value="B" ' + (gradeValue == 'B' ? 'selected' : '') + '>B</option>';
            html += '<option value="C+" ' + (gradeValue == 'C+' ? 'selected' : '') + '>C+</option>';
            html += '<option value="C" ' + (gradeValue == 'C' ? 'selected' : '') + '>C</option>';
            html += '<option value="D+" ' + (gradeValue == 'D+' ? 'selected' : '') + '>D+</option>';
            html += '<option value="D" ' + (gradeValue == 'D' ? 'selected' : '') + '>D</option>';
            html += '<option value="F" ' + (gradeValue == 'F' ? 'selected' : '') + '>F</option>';
            html += '</select>';
            html += '</td>';
            html += '<td>' + (isApproved ? '<span class="status-approved"><i class="fas fa-check-circle"></i> معتمدة</span>' : '<span class="status-pending"><i class="fas fa-clock"></i> غير معتمدة</span>') + '</td>';
            html += '</tr>';
        });
        $('#gradesTableBody').html(html);
    }
    
    // Save grades
    $('#saveGradesBtn').on('click', function() {
        var subjectcode = $('#grade_subjectcode').val();
        var batchId = $('#grade_batch_id').val();
        var semesterId = $('#grade_semester_id').val();
        var grades = [];
        
        $('#gradesTableBody tr').each(function() {
            var $row = $(this);
            var studentId = $row.find('.grade-input').data('student');
            var degree = $row.find('.grade-input').val();
            var grade = $row.find('.grade-select').val();
            
            // Check if input is not disabled (not approved)
            if (!$row.find('.grade-input').prop('readonly')) {
                grades.push({
                    student_id: studentId,
                    degree: degree,
                    grade: grade
                });
            }
        });
        
        if (grades.length === 0) {
            alert('لا توجد درجات للتحديث أو جميع الدرجات معتمدة');
            return;
        }
        
        $('#saveGradesBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> جاري الحفظ...');
        
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                ajax: 'save_grades',
                subjectcode: subjectcode,
                batch_id: batchId,
                semester_id: semesterId,
                grades: grades
            }),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#saveResult').html('<span class="text-success"><i class="fas fa-check"></i> تم حفظ ' + response.updated + ' درجة بنجاح</span>').fadeIn().delay(3000).fadeOut();
                    $('#loadGradesBtn').click(); // Reload data
                } else {
                    $('#saveResult').html('<span class="text-danger">خطأ في حفظ البيانات</span>').fadeIn().delay(3000).fadeOut();
                }
            },
            error: function() {
                $('#saveResult').html('<span class="text-danger">حدث خطأ في حفظ البيانات</span>').fadeIn().delay(3000).fadeOut();
            },
            complete: function() {
                $('#saveGradesBtn').prop('disabled', false).html('<i class="fas fa-save"></i> حفظ الدرجات');
            }
        });
    });
    
    // Enable load button when all selections are made
    $('#grade_instructor_id, #grade_subjectcode, #grade_batch_id, #grade_semester_id').on('change', function() {
        var allSelected = $('#grade_instructor_id').val() && $('#grade_subjectcode').val() && $('#grade_batch_id').val() && $('#grade_semester_id').val();
        $('#loadGradesBtn').prop('disabled', !allSelected);
    });
    
    // Reset form for new instructor
    window.resetInstructorForm = function() {
        $('#instructorForm')[0].reset();
        $('#instructor_id').val('');
        $('#passwordField').show();
        $('#instructorModalTitle').text('إضافة مدرس جديد');
    };
    
    // Edit Instructor
    $('.edit-instructor').on('click', function() {
        var id = $(this).data('id');
        $.ajax({
            url: 'api/instructor_api.php',
            type: 'GET',
            data: { action: 'get', id: id },
            dataType: 'json',
            success: function(data) {
                if (data.success) {
                    $('#instructor_id').val(data.instructor.id);
                    $('#name').val(data.instructor.name);
                    $('#email').val(data.instructor.email);
                    $('#phone').val(data.instructor.phone);
                    $('#specialization').val(data.instructor.specialization);
                    $('#college_id').val(data.instructor.college_id);
                    $('#passwordField').hide();
                    $('#instructorModalTitle').text('تعديل بيانات المدرس');
                    $('#instructorModal').modal('show');
                } else {
                    alert(data.message || 'حدث خطأ');
                }
            },
            error: function() {
                alert('حدث خطأ في تحميل البيانات');
            }
        });
    });
    
    // Save Instructor
    $('#saveInstructorBtn').on('click', function() {
        var formData = $('#instructorForm').serialize();
        var id = $('#instructor_id').val();
        var url = 'api/instructor_api.php';
        var action = id ? 'update' : 'add';
        
        $('#saveInstructorBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> جاري الحفظ...');
        
        $.ajax({
            url: url,
            type: 'POST',
            data: formData + '&action=' + action,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.message || 'حدث خطأ');
                    $('#saveInstructorBtn').prop('disabled', false).html('حفظ');
                }
            },
            error: function() {
                alert('حدث خطأ في حفظ البيانات');
                $('#saveInstructorBtn').prop('disabled', false).html('حفظ');
            }
        });
    });
    
    // Delete Instructor
    $('.delete-instructor').on('click', function() {
        if (confirm('هل أنت متأكد من حذف هذا المدرس؟')) {
            var id = $(this).data('id');
            $.ajax({
                url: 'api/instructor_api.php',
                type: 'POST',
                data: { action: 'delete', id: id },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.message || 'حدث خطأ');
                    }
                },
                error: function() {
                    alert('حدث خطأ في حذف المدرس');
                }
            });
        }
    });
    
    // Assign Subjects
    $('.assign-subjects').on('click', function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        $('#assign_instructor_id').val(id);
        $('#assignInstructorName').html('<h5>' + name + '</h5>');
        loadAssignedSubjects(id);
        $('#assignSubjectsModal').modal('show');
    });
    
    $('#assign_college_id').on('change', function() {
        var collegeId = $(this).val();
        if (collegeId) {
            $.ajax({
                url: window.location.pathname,
                type: 'GET',
                data: { ajax: 'get_subjects_by_college', college_id: collegeId },
                dataType: 'json',
                success: function(response) {
                    var options = '';
                    if (response.success && response.subjects && response.subjects.length > 0) {
                        $.each(response.subjects, function(i, subj) {
                            options += '<option value="' + subj.subjectcode + '">' + subj.subjectcode + ' - ' + subj.subjectnamea + ' (' + subj.credit_hours + ' ساعة)</option>';
                        });
                    } else {
                        options = '<option value="">لا توجد مواد</option>';
                    }
                    $('#available_subjects').html(options);
                },
                error: function() {
                    $('#available_subjects').html('<option value="">خطأ في التحميل</option>');
                }
            });
        } else {
            $('#available_subjects').html('');
        }
    });
    
    $('#assignSubjectBtn').on('click', function() {
        var instructorId = $('#assign_instructor_id').val();
        var selectedSubjects = $('#available_subjects').val();
        
        if (!selectedSubjects || selectedSubjects.length === 0) {
            alert('الرجاء اختيار مادة واحدة على الأقل');
            return;
        }
        
        $.ajax({
            url: 'api/instructor_api.php',
            type: 'POST',
            data: {
                action: 'assign_subjects',
                instructor_id: instructorId,
                subjects: JSON.stringify(selectedSubjects)
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    loadAssignedSubjects(instructorId);
                    alert('تم تعيين المواد بنجاح');
                } else {
                    alert(response.message || 'حدث خطأ');
                }
            },
            error: function() {
                alert('حدث خطأ في تعيين المواد');
            }
        });
    });
    
    function loadAssignedSubjects(instructorId) {
        $.ajax({
            url: window.location.pathname,
            type: 'GET',
            data: { ajax: 'get_assigned_subjects', instructor_id: instructorId },
            dataType: 'json',
            success: function(response) {
                var html = '';
                if (response.success && response.assigned && response.assigned.length > 0) {
                    $.each(response.assigned, function(i, subj) {
                        html += '<div class="assigned-badge">' + subj.subjectcode + ' - ' + subj.subjectnamea;
                        html += ' <button class="btn-remove-subject" data-subject="' + subj.subjectcode + '">&times;</button>';
                        html += '</div>';
                    });
                } else {
                    html = '<p class="text-muted text-center">لا توجد مواد مسندة</p>';
                }
                $('#assignedSubjectsList').html(html);
                
                // Add remove functionality
                $('.btn-remove-subject').off('click').on('click', function() {
                    var subjectcode = $(this).data('subject');
                    if (confirm('هل تريد إلغاء تعيين هذه المادة؟')) {
                        $.ajax({
                            url: 'api/instructor_api.php',
                            type: 'POST',
                            data: {
                                action: 'remove_subject',
                                instructor_id: instructorId,
                                subjectcode: subjectcode
                            },
                            dataType: 'json',
                            success: function(response) {
                                if (response.success) {
                                    loadAssignedSubjects(instructorId);
                                } else {
                                    alert('حدث خطأ');
                                }
                            },
                            error: function() {
                                alert('حدث خطأ في إلغاء التعيين');
                            }
                        });
                    }
                });
            }
        });
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        return String(text).replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }
});
</script>

<?php include 'footer.php'; ?>
</body>
</html>