<?php
// subject_close_archive.php - Manage closing, archiving, and editing permissions for subjects
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// Start session only once at the beginning
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// التحقق من CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// وظائف الأمان
function validateInt($input, $default = 0) {
    if (isset($input) && ctype_digit((string)$input)) {
        return (int)$input;
    }
    return $default;
}

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

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

// Initialize variables
$errors = [];
$success_message = '';
$action = validateString($_GET['action'] ?? '');

// Get filter data for dropdowns
$colleges = [];
$result = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $colleges[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

$programs = [];
$result = $mysqli1->query("SELECT id, name FROM programs  ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $programs[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

$all_sections = [];
$result = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $all_sections[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name']),
            'parent' => (int)$row['parent']
        ];
    }
}

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

$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[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

// Handle filter submission
$college_id = validateInt($_GET['college_id'] ?? 0);
$section_id = validateInt($_GET['section_id'] ?? 0);
$program_id = validateInt($_GET['program_id'] ?? 0);
$specialization_id = validateInt($_GET['specialization_id'] ?? 0);
$batch_id = validateInt($_GET['batch_id'] ?? 0);
$semester_id = validateInt($_GET['semester_id'] ?? 0);
$subject_filter = validateString($_GET['subject_filter'] ?? '');
$status_filter = validateString($_GET['status_filter'] ?? ''); // all, closed, open, archived

// التحقق من الصلاحيات
if (!$canAll && $scopeCollege !== null && $college_id > 0 && $scopeCollege != $college_id) {
    die('غير مصرح لك بالوصول لهذه البيانات');
}

// Handle Bulk Actions (Close, Open, Archive, Restore)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // التحقق من CSRF token
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    }
    
    $bulk_action = validateString($_POST['bulk_action'] ?? '');
    $selected_records = $_POST['selected_records'] ?? [];
    
    if (!empty($bulk_action) && !empty($selected_records)) {
        $mysqli1->begin_transaction();
        
        try {
            $updated_count = 0;
            
            foreach ($selected_records as $record_id) {
                list($student_id, $subjectcode, $batch_id_val, $semester_id_val) = explode('|', $record_id);
                
                $student_id = validateString($student_id);
                $subjectcode = validateString($subjectcode);
                $batch_id_val = validateInt($batch_id_val);
                $semester_id_val = validateInt($semester_id_val);
                
                $update_query = "";
                $params = [];
                $types = "";
                
                switch ($bulk_action) {
                    case 'close':
                        // Close for editing - set isapproved = 2 (closed)
                        $update_query = "UPDATE studentsubjects SET isapproved = 2, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
                        $types = "ssii";
                        $params = [$student_id, $subjectcode, $batch_id_val, $semester_id_val];
                        break;
                    
                    case 'open':
                        // Open for editing - set isapproved = 0 (open)
                        $update_query = "UPDATE studentsubjects SET isapproved = 0, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
                        $types = "ssii";
                        $params = [$student_id, $subjectcode, $batch_id_val, $semester_id_val];
                        break;
                    
                    case 'archive':
                        // Archive - set deleted_at (soft delete)
                        $update_query = "UPDATE studentsubjects SET deleted_at = NOW(), updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
                        $types = "ssii";
                        $params = [$student_id, $subjectcode, $batch_id_val, $semester_id_val];
                        break;
                    
                    case 'restore':
                        // Restore from archive - remove deleted_at
                        $update_query = "UPDATE studentsubjects SET deleted_at = NULL, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
                        $types = "ssii";
                        $params = [$student_id, $subjectcode, $batch_id_val, $semester_id_val];
                        break;
                    
                    case 'approve':
                        // Approve - set isapproved = 1 (approved/closed permanently)
                        $update_query = "UPDATE studentsubjects SET isapproved = 1, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
                        $types = "ssii";  // Add this line
                        $params = [$student_id, $subjectcode, $batch_id_val, $semester_id_val];  // Add this line
                    
    break;
                }
                
                if (!empty($update_query)) {
                    $stmt = $mysqli1->prepare($update_query);
                    if ($stmt) {
                        $stmt->bind_param($types, ...$params);
                        if ($stmt->execute()) {
                            $updated_count++;
                        }
                        $stmt->close();
                    }
                }
            }
            
            $mysqli1->commit();
            
            $action_messages = [
                'close' => 'تم إغلاق',
                'open' => 'تم فتح',
                'archive' => 'تم أرشفة',
                'restore' => 'تم استعادة',
                'approve' => 'تم اعتماد'
            ];
            
            $success_message = "✅ " . $action_messages[$bulk_action] . " $updated_count سجل بنجاح";
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            error_log("Bulk action error: " . $e->getMessage());
            $errors[] = "❌ حدث خطأ أثناء تنفيذ العملية: " . $e->getMessage();
        }
    } elseif (!empty($bulk_action) && empty($selected_records)) {
        $errors[] = "⚠️ الرجاء تحديد السجلات المراد معالجتها";
    }
}

// Handle individual record status change via AJAX
 // Handle individual record status change via AJAX
