<?php
// ============================================
// re_enroll_subjects.php - إعادة تسجيل مقررات الرسوب والإكمال (بدون تكرار)
// ============================================
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// CSRF Protection
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

function sanitizeInput($input, $type = 'string') {
    if ($type === 'student_id') {
        return preg_replace('/[^a-zA-Z0-9\-_]/', '', $input);
    } elseif ($type === 'subjectcode') {
        return preg_replace('/[^a-zA-Z0-9]/', '', $input);
    } elseif ($type === 'int') {
        return (int)$input;
    }
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

function validateInt($value, $min = 0, $max = PHP_INT_MAX) {
    $int = (int)$value;
    return ($int >= $min && $int <= $max) ? $int : 0;
}

$errors = [];
$success_message = '';

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

$programs = [];
$result = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    $programs = $result->fetch_all(MYSQLI_ASSOC);
}

$all_sections = [];
$result = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    $all_sections = $result->fetch_all(MYSQLI_ASSOC);
}

$batches = [];
$result = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value");
if ($result) {
    $batches = $result->fetch_all(MYSQLI_ASSOC);
}

$semesters = [];
$result = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
if ($result) {
    $semesters = $result->fetch_all(MYSQLI_ASSOC);
}

$subjectTypes = [];
$result = $mysqli1->query("SELECT id, name FROM subjecttypes WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    $subjectTypes = $result->fetch_all(MYSQLI_ASSOC);
}
if (empty($subjectTypes)) {
    $subjectTypes = [
        ['id' => 1, 'name' => 'عادي'],
        ['id' => 2, 'name' => 'إزالة رسوب'],
        ['id' => 3, 'name' => 'لم يؤخذ'],
        ['id' => 4, 'name' => 'ترفيع'],
        ['id' => 5, 'name' => 'فروقات منهج'],
        ['id' => 6, 'name' => 'تعليق دراسة']
    ];
}

if (!$canAll && $scopeCollege !== null) {
    $colleges = array_filter($colleges, function($college) use ($scopeCollege) {
        return $college['id'] == $scopeCollege;
    });
}