if (isset($_POST['toggle_status'])) {
    header('Content-Type: application/json');
    
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'طلب غير مصرح به']);
        exit;
    }
    
    $student_id = validateString($_POST['student_id'] ?? '');
    $subjectcode = validateString($_POST['subjectcode'] ?? '');
    $batch_id = validateInt($_POST['batch_id'] ?? 0);
    $semester_id = validateInt($_POST['semester_id'] ?? 0);
    $action = validateString($_POST['toggle_action'] ?? '');
    
    $update_query = "";
    $status_message = "";
    
    switch ($action) {
        case 'close':
            $update_query = "UPDATE studentsubjects SET isapproved = 2, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
            $status_message = "closed";
            break;
        case 'open':
            $update_query = "UPDATE studentsubjects SET isapproved = 0, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
            $status_message = "open";
            break;
        case 'approve':
            // Approve - set isapproved = 1 (approved/closed permanently)
            $update_query = "UPDATE studentsubjects SET isapproved = 1, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
            $status_message = "approved";
            break;
        case 'archive':
            $update_query = "UPDATE studentsubjects SET deleted_at = NOW(), updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
            $status_message = "archived";
            break;
        case 'restore':
            $update_query = "UPDATE studentsubjects SET deleted_at = NULL, updated_at = NOW() WHERE student_id = ? AND subjectcode = ? AND batch_id = ? AND semester_id = ?";
            $status_message = "restored";
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'إجراء غير صالح']);
            exit;
    }
    
    $stmt = $mysqli1->prepare($update_query);
    if ($stmt) {
        $stmt->bind_param("ssii", $student_id, $subjectcode, $batch_id, $semester_id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => $status_message]);
        } else {
            echo json_encode(['success' => false, 'message' => 'فشل تحديث الحالة: ' . $stmt->error]);
        }
        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => 'خطأ في قاعدة البيانات: ' . $mysqli1->error]);
    }
    exit;
}
// Get subjects data based on filters
$subjects_data = [];
$total_closed = 0;
$total_open = 0;
$total_archived = 0;
$total_records = 0;

if ($college_id && $section_id && $program_id && $batch_id && $semester_id) {
    // Build the query for studentsubjects with status info
    $query = "
        SELECT 
            ss.id,
            ss.student_id,
            ss.subjectcode,
            ss.semester_id,
            ss.batch_id,
            ss.isapproved,
            ss.degree,
            ss.grade,
            ss.created_at,
            ss.updated_at,
            ss.deleted_at,
            s.student_name,
            sub.subjectnamea,
            sub.credit_hours,
            CASE 
                WHEN ss.deleted_at IS NOT NULL THEN 'archived'
                WHEN ss.isapproved = 1 THEN 'approved'
                WHEN ss.isapproved = 2 THEN 'closed'
                ELSE 'open'
            END as status,
            CASE 
                WHEN ss.deleted_at IS NOT NULL THEN 'مؤرشف'
                WHEN ss.isapproved = 1 THEN 'معتمد ومغلق'
                WHEN ss.isapproved = 2 THEN 'مغلق للتعديل'
                ELSE 'مفتوح للتعديل'
            END as status_text
        FROM studentsubjects ss
        JOIN students s ON ss.student_id = s.student_id
        JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        WHERE s.college_id = ? 
        AND s.section_id = ? 
        AND s.program_id = ? 
        AND s.batch_id = ?
        AND ss.batch_id = ?
        AND ss.semester_id = ?
        AND s.deleted_at IS NULL
        AND sub.deleted_at IS NULL
    ";
    
    $types = "iiiiii";
    $params = [$college_id, $section_id, $program_id, $batch_id, $batch_id, $semester_id];
    
    if ($specialization_id > 0) {
        $query .= " AND s.specialization_id = ?";
        $types .= "i";
        $params[] = $specialization_id;
    }
    
    if (!empty($subject_filter)) {
        $query .= " AND ss.subjectcode = ?";
        $types .= "s";
        $params[] = $subject_filter;
    }
    
    // Apply status filter
    if (!empty($status_filter)) {
        switch ($status_filter) {
            case 'open':
                $query .= " AND ss.deleted_at IS NULL AND ss.isapproved = 0";
                break;
            case 'closed':
                $query .= " AND ss.deleted_at IS NULL AND ss.isapproved = 2";
                break;
            case 'approved':
                $query .= " AND ss.deleted_at IS NULL AND ss.isapproved = 1";
                break;
            case 'archived':
                $query .= " AND ss.deleted_at IS NOT NULL";
                break;
        }
    }
    
    $query .= " ORDER BY s.student_name, ss.subjectcode";
    
    $stmt = $mysqli1->prepare($query);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $subjects_data[] = [
                'id' => (int)$row['id'],
                'student_id' => validateString($row['student_id']),
                'student_name' => validateString($row['student_name']),
                'subjectcode' => validateString($row['subjectcode']),
                'subjectname' => validateString($row['subjectnamea']),
                'credit_hours' => (float)$row['credit_hours'],
                'semester_id' => (int)$row['semester_id'],
                'batch_id' => (int)$row['batch_id'],
                'isapproved' => (int)$row['isapproved'],
                'degree' => $row['degree'] ? (float)$row['degree'] : null,
                'grade' => $row['grade'] ? validateString($row['grade']) : null,
                'status' => $row['status'],
                'status_text' => $row['status_text'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
                'deleted_at' => $row['deleted_at']
            ];
            
            // Count statistics
            if ($row['status'] == 'closed' || $row['status'] == 'approved') {
                $total_closed++;
            } elseif ($row['status'] == 'open') {
                $total_open++;
            } elseif ($row['status'] == 'archived') {
                $total_archived++;
            }
            $total_records++;
        }
        $stmt->close();
    }
}

// Get unique subjects for filter
$all_subjects = [];
if ($college_id && $section_id && $program_id && $batch_id && $semester_id) {
    $subjectQuery = "
        SELECT DISTINCT 
            ss.subjectcode,
            sub.subjectnamea
        FROM studentsubjects ss
        JOIN students s ON ss.student_id = s.student_id
        JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        WHERE s.college_id = ? 
        AND s.section_id = ? 
        AND s.program_id = ? 
        AND s.batch_id = ?
        AND ss.batch_id = ?
        AND ss.semester_id = ?
        AND s.deleted_at IS NULL
        AND sub.deleted_at IS NULL
    ";
    
    $types = "iiiiii";
    $params = [$college_id, $section_id, $program_id, $batch_id, $batch_id, $semester_id];
    
    if ($specialization_id > 0) {
        $subjectQuery .= " AND s.specialization_id = ?";
        $types .= "i";
        $params[] = $specialization_id;
    }
    
    $subjectStmt = $mysqli1->prepare($subjectQuery);
    if ($subjectStmt) {
        $subjectStmt->bind_param($types, ...$params);
        $subjectStmt->execute();
        $subjectResult = $subjectStmt->get_result();
        while ($row = $subjectResult->fetch_assoc()) {
            $all_subjects[$row['subjectcode']] = $row['subjectnamea'];
        }
        $subjectStmt->close();
    }
}

include 'header.php';
?>