$college_id = isset($_GET['college_id']) && ctype_digit($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$section_id = isset($_GET['section_id']) && ctype_digit($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
$program_id = isset($_GET['program_id']) && ctype_digit($_GET['program_id']) ? (int)$_GET['program_id'] : 0;
$specialization_id = isset($_GET['specialization_id']) && ctype_digit($_GET['specialization_id']) ? (int)$_GET['specialization_id'] : 0;
$batch_id = isset($_GET['batch_id']) && ctype_digit($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
$semester_id = isset($_GET['semester_id']) && ctype_digit($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
$selected_subjecttype_id = isset($_GET['subjecttype_id']) && ctype_digit($_GET['subjecttype_id']) ? (int)$_GET['subjecttype_id'] : 1;

// ============================================
// Handle re-enrollment submission
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['re_enroll_action'])) {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $errors[] = "طلب غير مصرح به. يرجى تحديث الصفحة والمحاولة مرة أخرى.";
    } else {
        $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
        $subjectcode = sanitizeInput($_POST['subjectcode'] ?? '', 'subjectcode');
        $last_semester_id = validateInt($_POST['last_semester_id'] ?? 0, 1);
        $batch_id_enroll = validateInt($_POST['batch_id'] ?? 0, 1);
        $subjecttype_id_enroll = validateInt($_POST['subjecttype_id'] ?? 0, 1);
        
        if (empty($student_id) || empty($subjectcode)) {
            $errors[] = "بيانات غير مكتملة لإعادة التسجيل";
        } elseif ($last_semester_id <= 0) {
            $errors[] = "لا يوجد فصل دراسي صالح للتسجيل";
        } else {
            $checkStmt = $mysqli1->prepare("
                SELECT id FROM studentsubjects 
                WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ? AND deleted_at IS NULL
            ");
            $checkStmt->bind_param('ssii', $student_id, $subjectcode, $last_semester_id, $batch_id_enroll);
            $checkStmt->execute();
            $existing = $checkStmt->get_result()->fetch_assoc();
            
            if ($existing) {
                $updateStmt = $mysqli1->prepare("
                    UPDATE studentsubjects 
                    SET subjecttype_id = ?, weight = 100.00, updated_at = NOW()
                    WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ? AND deleted_at IS NULL
                ");
                $updateStmt->bind_param('issii', $subjecttype_id_enroll, $student_id, $subjectcode, $last_semester_id, $batch_id_enroll);
                if ($updateStmt->execute()) {
                    $success_message = "تم تحديث تسجيل المادة بنجاح";
                } else {
                    $errors[] = "فشل تحديث التسجيل";
                }
                $updateStmt->close();
            } else {
                $insertStmt = $mysqli1->prepare("
                    INSERT INTO studentsubjects (subjectcode, student_id, semester_id, batch_id, subjecttype_id, weight, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, 100.00, NOW(), NOW())
                ");
                $insertStmt->bind_param('ssiii', $subjectcode, $student_id, $last_semester_id, $batch_id_enroll, $subjecttype_id_enroll);
                if ($insertStmt->execute()) {
                    $success_message = "تم إعادة تسجيل المادة بنجاح";
                } else {
                    $errors[] = "فشل إعادة التسجيل: " . $mysqli1->error;
                }
                $insertStmt->close();
            }
            $checkStmt->close();
        }
    }
}

// ============================================
// Get students with failing grades - WITHOUT DUPLICATES
// ============================================
$failing_cases = [];
$college_name = $section_name = $program_name = $selected_specialization_name = '';

if ($college_id && $section_id && $program_id && $batch_id && $semester_id) {
    // Get names for display
    $nameStmt = $mysqli1->prepare("SELECT name FROM colleges WHERE id = ?");
    $nameStmt->bind_param('i', $college_id);
    $nameStmt->execute();
    $college_name = $nameStmt->get_result()->fetch_assoc()['name'] ?? '';
    $nameStmt->close();
    
    $nameStmt = $mysqli1->prepare("SELECT name FROM sections WHERE id = ?");
    $nameStmt->bind_param('i', $section_id);
    $nameStmt->execute();
    $section_name = $nameStmt->get_result()->fetch_assoc()['name'] ?? '';
    $nameStmt->close();
    
    $nameStmt = $mysqli1->prepare("SELECT name FROM programs WHERE id = ?");
    $nameStmt->bind_param('i', $program_id);
    $nameStmt->execute();
    $program_name = $nameStmt->get_result()->fetch_assoc()['name'] ?? '';
    $nameStmt->close();
    
    if ($specialization_id > 0) {
        $specStmt = $mysqli1->prepare("SELECT specialization_name_ar FROM specializations WHERE specialization_id = ?");
        $specStmt->bind_param('i', $specialization_id);
        $specStmt->execute();
        $selected_specialization_name = $specStmt->get_result()->fetch_assoc()['specialization_name_ar'] ?? '';
        $specStmt->close();
    }
    
    // Build student query with filters
    $studentQuery = "
        SELECT s.student_id, s.student_name, s.college_id, s.section_id, s.program_id, s.batch_id
        FROM students s
        WHERE s.college_id = ? AND s.section_id = ? AND s.program_id = ? AND s.batch_id = ?
        AND s.deleted_at IS NULL
    ";
    $params = [$college_id, $section_id, $program_id, $batch_id];
    $types = "iiii";
    
    if ($specialization_id > 0) {
        $studentQuery .= " AND s.specialization_id = ?";
        $types .= "i";
        $params[] = $specialization_id;
    }
    
    $studentStmt = $mysqli1->prepare($studentQuery);
    $studentStmt->bind_param($types, ...$params);
    $studentStmt->execute();
    $students = $studentStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $studentStmt->close();
    
    // Define failing grades
    $failingGrades = ['F', 'F*', 'F**', 'I', 'W', 'N'];
    $gradePlaceholders = implode(',', array_fill(0, count($failingGrades), '?'));
    
    // Use an associative array to track unique (student_id, subjectcode) pairs
    $uniqueCases = [];
    
    foreach ($students as $student) {
        // Get all failing grades for this student, ordered by semester (most recent first for each subject)
        $failStmt = $mysqli1->prepare("
            SELECT ss.subjectcode, ss.grade, ss.semester_id as original_semester, ss.batch_id,
                   sub.subjectnamea, sub.subjectnamee
            FROM studentsubjects ss
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode
            WHERE ss.student_id = ? AND ss.grade IN ($gradePlaceholders)
            AND ss.deleted_at IS NULL
            ORDER BY ss.subjectcode, ss.semester_id DESC
        ");
        $bindParams = array_merge([$student['student_id']], $failingGrades);
        $failStmt->bind_param('s' . str_repeat('s', count($failingGrades)), ...$bindParams);
        $failStmt->execute();
        $failedSubjects = $failStmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $failStmt->close();
        
        // Track which subjects we've already processed for this student
        $processedSubjects = [];
        
        foreach ($failedSubjects as $failed) {
            $subjectKey = $failed['subjectcode'];
            
            // Skip if we already processed this subject for this student (use only the most recent failing record)
            if (in_array($subjectKey, $processedSubjects)) {
                continue;
            }
            $processedSubjects[] = $subjectKey;
            
            // Check if student has retaken this subject (any enrollment in any semester)
            // We check for ANY enrollment of this subject regardless of grade
            $retakeStmt = $mysqli1->prepare("
                SELECT id, semester_id FROM studentsubjects 
                WHERE student_id = ? AND subjectcode = ? AND deleted_at IS NULL
            ");
            $retakeStmt->bind_param('ss', $student['student_id'], $failed['subjectcode']);
            $retakeStmt->execute();
            $allEnrollments = $retakeStmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $retakeStmt->close();
            
            // Check if there's any enrollment that is NOT the original failing one
            $hasRetaken = false;
            $latestSemester = $failed['original_semester'];
            
            foreach ($allEnrollments as $enrollment) {
                if ($enrollment['semester_id'] != $failed['original_semester']) {
                    $hasRetaken = true;
                }
                if ($enrollment['semester_id'] > $latestSemester) {
                    $latestSemester = $enrollment['semester_id'];
                }
            }
            
            // Only include if NOT retaken
            if (!$hasRetaken) {
                // Get the latest semester overall for this student (from any subject)
                $lastSemStmt = $mysqli1->prepare("
                    SELECT MAX(semester_id) as last_semester 
                    FROM studentsubjects 
                    WHERE student_id = ? AND deleted_at IS NULL
                ");
                $lastSemStmt->bind_param('s', $student['student_id']);
                $lastSemStmt->execute();
                $lastSemResult = $lastSemStmt->get_result()->fetch_assoc();
                $globalLastSemester = $lastSemResult['last_semester'] ?? $semester_id;
                $lastSemStmt->close();
                
                // Create unique key to prevent any duplicate entries across different logic paths
                $uniqueKey = $student['student_id'] . '|' . $failed['subjectcode'];
                
                if (!isset($uniqueCases[$uniqueKey])) {
                    $uniqueCases[$uniqueKey] = [
                        'student_id' => $student['student_id'],
                        'student_name' => $student['student_name'],
                        'college_id' => $student['college_id'],
                        'section_id' => $student['section_id'],
                        'program_id' => $student['program_id'],
                        'subjectcode' => $failed['subjectcode'],
                        'subjectname' => $failed['subjectnamea'] . ($failed['subjectnamee'] ? " ({$failed['subjectnamee']})" : ''),
                        'grade' => $failed['grade'],
                        'original_semester' => $failed['original_semester'],
                        'last_semester' => $globalLastSemester,
                        'batch_id' => $student['batch_id']
                    ];
                }
            }
        }
    }
    
    // Convert the unique cases array to a simple indexed array
    $failing_cases = array_values($uniqueCases);
}

include 'header.php';
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إعادة تسجيل مقررات الرسوب والإكمال | نظام التسجيل الأكاديمي</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { text-align: right; direction: rtl; }
        body { font-family: 'Cairo', sans-serif; background: #f0f4f8; min-height: 100vh; padding: 30px 20px; }
        .main-wrapper { max-width: 1400px; margin: auto; }
        .page-header { background: linear-gradient(135deg, #1e3c72, #2a5298); border-radius: 30px; padding: 30px 40px; margin-bottom: 30px; color: white; box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
        .filter-card, .content-card { background: white; border-radius: 28px; padding: 25px; margin-bottom: 25px; box-shadow: 0 8px 20px rgba(0,0,0,0.05); border: 1px solid #e2e8f0; }
        .btn-gradient { background: linear-gradient(135deg, #00b09b, #96c93d); border: none; color: white; padding: 10px 25px; border-radius: 50px; font-weight: 600; }
        .btn-primary-custom { background: linear-gradient(135deg, #1e3c72, #2a5298); border: none; color: white; padding: 10px 25px; border-radius: 50px; font-weight: 600; }
        .btn-reset { background: linear-gradient(135deg, #6b7280, #4b5563); border: none; color: white; padding: 10px 20px; border-radius: 50px; }
        .grade-badge { background: #dc2626; color: white; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: bold; display: inline-block; }
        .semester-badge { background: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; }
        .enroll-btn { background: linear-gradient(135deg, #10b981, #059669); border: none; color: white; padding: 8px 18px; border-radius: 40px; font-size: 0.85rem; transition: 0.2s; }
        .enroll-btn:hover { transform: translateY(-2px); background: linear-gradient(135deg, #059669, #047857); }
        .case-row { transition: 0.2s; }
        .case-row:hover { background: #fefce8; }
        .alert-custom { border-radius: 20px; animation: slideIn 0.5s ease; margin-bottom: 20px; }
        @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.85rem; display: inline-flex; align-items: center; gap: 5px; }
        .stat-card { background: linear-gradient(135deg, #f5f7fa, #e9edf5); border-radius: 25px; padding: 20px; text-align: center; }
        .required-field::after { content: " *"; color: #e53e3e; }
        .form-control, .form-select { border-radius: 15px; padding: 10px 15px; border: 2px solid #e2e8f0; text-align: right; }
        @media (max-width: 768px) { .page-header { padding: 20px; } }
        .table-responsive { border-radius: 20px; overflow: hidden; }
        .info-note { background: #fef9e6; border-right: 4px solid #f59e0b; padding: 15px; border-radius: 15px; margin-bottom: 20px; }
    </style>
</head>
<body>
<div class="main-wrapper">
    <!-- Page Header -->
    <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
        <div>
            <h1><i class="fas fa-arrow-rotate-left ms-3"></i> إعادة تسجيل مقررات الرسوب والإكمال</h1>
            <p class="mb-0 mt-2"><i class="fas fa-exclamation-triangle ms-2"></i> التقديرات المستهدفة: F , F* , F** , I , W , N | يتم التسجيل في آخر فصل دراسي للطالب</p>
        </div>
        <a href="admin_dashboard.php" class="btn btn-outline-light rounded-pill px-4"><i class="fas fa-arrow-right ms-2"></i> العودة للوحة التحكم </a>
    </div>

    <!-- Alert Messages -->
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger alert-dismissible fade show alert-custom" role="alert">
            <i class="fas fa-exclamation-circle ms-2"></i>
            <?php foreach ($errors as $error): echo "<div>• " . htmlspecialchars($error) . "</div>"; 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 alert-custom" role="alert">
            <i class="fas fa-check-circle ms-2"></i> <?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Info Note -->
    <div class="info-note">
        <i class="fas fa-info-circle text-warning ms-2"></i>
        <strong>ملاحظة:</strong> يتم عرض كل مقرر راسب لمرة واحدة فقط لكل طالب، حتى لو كان الطالب قد رسب في نفس المقرر عدة مرات. يتم إعادة التسجيل في <strong>آخر فصل دراسي</strong> مسجل للطالب في النظام.
    </div>

    <!-- Filter Card -->
    <div class="filter-card">
        <form method="get" class="row g-4" 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>
                    <option value="">اختر الكلية</option>
                    <?php foreach ($colleges as $college): ?>
                        <option value="<?= (int)$college['id'] ?>" <?= ($college_id == $college['id']) ? 'selected' : '' ?>><?= htmlspecialchars($college['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </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']) ?></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']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-12">
                <div class="d-flex gap-3 justify-content-end">
                    <a href="re_enroll_subjects.php" class="btn-reset"><i class="fas fa-redo-alt ms-2"></i> إعادة تعيين</a>
                    <button type="submit" class="btn-primary-custom"><i class="fas fa-search ms-2"></i> بحث عن الحالات</button>
                </div>
            </div>
        </form>
        
        <?php if ($college_id || $section_id || $program_id || $batch_id): ?>
            <div class="mt-3 d-flex flex-wrap gap-2">
                <span class="fw-bold"><i class="fas fa-filter"></i> الفلاتر النشطة:</span>
                <?php if ($college_name): ?><span class="filter-badge"><i class="fas fa-university"></i> <?= htmlspecialchars($college_name) ?></span><?php endif; ?>
                <?php if ($section_name): ?><span class="filter-badge"><i class="fas fa-layer-group"></i> <?= htmlspecialchars($section_name) ?></span><?php endif; ?>
                <?php if ($program_name): ?><span class="filter-badge"><i class="fas fa-graduation-cap"></i> <?= htmlspecialchars($program_name) ?></span><?php endif; ?>
                <?php if ($selected_specialization_name): ?><span class="filter-badge"><i class="fas fa-tag"></i> <?= htmlspecialchars($selected_specialization_name) ?></span><?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Subject Type Selection -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="content-card">
                <label class="form-label fw-bold"><i class="fas fa-tag ms-1"></i> نوع التسجيل لإعادة التسجيل <span class="text-danger">*</span></label>
                <select class="form-select" id="global_subjecttype_id">
                    <?php foreach ($subjectTypes as $type): ?>
                        <option value="<?= (int)$type['id'] ?>" <?= ($selected_subjecttype_id == $type['id']) ? 'selected' : '' ?>><?= htmlspecialchars($type['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <small class="text-muted">سيتم استخدام هذا النوع عند إعادة تسجيل المقررات الراسبة</small>
            </div>
        </div>
    </div>

    <!-- Results Section -->
    <div class="content-card">
        <div class="d-flex justify-content-between align-items-center flex-wrap mb-3">
            <h5><i class="fas fa-list-check ms-2"></i> حالات المقررات الراسبة (لم يتم إعادة تسجيلها)</h5>
            <span class="badge bg-danger rounded-pill px-3 py-2"><?= count($failing_cases) ?> حالة (فريدة)</span>
        </div>
        
        <?php if (empty($failing_cases) && $college_id && $section_id && $program_id && $batch_id): ?>
            <div class="text-center py-5">
                <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                <h5>لا توجد حالات</h5>
                <p class="text-muted">جميع المقررات الراسبة تم إعادة تسجيلها أو لا توجد مقررات راسبة بهذه المعايير</p>
            </div>
        <?php elseif (empty($failing_cases)): ?>
            <div class="text-center py-5">
                <i class="fas fa-search fa-4x text-muted mb-3"></i>
                <h5>الرجاء اختيار معايير البحث</h5>
                <p class="text-muted">اختر الكلية، القسم، البرنامج، الدفعة والفصل الدراسي ثم اضغط بحث</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>الطالب</th>
                            <th>المقرر الراسب</th>
                            <th>التقدير</th>
                            <th>الفصل الأصلي</th>
                            <th>آخر فصل دراسي للطالب</th>
                            <th>الإجراء</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($failing_cases as $case): ?>
                            <tr class="case-row">
                                <td>
                                    <strong><?= htmlspecialchars($case['student_name']) ?></strong><br>
                                    <small class="text-muted"><?= htmlspecialchars($case['student_id']) ?></small>
                                </td>
                                <td>
                                    <strong><?= htmlspecialchars($case['subjectcode']) ?></strong><br>
                                    <small><?= htmlspecialchars($case['subjectname']) ?></small>
                                </td>
                                <td><span class="grade-badge"><?= htmlspecialchars($case['grade']) ?></span></td>
                                <td><span class="semester-badge">الفصل <?= (int)$case['original_semester'] ?></span></td>
                                <td>
                                    <span class="badge bg-info text-dark">الفصل <?= (int)$case['last_semester'] ?></span>
                                    <br><small>سيتم التسجيل فيه</small>
                                </td>
                                <td>
                                    <form method="POST" action="" onsubmit="return confirm('⚠️ هل أنت متأكد من إعادة تسجيل المقرر <?= htmlspecialchars($case['subjectcode']) ?> للطالب <?= htmlspecialchars($case['student_name']) ?>؟\nسيتم التسجيل في الفصل <?= (int)$case['last_semester'] ?> بنوع التسجيل المحدد.')">
                                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                                        <input type="hidden" name="re_enroll_action" value="1">
                                        <input type="hidden" name="student_id" value="<?= htmlspecialchars($case['student_id']) ?>">
                                        <input type="hidden" name="subjectcode" value="<?= htmlspecialchars($case['subjectcode']) ?>">
                                        <input type="hidden" name="last_semester_id" value="<?= (int)$case['last_semester'] ?>">
                                        <input type="hidden" name="batch_id" value="<?= (int)$case['batch_id'] ?>">
                                        <input type="hidden" name="subjecttype_id" class="subjecttype_hidden" value="<?= $selected_subjecttype_id ?>">
                                        <button type="submit" class="enroll-btn"><i class="fas fa-plus-circle ms-1"></i> إعادة التسجيل</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Statistics -->
            <div class="row g-4 mt-3">
                <div class="col-md-4">
                    <div class="stat-card">
                        <i class="fas fa-users fa-2x mb-2"></i>
                        <h3><?= count(array_unique(array_column($failing_cases, 'student_id'))) ?></h3>
                        <div>طلاب لديهم رسوب</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stat-card">
                        <i class="fas fa-book fa-2x mb-2"></i>
                        <h3><?= count($failing_cases) ?></h3>
                        <div>مقرر راسب غير معاد (فريد)</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stat-card">
                        <i class="fas fa-arrow-rotate-left fa-2x mb-2"></i>
                        <h3>جاهز للتسجيل</h3>
                        <div>باستخدام آخر فصل دراسي</div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </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() {
    // Update hidden subjecttype_id fields when global selection changes
    $('#global_subjecttype_id').on('change', function() {
        $('.subjecttype_hidden').val($(this).val());
    });
    
    // Load sections when college changes
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        const sectionSelect = $('#section_id');
        const programSelect = $('#program_id');
        const specializationSelect = $('#specialization_id');
        
        sectionSelect.html('<option value="">اختر القسم</option>').prop('disabled', true);
        programSelect.html('<option value="">اختر البرنامج</option>').prop('disabled', true);
        specializationSelect.html('<option value="">جميع التخصصات</option>').prop('disabled', true);
        
        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(function(section) {
                        options += `<option value="${section.id}" ${section.id == <?= $section_id ?> ? 'selected' : ''}>${escapeHtml(section.name)}</option>`;
                    });
                    sectionSelect.html(options).prop('disabled', false);
                    loadPrograms(collegeId);
                },
                error: function() { sectionSelect.html('<option value="">خطأ في التحميل</option>').prop('disabled', false); }
            });
        } else {
            sectionSelect.prop('disabled', true);
            programSelect.prop('disabled', true);
            specializationSelect.prop('disabled', true);
        }
    });
    
    function loadPrograms(collegeId) {
        const programSelect = $('#program_id');
        programSelect.html('<option value="">اختر البرنامج</option>').prop('disabled', true);
        $.ajax({
            url: 'ajax/get_programs.php',
            method: 'GET',
            data: { college_id: collegeId },
            dataType: 'json',
            success: function(programs) {
                let options = '<option value="">اختر البرنامج</option>';
                programs.forEach(function(program) {
                    options += `<option value="${program.id}" ${program.id == <?= $program_id ?> ? 'selected' : ''}>${escapeHtml(program.name)}</option>`;
                });
                programSelect.html(options).prop('disabled', false);
            },
            error: function() { programSelect.html('<option value="">خطأ</option>').prop('disabled', false); }
        });
    }
    
    function loadSpecializations() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            $('#specialization_id').prop('disabled', true);
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { section_id: sectionId, program_id: programId },
                dataType: 'json',
                success: function(specializations) {
                    let options = '<option value="">جميع التخصصات</option>';
                    specializations.forEach(function(spec) {
                        options += `<option value="${spec.specialization_id}" ${spec.specialization_id == <?= $specialization_id ?> ? 'selected' : ''}>${escapeHtml(spec.specialization_name_ar)}</option>`;
                    });
                    $('#specialization_id').html(options).prop('disabled', false);
                },
                error: function() { $('#specialization_id').html('<option value="">خطأ</option>').prop('disabled', false); }
            });
        }
    }
    
    $('#section_id, #program_id').on('change', loadSpecializations);
    
    function escapeHtml(text) {
        if (!text) return '';
        return text.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }
    
    <?php if ($college_id): ?>$('#college_id').trigger('change');<?php endif; ?>
    <?php if ($section_id && $program_id): ?>loadSpecializations();<?php endif; ?>
});
</script>

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