<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --header-gradient: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
        --success-gradient: linear-gradient(135deg, #00b09b, #96c93d);
        --danger-gradient: linear-gradient(135deg, #fc6767, #ec008c);
        --warning-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        --info-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        --closed-color: #f59e0b;
        --open-color: #10b981;
        --archived-color: #6b7280;
        --approved-color: #059669;
    }

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

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

    .page-header {
        background: var(--header-gradient);
        border-radius: 30px;
        padding: 30px 40px;
        margin-bottom: 30px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        position: relative;
        overflow: hidden;
        color: white;
    }

    .page-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: rotate 20s linear infinite;
        z-index: 0;
    }

    @keyframes rotate {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    .page-header h1 {
        font-size: 2rem;
        font-weight: 800;
        margin: 0;
        text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        position: relative;
        z-index: 2;
    }

    .page-header p {
        font-size: 0.9rem;
        margin-top: 5px;
        opacity: 0.9;
        position: relative;
        z-index: 2;
    }
.page-header .btn-outline-gradient,
.page-header .btn-gradient {
    position: relative;
    z-index: 3; /* اجعل الأزرار فوق كل شيء */
    pointer-events: auto; /* تأكد من أن الأزرار قابلة للنقر */
}
    .btn-gradient {
        background: var(--success-gradient);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 176, 155, 0.4);
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-gradient:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6);
        color: white;
    }

    .btn-outline-gradient {
        background: transparent;
        border: 2px solid rgba(255, 255, 255, 0.5);
        color: white;
        padding: 10px 25px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-outline-gradient:hover {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        transform: translateY(-2px);
    }
/* Make action buttons responsive - keep in same line */
.action-buttons {
    display: flex;
    gap: 5px;
    justify-content: center;
    flex-wrap: nowrap;
    white-space: nowrap;
}

.action-btn {
    padding: 5px 8px;
    margin: 0 2px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    border: none;
    transition: all 0.2s ease;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    white-space: nowrap;
}

.action-btn i {
    font-size: 0.7rem;
}

/* Responsive adjustments for mobile */
@media (max-width: 768px) {
    .action-btn {
        padding: 4px 6px;
        font-size: 0.6rem;
    }
    
    .action-btn i {
        font-size: 0.6rem;
    }
    
    .status-table th,
    .status-table td {
        padding: 6px 4px;
    }
}

@media (max-width: 480px) {
    .action-btn span {
        display: none;
    }
    
    .action-btn i {
        margin: 0;
    }
    
    .action-btn {
        padding: 5px 8px;
    }
}
    .btn-reset {
        background: linear-gradient(135deg, #6b7280, #4b5563);
        border: none;
        color: white;
        padding: 10px 20px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

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

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

    .required-field::after {
        content: " *";
        color: #e53e3e;
    }

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

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

    .content-card {
        background: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        border-right: 5px solid #667eea;
    }

    .stat-card {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        border-radius: 20px;
        padding: 20px 15px;
        text-align: center;
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        height: 100%;
        cursor: pointer;
    }

    .stat-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
    }

    .stat-card.active {
        background: var(--primary-gradient);
        color: white;
    }

    .stat-card.active .stat-number,
    .stat-card.active .stat-label,
    .stat-card.active .stat-icon {
        color: white;
    }

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

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

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

    .scrollable-area {
        max-height: 550px;
        overflow-y: auto;
        overflow-x: auto;
        border-radius: 20px;
        border: 1px solid #e2e8f0;
        background: white;
    }

    .status-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.85rem;
    }

    .status-table th {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        font-weight: 700;
        color: #2d3748;
        padding: 12px 8px;
        text-align: center;
        position: sticky;
        top: 0;
        z-index: 10;
        border-bottom: 2px solid #e2e8f0;
        white-space: nowrap;
    }

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

    .status-table tr:hover {
        background-color: #f8fafc;
    }

    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 5px 12px;
        border-radius: 50px;
        font-size: 0.75rem;
        font-weight: 600;
    }

    .status-open {
        background: linear-gradient(135deg, #d1fae5, #a7f3d0);
        color: #065f46;
    }

    .status-closed {
        background: linear-gradient(135deg, #fed7aa, #fde68a);
        color: #92400e;
    }

    .status-approved {
        background: linear-gradient(135deg, #a7f3d0, #6ee7b7);
        color: #064e3b;
    }

    .status-archived {
        background: linear-gradient(135deg, #e5e7eb, #d1d5db);
        color: #374151;
    }

    .action-btn {
        padding: 5px 10px;
        margin: 2px;
        border-radius: 20px;
        font-size: 0.7rem;
        font-weight: 600;
        border: none;
        transition: all 0.2s ease;
        cursor: pointer;
    }

    .action-btn-open {
        background: linear-gradient(135deg, #10b981, #059669);
        color: white;
    }

    .action-btn-close {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
    }

    .action-btn-archive {
        background: linear-gradient(135deg, #6b7280, #4b5563);
        color: white;
    }

    .action-btn-restore {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        color: white;
    }

    .action-btn-approve {
        background: linear-gradient(135deg, #059669, #047857);
        color: white;
    }

    .action-btn:hover {
        transform: translateY(-1px);
        filter: brightness(1.05);
    }

    .select-all {
        cursor: pointer;
    }

    .bulk-actions {
        background: #f8fafc;
        border-radius: 16px;
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid #e2e8f0;
    }

    .alert {
        border-radius: 20px;
        border: none;
        padding: 15px 25px;
        font-weight: 600;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        animation: slideIn 0.5s ease;
        margin-bottom: 25px;
    }

    @keyframes slideIn {
        from { transform: translateY(-20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }

    .filter-badge {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        padding: 5px 12px;
        border-radius: 50px;
        font-size: 0.8rem;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .loading-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        justify-content: center;
        align-items: center;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #2596be;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

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

    .info-icon {
        cursor: help;
        margin-left: 5px;
        color: #667eea;
    }
    /* FORCE RTL DROPDOWN ARROWS - MUST BE LAST */
select.form-select,
.filter-card select.form-select,
.subject-filter-section select.form-select,
select.form-select:not([multiple]) {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e") !important;
    background-position: left 0.75rem center !important;
    background-repeat: no-repeat !important;
    background-size: 16px 12px !important;
    padding-left: 2rem !important;
    padding-right: 0.75rem !important;
    text-align: right !important;
    direction: rtl !important;
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    appearance: none !important;
}

/* Also fix the subject filter select */
.subject-filter-section .form-select {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e") !important;
    background-position: left 0.75rem center !important;
    background-repeat: no-repeat !important;
    padding-left: 2rem !important;
    padding-right: 0.75rem !important;
    text-align: right !important;
    direction: rtl !important;
}
</style>

<div class="main-wrapper" dir="rtl">
    <div class="container-fluid px-4">
        <!-- Page Header -->
        <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
            <div>
                <h1 class="mb-2">
                    <i class="fas fa-lock ms-3"></i>
                    إدارة إغلاق وأرشفة المقررات
                </h1>
                <p class="mb-0">
                    <i class="fas fa-info-circle ms-2"></i>
                    التحكم في صلاحية تعديل المقررات الدراسية - إغلاق/فتح المقررات، الأرشفة، والاعتماد النهائي
                </p>
            </div>
            <div class="d-flex gap-3 mt-3 mt-md-0">
                <a href="subject_grades.php" class="btn-outline-gradient">
                    <i class="fas fa-chart-bar ms-2"></i>
                    إدخال الدرجات
                </a>
                <a href="subject_enrollment.php" class="btn-outline-gradient">
                    <i class="fas fa-user-graduate ms-2"></i>
                    تسجيل المقررات
                </a>
                 <a href="admin_dashboard.php" class="btn-outline-gradient">
                    <i class="fas fa-user-graduate ms-2"></i>
                    لوحة التحكم 
                </a>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle ms-2"></i>
                <?php foreach ($errors as $error): ?>
                    <div><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endforeach; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle ms-2"></i>
                <?= htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="filter-card">
            <form method="get" class="row g-3" id="filterForm">
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-university ms-1"></i> الكلية
                    </label>
                    <select class="form-select" name="college_id" id="college_id" required
                            <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                        <option value="">اختر الكلية</option>
                        <?php foreach ($colleges as $college): ?>
                            <option value="<?= (int)$college['id'] ?>" 
                                <?= ($college_id == $college['id']) || (!$canAll && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$canAll && $scopeCollege !== null): ?>
                        <input type="hidden" name="college_id" value="<?= (int)$scopeCollege ?>">
                    <?php endif; ?>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-layer-group ms-1"></i> القسم
                    </label>
                    <select class="form-select" name="section_id" id="section_id" required>
                        <option value="">اختر القسم</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-graduation-cap ms-1"></i> البرنامج
                    </label>
                    <select class="form-select" name="program_id" id="program_id" required>
                        <option value="">اختر البرنامج</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">
                        <i class="fas fa-tag ms-1"></i> التخصص
                    </label>
                    <select class="form-select" name="specialization_id" id="specialization_id">
                        <option value="">جميع التخصصات</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-users ms-1"></i> الدفعة
                    </label>
                    <select class="form-select" name="batch_id" id="batch_id" required>
                        <option value="">اختر الدفعة</option>
                        <?php foreach ($batches as $batch): ?>
                            <option value="<?= (int)$batch['id'] ?>" 
                                <?= ($batch_id == $batch['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-calendar-alt ms-1"></i> الفصل الدراسي
                    </label>
                    <select class="form-select" name="semester_id" id="semester_id" required>
                        <option value="">اختر الفصل</option>
                        <?php foreach ($semesters as $semester): ?>
                            <option value="<?= (int)$semester['id'] ?>" 
                                <?= ($semester_id == $semester['id']) ? 'selected' : '' ?>>
                                الفصل <?= htmlspecialchars($semester['name'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-4">
                    <label class="form-label">
                        <i class="fas fa-book ms-1"></i> المادة
                    </label>
                    <select class="form-select" name="subject_filter">
                        <option value="">جميع المقررات</option>
                        <?php foreach ($all_subjects as $code => $name): ?>
                            <option value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" 
                                <?= ($subject_filter == $code) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?> - <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-4">
                    <label class="form-label">
                        <i class="fas fa-filter ms-1"></i> حالة المادة
                    </label>
                    <select class="form-select" name="status_filter">
                        <option value="">جميع الحالات</option>
                        <option value="open" <?= ($status_filter == 'open') ? 'selected' : '' ?>>مفتوح للتعديل</option>
                        <option value="closed" <?= ($status_filter == 'closed') ? 'selected' : '' ?>>مغلق للتعديل</option>
                        <option value="approved" <?= ($status_filter == 'approved') ? 'selected' : '' ?>>معتمد ومغلق</option>
                        <option value="archived" <?= ($status_filter == 'archived') ? 'selected' : '' ?>>مؤرشف</option>
                    </select>
                </div>
                
                <div class="col-md-4 d-flex align-items-end">
                    <div class="d-flex gap-3 w-100">
                        <a href="subject_close_archive.php" class="btn-reset flex-grow-1 text-center">
                            <i class="fas fa-redo-alt ms-2"></i> إعادة تعيين
                        </a>
                        <button type="submit" class="btn-gradient flex-grow-1">
                            <i class="fas fa-search ms-2"></i> بحث
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <?php if ($college_id && $section_id && $program_id && $batch_id && $semester_id): ?>
            
            <!-- Statistics Cards -->
            <div class="row g-3 mb-4">
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card" data-filter="open">
                        <div class="stat-icon"><i class="fas fa-lock-open"></i></div>
                        <div class="stat-number"><?= $total_open ?></div>
                        <div class="stat-label">مواد مفتوحة للتعديل</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card" data-filter="closed">
                        <div class="stat-icon"><i class="fas fa-lock"></i></div>
                        <div class="stat-number"><?= $total_closed ?></div>
                        <div class="stat-label">مواد مغلقة للتعديل</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card" data-filter="archived">
                        <div class="stat-icon"><i class="fas fa-archive"></i></div>
                        <div class="stat-number"><?= $total_archived ?></div>
                        <div class="stat-label">مواد مؤرشفة</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card" data-filter="all">
                        <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
                        <div class="stat-number"><?= $total_records ?></div>
                        <div class="stat-label">إجمالي السجلات</div>
                    </div>
                </div>
            </div>

            <!-- Information Card -->
            <div class="content-card">
                <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                    <div>
                        <h5 class="fw-bold mb-3">
                            <i class="fas fa-info-circle text-primary ms-2"></i>
                            شرح حالات المقررات
                        </h5>
                        <div class="row g-3">
                            <div class="col-md-3">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <span class="status-badge status-open"><i class="fas fa-lock-open"></i> مفتوح للتعديل</span>
                                    <span class="text-muted small">يمكن تعديل الدرجات والتقديرات</span>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <span class="status-badge status-closed"><i class="fas fa-lock"></i> مغلق للتعديل</span>
                                    <span class="text-muted small">لا يمكن تعديل الدرجات - للقراءة فقط</span>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <span class="status-badge status-approved"><i class="fas fa-check-circle"></i> معتمد ومغلق</span>
                                    <span class="text-muted small">تم الاعتماد النهائي - مغلق بشكل دائم</span>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <span class="status-badge status-archived"><i class="fas fa-archive"></i> مؤرشف</span>
                                    <span class="text-muted small">تمت الأرشفة - غير ظاهر في الإدخال</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php if (!empty($subjects_data)): ?>
                
                <!-- Bulk Actions -->
                <form method="POST" id="bulkActionForm">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="bulk_action" id="bulk_action" value="">
                    
                    <div class="bulk-actions">
                        <div class="d-flex flex-wrap align-items-center gap-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="selectAll">
                                <label class="form-check-label" for="selectAll">تحديد الكل</label>
                            </div>
                            <span class="text-muted">|</span>
                            <span id="selectedCount" class="fw-bold">0</span>
                            <span>سجل محدد</span>
                            <div class="flex-grow-1"></div>
                            <button type="button" class="action-btn action-btn-open" onclick="submitBulkAction('open')">
                                <i class="fas fa-lock-open"></i> فتح للتعديل
                            </button>
                            <button type="button" class="action-btn action-btn-close" onclick="submitBulkAction('close')">
                                <i class="fas fa-lock"></i> إغلاق للتعديل
                            </button>
                            <button type="button" class="action-btn action-btn-approve" onclick="submitBulkAction('approve')">
                                <i class="fas fa-check-circle"></i> اعتماد وإغلاق
                            </button>
                            <button type="button" class="action-btn action-btn-archive" onclick="submitBulkAction('archive')">
                                <i class="fas fa-archive"></i> أرشفة
                            </button>
                            <button type="button" class="action-btn action-btn-restore" onclick="submitBulkAction('restore')">
                                <i class="fas fa-trash-restore"></i> استعادة
                            </button>
                        </div>
                    </div>
                    
                    <!-- Status Table -->
                    <div class="content-card">
                        <div class="content-card-header">
                            <h5>
                                <i class="fas fa-table ms-2"></i>
                                قائمة المقررات والحالات
                            </h5>
                            <div class="d-flex align-items-center gap-3">
                                <span class="badge" style="background: var(--primary-gradient); color: white; padding: 6px 15px;">
                                    <i class="fas fa-users ms-1"></i> <?= count(array_unique(array_column($subjects_data, 'student_id'))) ?> طالب
                                </span>
                                <span class="badge" style="background: var(--success-gradient); color: white; padding: 6px 15px;">
                                    <i class="fas fa-book ms-1"></i> <?= count($subjects_data) ?> مادة
                                </span>
                            </div>
                        </div>
                        
                        <div class="scrollable-area">
                            <table class="status-table" id="statusTable">
                                <thead>
                                    <tr>
                                        <th width="40"><input type="checkbox" class="select-all-checkbox"></th>
                                        <th width="50">#</th>
                                        <th width="130">رقم الطالب</th>
                                        <th>اسم الطالب</th>
                                        <th width="100">كود المادة</th>
                                        <th>اسم المادة</th>
                                        <th width="60">الدرجة</th>
                                        <th width="80">التقدير</th>
                                        <th width="120">الحالة</th>
                                        <th width="180">إجراءات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $counter = 1;
                                    foreach ($subjects_data as $row): 
                                        $record_id = $row['student_id'] . '|' . $row['subjectcode'] . '|' . $row['batch_id'] . '|' . $row['semester_id'];
                                    ?>
                                        <tr data-status="<?= $row['status'] ?>">
                                            <td>
                                                <input type="checkbox" class="record-checkbox" value="<?= htmlspecialchars($record_id, ENT_QUOTES, 'UTF-8') ?>">
                                             </div>
                                            <td><?= $counter++ ?></div>
                                            <td><code><?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?></code></div>
                                            <td><div style="text-align: right;"><?= htmlspecialchars($row['student_name'], ENT_QUOTES, 'UTF-8') ?></div></div>
                                            <td><strong><?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?></strong></div>
                                            <td><div style="text-align: right;"><?= htmlspecialchars($row['subjectname'], ENT_QUOTES, 'UTF-8') ?></div></div>
                                            <td>
                                                <?php if ($row['degree'] !== null && $row['degree'] > 0): ?>
                                                    <span class="fw-bold"><?= number_format($row['degree'], 1) ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted">--</span>
                                                <?php endif; ?>
                                             </div>
                                            <td>
                                                <?php if ($row['grade']): ?>
                                                    <span class="badge bg-secondary rounded-pill"><?= htmlspecialchars($row['grade'], ENT_QUOTES, 'UTF-8') ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted">--</span>
                                                <?php endif; ?>
                                             </div>
                                            <td>
                                                <span class="status-badge status-<?= $row['status'] ?>">
                                                    <i class="fas <?= $row['status'] == 'open' ? 'fa-lock-open' : ($row['status'] == 'closed' ? 'fa-lock' : ($row['status'] == 'approved' ? 'fa-check-circle' : 'fa-archive')) ?>"></i>
                                                    <?= htmlspecialchars($row['status_text'], ENT_QUOTES, 'UTF-8') ?>
                                                </span>
                                             </div>
                                            <td>
                                                <div class="action-buttons">
                                                    <?php if ($row['status'] != 'open' && $row['status'] != 'archived'): ?>
                                                        <button type="button" class="action-btn action-btn-open" onclick="toggleStatus('<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>', <?= (int)$row['batch_id'] ?>, <?= (int)$row['semester_id'] ?>, 'open')">
                                                            <i class="fas fa-lock-open"></i> فتح
                                                        </button>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($row['status'] != 'closed' && $row['status'] != 'approved' && $row['status'] != 'archived'): ?>
                                                        <button type="button" class="action-btn action-btn-close" onclick="toggleStatus('<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>', <?= (int)$row['batch_id'] ?>, <?= (int)$row['semester_id'] ?>, 'close')">
                                                            <i class="fas fa-lock"></i> إغلاق
                                                        </button>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($row['status'] != 'approved' && $row['status'] != 'archived'): ?>
                                                        <button type="button" class="action-btn action-btn-approve" onclick="toggleStatus('<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>', <?= (int)$row['batch_id'] ?>, <?= (int)$row['semester_id'] ?>, 'approve')">
                                                            <i class="fas fa-check-circle"></i> اعتماد
                                                        </button>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($row['status'] != 'archived'): ?>
                                                        <button type="button" class="action-btn action-btn-archive" onclick="toggleStatus('<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>', <?= (int)$row['batch_id'] ?>, <?= (int)$row['semester_id'] ?>, 'archive')">
                                                            <i class="fas fa-archive"></i> أرشفة
                                                        </button>
                                                    <?php else: ?>
                                                        <button type="button" class="action-btn action-btn-restore" onclick="toggleStatus('<?= htmlspecialchars($row['student_id'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($row['subjectcode'], ENT_QUOTES, 'UTF-8') ?>', <?= (int)$row['batch_id'] ?>, <?= (int)$row['semester_id'] ?>, 'restore')">
                                                            <i class="fas fa-trash-restore"></i> استعادة
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                             </div>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </form>
                
            <?php else: ?>
                <div class="content-card">
                    <div class="text-center py-5">
                        <i class="fas fa-search fa-4x text-muted mb-3 opacity-50"></i>
                        <h4 class="fw-bold mb-3">لا توجد بيانات</h4>
                        <p class="text-muted mb-4">
                            <?php if (!empty($subject_filter)): ?>
                                لا توجد مواد مسجلة للطلاب بناءً على المادة المحددة
                            <?php elseif ($specialization_id > 0): ?>
                                لا توجد مواد مسجلة للطلاب في هذا التخصص
                            <?php else: ?>
                                لا توجد مواد مسجلة للطلاب بناءً على معايير الترشيح المختارة
                            <?php endif; ?>
                        </p>
                        <a href="subject_enrollment.php" class="btn-gradient">
                            <i class="fas fa-user-graduate ms-2"></i> الذهاب لتسجيل المقررات
                        </a>
                    </div>
                </div>
            <?php endif; ?>
            
        <?php else: ?>
            <div class="content-card">
                <div class="text-center py-5">
                    <i class="fas fa-filter fa-4x text-muted mb-3 opacity-50"></i>
                    <h4 class="fw-bold mb-3">اختر معايير الترشيح</h4>
                    <p class="text-muted mb-4">الرجاء اختيار الكلية، القسم، البرنامج، الدفعة، والفصل الدراسي للبدء</p>
                </div>
            </div>
        <?php endif; ?>
        
    </div>
    <!-- Simple info icon with tooltip -->
<div class="content-card mt-3">
    <div class="d-flex justify-content-between align-items-center">
        <h5 class="fw-bold mb-0">
            <i class="fas fa-info-circle text-primary ms-2"></i>
            إجراءات المقررات الدراسية
            <button type="button" class="btn btn-link p-0 me-2" 
                    data-bs-toggle="tooltip" 
                    data-bs-html="true"
                    title="<div class='text-end' style='direction: rtl;'>
                            <strong>📖 شرح الإجراءات:</strong><br>
                            • <strong class='text-info'>فتح للتعديل</strong>: يسمح بتعديل الدرجات<br>
                            • <strong class='text-warning'>إغلاق للتعديل</strong>: منع مؤقت للتعديل (قابل للفتح)<br>
                            • <strong class='text-success'>اعتماد وإغلاق</strong>: اعتماد نهائي ⚠️ لا يمكن التراجع!<br>
                            • <strong class='text-secondary'>أرشفة</strong>: نقل للأرشيف (قابل للاستعادة)<br>
                            • <strong class='text-primary'>استعادة</strong>: إرجاع من الأرشيف
                            </div>">
                <i class="fas fa-question-circle text-muted"></i>
            </button>
        </h5>
    </div>
</div>

<script>
// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl, {
        html: true,
        placement: 'bottom'
    })
});
</script>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
    <div class="mt-2 text-white">جاري تنفيذ العملية...</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>
// Global variables
let selectedRecords = new Set();

$(document).ready(function() {
    // Load sections when college changes
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        if (collegeId) {
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(sections) {
                    let options = '<option value="">اختر القسم</option>';
                    sections.forEach(section => {
                        options += `<option value="${section.id}">${section.name}</option>`;
                    });
                    $('#section_id').html(options).prop('disabled', false);
                    // After loading sections, load programs (programs are independent)
                    loadPrograms();
                },
                error: function() {
                    $('#section_id').html('<option value="">خطأ في تحميل الأقسام</option>').prop('disabled', false);
                }
            });
        }
    });
    
        function loadPrograms() {
        $.ajax({
            url: 'ajax/get_programs.php',
            method: 'GET',
            dataType: 'json',
            success: function(programs) {
                let options = '<option value="">اختر البرنامج</option>';
                programs.forEach(program => {
                    options += `<option value="${program.id}">${program.name}</option>`;
                });
                $('#program_id').html(options).prop('disabled', false);
            },
            error: function() {
                $('#program_id').html('<option value="">خطأ في تحميل البرامج</option>').prop('disabled', false);
            }
        });
    }
    
    function loadSpecializations() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { section_id: sectionId, program_id: programId },
                dataType: 'json',
                success: function(specializations) {
                    let options = '<option value="">جميع التخصصات</option>';
                    specializations.forEach(spec => {
                        options += `<option value="${spec.specialization_id}">${spec.specialization_name_ar}</option>`;
                    });
                    $('#specialization_id').html(options).prop('disabled', false);
                },
                error: function() {
                    $('#specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                }
            });
        }
    }
    
    <?php if ($section_id && $program_id): ?> loadSpecializations(); <?php endif; ?>
    <?php if ($college_id): ?> $('#college_id').trigger('change'); <?php endif; ?>
    
    $('#section_id, #program_id').on('change', function() { loadSpecializations(); });
    
    // Select All functionality
    $('#selectAll, .select-all-checkbox').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('.record-checkbox').prop('checked', isChecked).trigger('change');
    });
    
    // Individual checkbox change
    $('.record-checkbox').on('change', function() {
        const recordId = $(this).val();
        if ($(this).prop('checked')) {
            selectedRecords.add(recordId);
        } else {
            selectedRecords.delete(recordId);
        }
        updateSelectedCount();
        
        // Update select all checkbox
        const allChecked = $('.record-checkbox:checked').length === $('.record-checkbox').length;
        $('#selectAll, .select-all-checkbox').prop('checked', allChecked);
    });
    
    function updateSelectedCount() {
        $('#selectedCount').text(selectedRecords.size);
    }
    
    // Initialize selected records from checkboxes
    $('.record-checkbox').each(function() {
        if ($(this).prop('checked')) {
            selectedRecords.add($(this).val());
        }
    });
    updateSelectedCount();
    
    // Stat card click filter
    $('.stat-card').on('click', function() {
        const filter = $(this).data('filter');
        if (filter === 'all') {
            window.location.href = updateQueryStringParameter('status_filter', '');
        } else {
            window.location.href = updateQueryStringParameter('status_filter', filter);
        }
    });
    
    function updateQueryStringParameter(key, value) {
        const urlParams = new URLSearchParams(window.location.search);
        if (value) {
            urlParams.set(key, value);
        } else {
            urlParams.delete(key);
        }
        return window.location.pathname + '?' + urlParams.toString();
    }
    
    // Auto-hide alerts
    setTimeout(() => $('.alert').fadeOut(500, function() { $(this).remove(); }), 5000);
});

// Submit bulk action
function submitBulkAction(action) {
    const selected = [];
    $('.record-checkbox:checked').each(function() {
        selected.push($(this).val());
    });
    
    if (selected.length === 0) {
        showAlert('warning', '⚠️ الرجاء تحديد السجلات المراد معالجتها');
        return;
    }
    
    let confirmMessage = '';
    switch(action) {
        case 'open':
            confirmMessage = 'هل أنت متأكد من فتح السجلات المحددة للتعديل؟';
            break;
        case 'close':
            confirmMessage = '⚠️ تحذير: إغلاق السجلات سيمنع أي تعديلات مستقبلية. هل أنت متأكد؟';
            break;
        case 'approve':
            confirmMessage = '⚠️ تحذير: اعتماد السجلات سيغلقها بشكل دائم ولا يمكن التراجع. هل أنت متأكد؟';
            break;
        case 'archive':
            confirmMessage = 'هل أنت متأكد من أرشفة السجلات المحددة؟';
            break;
        case 'restore':
            confirmMessage = 'هل أنت متأكد من استعادة السجلات المحددة؟';
            break;
    }
    
    if (confirm(confirmMessage)) {
        $('#bulk_action').val(action);
        $('#loadingOverlay').fadeIn(200);
        
        // Create a form with all selected records
        const form = $('#bulkActionForm');
        // Remove existing hidden inputs for selected records
        form.find('input[name="selected_records[]"]').remove();
        // Add new hidden inputs
        selected.forEach(record => {
            form.append(`<input type="hidden" name="selected_records[]" value="${record}">`);
        });
        form.submit();
    }
}

// Toggle individual record status via AJAX
function toggleStatus(studentId, subjectCode, batchId, semesterId, action) {
    let confirmMessage = '';
    let actionText = '';
    
    switch(action) {
        case 'open':
            confirmMessage = 'هل أنت متأكد من فتح هذا السجل للتعديل؟';
            actionText = 'فتح';
            break;
        case 'close':
            confirmMessage = '⚠️ تحذير: إغلاق السجل سيمنع أي تعديلات مستقبلية. هل أنت متأكد؟';
            actionText = 'إغلاق';
            break;
        case 'approve':
            confirmMessage = '⚠️ تحذير: اعتماد السجل سيغلقه بشكل دائم ولا يمكن التراجع. هل أنت متأكد؟';
            actionText = 'اعتماد';
            break;
        case 'archive':
            confirmMessage = 'هل أنت متأكد من أرشفة هذا السجل؟';
            actionText = 'أرشفة';
            break;
        case 'restore':
            confirmMessage = 'هل أنت متأكد من استعادة هذا السجل؟';
            actionText = 'استعادة';
            break;
    }
    
    if (confirm(confirmMessage)) {
        $('#loadingOverlay').fadeIn(200);
        
        $.ajax({
            url: window.location.href,
            method: 'POST',
            data: {
                toggle_status: true,
                csrf_token: '<?= $_SESSION['csrf_token'] ?>',
                student_id: studentId,
                subjectcode: subjectCode,
                batch_id: batchId,
                semester_id: semesterId,
                toggle_action: action
            },
            dataType: 'json',
            success: function(response) {
                $('#loadingOverlay').fadeOut(200);
                if (response.success) {
                    showAlert('success', `✅ تم ${actionText} السجل بنجاح`);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showAlert('danger', `❌ فشل ${actionText} السجل: ${response.message}`);
                }
            },
            error: function() {
                $('#loadingOverlay').fadeOut(200);
                showAlert('danger', '❌ حدث خطأ في الاتصال');
            }
        });
    }
}

function showAlert(type, message) {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3" style="z-index: 10000; min-width: 300px; text-align: center;">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    $('body').append(alertHtml);
    setTimeout(() => $('.alert.position-fixed').fadeOut(500, function() { $(this).remove(); }), 3000);
}
</script>

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