<?php
/**
 * حضور الطلاب - قوائم الحضور، إدخال الحضور، وتقرير عدم السماح بالجلوس
 * Student Attendance: lists per course, entry, and report (25% absence = no exam)
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';

$auth = new Auth();
if (!$auth->isLoggedIn()) {
    header('Location: login.php');
    exit;
}

$db = Database::getInstance();

// عدد المحاضرات في الفصل الدراسي
define('ATTENDANCE_LECTURES_COUNT', 12);

// نسبة الغياب التي تمنع من الجلوس (25%)
define('ATTENDANCE_ABSENCE_THRESHOLD_RATIO', 0.25);

function getSemesterName($number) {
    $n = (int)$number;
    $names = [1 => 'الفصل الأول', 2 => 'الفصل الثاني', 3 => 'الفصل الثالث', 4 => 'الفصل الرابع',
              5 => 'الفصل الخامس', 6 => 'الفصل السادس', 7 => 'الفصل السابع', 8 => 'الفصل الثامن'];
    return $names[$n] ?? ('فصل ' . $n);
}

// التأكد من وجود جدول الحضور
$db->query("
    CREATE TABLE IF NOT EXISTS attendance (
        id INT PRIMARY KEY AUTO_INCREMENT,
        student_id INT NOT NULL,
        course_id INT NOT NULL,
        semester_id INT NOT NULL,
        lecture_1 TINYINT(1) NULL,
        lecture_2 TINYINT(1) NULL,
        lecture_3 TINYINT(1) NULL,
        lecture_4 TINYINT(1) NULL,
        lecture_5 TINYINT(1) NULL,
        lecture_6 TINYINT(1) NULL,
        lecture_7 TINYINT(1) NULL,
        lecture_8 TINYINT(1) NULL,
        lecture_9 TINYINT(1) NULL,
        lecture_10 TINYINT(1) NULL,
        lecture_11 TINYINT(1) NULL,
        lecture_12 TINYINT(1) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_attendance (student_id, course_id, semester_id),
        FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
        FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
        FOREIGN KEY (semester_id) REFERENCES semesters(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

$college_id = isset($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$major_id = isset($_GET['major_id']) ? (int)$_GET['major_id'] : 0;
$semester_number = isset($_GET['semester_number']) ? (int)$_GET['semester_number'] : 0;
$academic_year = isset($_GET['academic_year']) ? trim($_GET['academic_year']) : '';
$semester_id = 0;
$message = '';
$tab = isset($_GET['tab']) ? $_GET['tab'] : 'lists'; // lists | entry | report
if (isset($_GET['saved']) && $_GET['saved'] == '1') {
    $message = '<div class="alert alert-success">تم حفظ الحضور بنجاح.</div>';
}

// حفظ إدخال الحضور
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_attendance'])) {
    $sem_id = (int)($_POST['semester_id'] ?? 0);
    $course_id = (int)($_POST['course_id'] ?? 0);
    if ($sem_id && $course_id && isset($_POST['attendance']) && is_array($_POST['attendance'])) {
        foreach ($_POST['attendance'] as $student_id => $lectures) {
            $student_id = (int)$student_id;
            $row = ['student_id' => $student_id, 'course_id' => $course_id, 'semester_id' => $sem_id];
            for ($i = 1; $i <= ATTENDANCE_LECTURES_COUNT; $i++) {
                $key = 'lecture_' . $i;
                $row[$key] = isset($lectures[$i]) && $lectures[$i] !== '' ? ($lectures[$i] === '1' ? 1 : 0) : null;
            }
            $cols = array_keys($row);
            $placeholders = implode(',', array_fill(0, count($cols), '?'));
            $up = [];
            foreach (array_slice($cols, 3) as $c) $up[] = $c . ' = VALUES(' . $c . ')';
            $sql = "INSERT INTO attendance (" . implode(',', $cols) . ") VALUES ($placeholders)
                    ON DUPLICATE KEY UPDATE " . implode(', ', $up);
            $db->query($sql, array_values($row));
        }
        $redir = 'attendance.php?college_id=' . (int)($_POST['college_id'] ?? 0) . '&major_id=' . (int)($_POST['major_id'] ?? 0) . '&semester_number=' . (int)($_POST['semester_number'] ?? 0) . '&academic_year=' . urlencode($_POST['academic_year'] ?? '') . '&tab=entry&entry_course_id=' . $course_id . '&saved=1';
        header('Location: ' . $redir);
        exit;
    }
}

// استخراج semester_id
if ($college_id && $major_id && $semester_number && $academic_year !== '') {
    $sem = $db->fetchOne(
        "SELECT id FROM semesters WHERE major_id = ? AND semester_number = ? AND academic_year = ?",
        [$major_id, $semester_number, $academic_year]
    );
    if ($sem) {
        $semester_id = (int)$sem['id'];
    }
}

$semester_info = null;
$college_name = '';
$courses_list = [];
$students_by_course = []; // course_id => [ students ]

if ($semester_id) {
    $semester_info = $db->fetchOne(
        "SELECT s.*, m.name_ar as major_name, c.name_ar as college_name, c.id as college_id
         FROM semesters s
         JOIN majors m ON s.major_id = m.id
         JOIN colleges c ON m.college_id = c.id
         WHERE s.id = ?",
        [$semester_id]
    );
    if ($semester_info) {
        if (!$auth->belongsToCollege($semester_info['college_id']) && !$auth->hasRole('admin')) {
            header('Location: dashboard.php');
            exit;
        }
        $college_name = $semester_info['college_name'];
        // مواد لها تسجيل طلاب في هذا الفصل — كل مادة مرة واحدة فقط (مفتاح: رمز + اسم بعد trim)
        $course_ids_raw = $db->fetchAll(
            "SELECT DISTINCT sc.course_id
             FROM student_courses sc
             WHERE sc.semester_id = ?",
            [$semester_id]
        );
        $unique_course_ids = array_values(array_unique(array_column($course_ids_raw, 'course_id')));
        $by_key = []; // مفتاح فريد => ['id'=>..., 'code'=>..., 'name_ar'=>..., 'ids'=>[..]]
        foreach ($unique_course_ids as $course_id) {
            $c = $db->fetchOne("SELECT id, code, name_ar FROM courses WHERE id = ?", [$course_id]);
            if (!$c) continue;
            $code = preg_replace('/\s+/u', ' ', trim((string)($c['code'] ?? '')));
            $name = preg_replace('/\s+/u', ' ', trim((string)($c['name_ar'] ?? '')));
            $key = $code . '|' . $name; // مفتاح فريد: رمز+اسم (تطبيع المسافات) لتفادي تكرار القائمة
            if (!isset($by_key[$key])) {
                $by_key[$key] = ['id' => (int)$c['id'], 'code' => $c['code'], 'name_ar' => $c['name_ar'], 'ids' => [(int)$c['id']]];
            } else {
                if (!in_array((int)$c['id'], $by_key[$key]['ids'], true)) {
                    $by_key[$key]['ids'][] = (int)$c['id'];
                }
            }
        }
        $courses_list = [];
        foreach ($by_key as $info) {
            $courses_list[] = ['id' => $info['id'], 'code' => $info['code'], 'name_ar' => $info['name_ar'], '_ids' => $info['ids']];
        }
        // تمريرة ثانية: دمج أي سجلات تشارك نفس الرمز والاسم (بعد تطبيع) لتفادي تكرار القائمة
        $seen_key = [];
        $merged = [];
        foreach ($courses_list as $c) {
            $nk = preg_replace('/\s+/u', ' ', trim((string)($c['code'] ?? ''))) . '|' . preg_replace('/\s+/u', ' ', trim((string)($c['name_ar'] ?? '')));
            if (isset($seen_key[$nk])) {
                $idx = $seen_key[$nk];
                $merged[$idx]['_ids'] = array_values(array_unique(array_merge($merged[$idx]['_ids'], $c['_ids'])));
                continue;
            }
            $seen_key[$nk] = count($merged);
            $merged[] = $c;
        }
        $courses_list = array_values($merged);
        usort($courses_list, function ($a, $b) { return strcmp(trim($a['code']), trim($b['code'])); });
        foreach ($courses_list as $course) {
            $ids = $course['_ids'];
            $cid = $course['id'];
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $students_by_course[$cid] = $db->fetchAll(
                "SELECT DISTINCT s.id, s.student_number, s.full_name_ar
                 FROM students s
                 INNER JOIN student_courses sc ON sc.student_id = s.id AND sc.semester_id = ?
                 WHERE sc.course_id IN ($placeholders)
                 ORDER BY s.full_name_ar",
                array_merge([$semester_id], $ids)
            );
        }
    }
}

// جلب قيم الحضور المحفوظة (لصفحة الإدخال أو التقرير) — لكل معرفات المواد المدمجة
$attendance_records = []; // (student_id, course_id) => row from attendance
if ($semester_id && !empty($courses_list)) {
    $all_ids = [];
    foreach ($courses_list as $c) {
        if (!empty($c['_ids'])) {
            $all_ids = array_merge($all_ids, $c['_ids']);
        } else {
            $all_ids[] = $c['id'];
        }
    }
    $all_ids = array_unique($all_ids);
    $placeholders = implode(',', array_fill(0, count($all_ids), '?'));
    $rows = $db->fetchAll(
        "SELECT * FROM attendance WHERE semester_id = ? AND course_id IN ($placeholders)",
        array_merge([$semester_id], $all_ids)
    );
    foreach ($rows as $r) {
        $attendance_records[$r['student_id'] . '_' . $r['course_id']] = $r;
    }
}

// عتبة الغياب (25% من 12 = 3 محاضرات)
$attendance_threshold = (int)ceil(ATTENDANCE_LECTURES_COUNT * ATTENDANCE_ABSENCE_THRESHOLD_RATIO);

// تقرير شامل: جميع الطلاب لكل مادة مع حالة السماح بالجلوس (مسموح / غير مسموح)
$report_all_by_course = []; // course_id => [ ['student'=>..., 'absent'=>n, 'total'=>n, 'allowed'=>bool], ... ]
if ($semester_id && !empty($courses_list)) {
    foreach ($courses_list as $course) {
        $cid = $course['id'];
        $report_all_by_course[$cid] = [];
        $lookup_ids = !empty($course['_ids']) ? $course['_ids'] : [$cid];
        foreach ($students_by_course[$cid] ?? [] as $stu) {
            $rec = null;
            foreach ($lookup_ids as $aid) {
                $key = $stu['id'] . '_' . $aid;
                if (!empty($attendance_records[$key])) {
                    $rec = $attendance_records[$key];
                    break;
                }
            }
            $absent = 0;
            $total = 0;
            for ($i = 1; $i <= ATTENDANCE_LECTURES_COUNT; $i++) {
                $col = 'lecture_' . $i;
                if ($rec && isset($rec[$col]) && $rec[$col] !== null) {
                    $total++;
                    if ((int)$rec[$col] === 0) $absent++;
                }
            }
            // مسموح فقط إذا سُجّل الحضور (total > 0) وكان الغياب أقل من 25%
            // إذا لم يُسجّل أي حضور (total === 0) أو غياب >= العتبة => غير مسموح
            $allowed = ($total > 0) && ($absent < $attendance_threshold);
            $report_all_by_course[$cid][] = [
                'student' => $stu,
                'absent' => $absent,
                'total' => $total,
                'allowed' => $allowed,
                'not_recorded' => ($total === 0) // لم يُسجّل الحضور بعد
            ];
        }
    }
}

// للتوافق مع أي استخدام سابق: قائمة غير المسموح لهم فقط
$not_allowed_by_course = [];
foreach ($report_all_by_course as $cid => $list) {
    $not_allowed_by_course[$cid] = array_filter($list, function ($item) { return !$item['allowed']; });
}

// الكليات والتخصصات والفصول والسنوات
$colleges = [];
if ($auth->hasRole('admin')) {
    $colleges = $db->fetchAll("SELECT id, name_ar FROM colleges ORDER BY name_ar");
} else {
    $user = $auth->getCurrentUser();
    if ($user && !empty($user['college_id'])) {
        $colleges = $db->fetchAll("SELECT id, name_ar FROM colleges WHERE id = ?", [$user['college_id']]);
    }
}
$majors = [];
if ($college_id) {
    $majors = $db->fetchAll("SELECT id, name_ar FROM majors WHERE college_id = ? ORDER BY name_ar", [$college_id]);
}
$semesters = [];
if ($major_id) {
    $semesters = $db->fetchAll(
        "SELECT DISTINCT semester_number FROM semesters WHERE major_id = ? ORDER BY semester_number",
        [$major_id]
    );
}
$academic_years = [];
if ($major_id && $semester_number) {
    $academic_years = $db->fetchAll(
        "SELECT DISTINCT academic_year FROM semesters WHERE major_id = ? AND semester_number = ? ORDER BY academic_year DESC",
        [$major_id, $semester_number]
    );
}

$base_url = 'attendance.php?college_id=' . $college_id . '&major_id=' . $major_id . '&semester_number=' . $semester_number . '&academic_year=' . urlencode($academic_year);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>حضور الطلاب</title>
    <?php include __DIR__ . '/includes/compatibility.php'; ?>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .attendance-header { text-align: center; margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 8px; }
        .attendance-header h1 { font-size: 1.4em; color: #333; margin: 0 0 8px 0; }
        .attendance-header h2 { font-size: 1.2em; color: #667eea; margin: 0; }
        .semester-selector { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: inline-block; min-width: 120px; }
        .tabs { margin: 20px 0; border-bottom: 2px solid #667eea; }
        .tabs a { display: inline-block; padding: 12px 24px; margin-left: 5px; background: #e0e0e0; color: #333; text-decoration: none; border-radius: 8px 8px 0 0; }
        .tabs a.active { background: #667eea; color: white; }
        .tabs a:hover { background: #5a6fd6; color: white; }
        .att-table { width: 100%; border-collapse: collapse; margin: 15px 0; font-size: 14px; }
        .att-table th, .att-table td { border: 1px solid #ddd; padding: 8px; text-align: center; }
        .att-table th { background: #667eea; color: white; }
        .att-table tr:nth-child(even) { background: #f9f9f9; }
        .att-lecture-col { min-width: 38px; }
        .no-print { }
        @media print {
            .no-print, .semester-selector, .tabs, .main-header, .main-footer, .btn { display: none !important; }
            .list-per-course { page-break-after: always; }
            .list-per-course:last-child { page-break-after: auto; }
        }
        .report-block { margin-bottom: 25px; padding: 15px; background: #fff8e1; border: 1px solid #ffc107; border-radius: 8px; }
        .report-block h4 { margin: 0 0 10px 0; color: #f57c00; }
        .alert { padding: 12px; border-radius: 6px; margin-bottom: 15px; }
        .alert-success { background: #e8f5e9; color: #2e7d32; border: 1px solid #a5d6a7; }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <div class="container">
        <div class="page-header no-print">
            <h2>حضور الطلاب</h2>
            <p style="margin-top: 8px; color: #666; font-size: 14px;">قوائم الحضور للطباعة • إدخال الحضور • <strong>تقرير الحضور (الجميع — مسموح / غير مسموح بالجلوس)</strong>. بعد اختيار الكلية والتخصص والفصل والسنة تظهر التبويبات.</p>
        </div>

        <?php echo $message; ?>

        <div class="semester-selector">
            <form method="GET" action="attendance.php" id="selForm">
                <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tab); ?>">
                <div class="form-group">
                    <label>الكلية:</label>
                    <select name="college_id" id="college_select" required onchange="document.getElementById('selForm').submit();">
                        <option value="">-- اختر الكلية --</option>
                        <?php foreach ($colleges as $c): ?>
                            <option value="<?php echo $c['id']; ?>" <?php echo $college_id == $c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name_ar']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if ($college_id): ?>
                <div class="form-group">
                    <label>التخصص:</label>
                    <select name="major_id" id="major_select" required onchange="document.getElementById('selForm').submit();">
                        <option value="">-- اختر التخصص --</option>
                        <?php foreach ($majors as $m): ?>
                            <option value="<?php echo $m['id']; ?>" <?php echo $major_id == $m['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($m['name_ar']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <?php if ($major_id): ?>
                <div class="form-group">
                    <label>الفصل الدراسي:</label>
                    <select name="semester_number" onchange="document.getElementById('selForm').submit();">
                        <option value="">-- اختر الفصل --</option>
                        <?php foreach ($semesters as $s): ?>
                            <option value="<?php echo $s['semester_number']; ?>" <?php echo $semester_number == $s['semester_number'] ? 'selected' : ''; ?>><?php echo getSemesterName($s['semester_number']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <?php if ($major_id && $semester_number): ?>
                <div class="form-group">
                    <label>السنة الدراسية:</label>
                    <select name="academic_year" onchange="document.getElementById('selForm').submit();">
                        <option value="">-- اختر السنة --</option>
                        <?php foreach ($academic_years as $y): ?>
                            <option value="<?php echo htmlspecialchars($y['academic_year']); ?>" <?php echo $academic_year === $y['academic_year'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($y['academic_year']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
            </form>
        </div>

        <?php if ($semester_id && $semester_info): ?>
        <p class="no-print" style="margin-bottom: 10px; color: #555;">اختر أحد التبويبات:</p>
        <div class="tabs no-print">
            <a href="<?php echo $base_url; ?>&tab=lists" class="<?php echo $tab === 'lists' ? 'active' : ''; ?>">قوائم الحضور للطباعة</a>
            <a href="<?php echo $base_url; ?>&tab=entry" class="<?php echo $tab === 'entry' ? 'active' : ''; ?>">إدخال الحضور</a>
            <a href="<?php echo $base_url; ?>&tab=report" class="<?php echo $tab === 'report' ? 'active' : ''; ?>">📋 تقرير الحضور (الجميع)</a>
        </div>

        <?php if ($tab === 'lists'): ?>
        <!-- قوائم الحضور لكل مادة - تسلم لاستاذ المادة -->
        <p class="no-print" style="margin-bottom: 15px;">استخرج القوائم حسب الفصل والسنة المحددة. كل قائمة لمادة واحدة تحتوي على الطلاب المسجلين فيها مع أعمدة المحاضرات الـ <?php echo ATTENDANCE_LECTURES_COUNT; ?> (م_1 إلى م_<?php echo ATTENDANCE_LECTURES_COUNT; ?>). تُسلّم القائمة لأستاذ المادة لتعبئتها ثم تُفرغ في نظام الحضور.</p>
        <?php foreach ($courses_list as $course): ?>
        <?php $students = $students_by_course[$course['id']] ?? []; if (empty($students)) continue; ?>
        <div class="list-per-course">
            <div class="attendance-header">
                <h1><?php echo htmlspecialchars($college_name); ?></h1>
                <h2>قائمة حضور — <?php echo htmlspecialchars($course['name_ar']); ?> (<?php echo htmlspecialchars($course['code']); ?>)</h2>
                <p style="margin: 8px 0 0 0; color: #666;"><?php echo getSemesterName($semester_info['semester_number']); ?> — <?php echo htmlspecialchars($semester_info['academic_year']); ?></p>
            </div>
            <table class="att-table">
                <thead>
                    <tr>
                        <th>م</th>
                        <th>الرقم الجامعي</th>
                        <th>الاسم</th>
                        <?php for ($i = 1; $i <= ATTENDANCE_LECTURES_COUNT; $i++): ?>
                        <th class="att-lecture-col">م_<?php echo $i; ?></th>
                        <?php endfor; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1; foreach ($students as $stu): ?>
                    <tr>
                        <td><?php echo $sn++; ?></td>
                        <td><?php echo htmlspecialchars($stu['student_number']); ?></td>
                        <td style="text-align: right;"><?php echo htmlspecialchars($stu['full_name_ar']); ?></td>
                        <?php for ($i = 1; $i <= ATTENDANCE_LECTURES_COUNT; $i++): ?>
                        <td></td>
                        <?php endfor; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <p style="margin-top: 10px; font-size: 13px; color: #666;">تسلم هذه القائمة لأستاذ المادة لتعبيئتها ثم إفراغها في نظام الحضور والغياب.</p>
        </div>
        <?php endforeach; ?>
        <div class="no-print" style="margin-top: 20px;">
            <button type="button" onclick="window.print();" class="btn btn-primary">طباعة القوائم</button>
        </div>
        <?php endif; ?>

        <?php if ($tab === 'entry'): ?>
        <!-- إدخال الحضور: اختيار المادة ثم جدول طلاب x محاضرات -->
        <div class="no-print">
            <form method="GET" style="margin-bottom: 20px;">
                <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
                <input type="hidden" name="major_id" value="<?php echo $major_id; ?>">
                <input type="hidden" name="semester_number" value="<?php echo $semester_number; ?>">
                <input type="hidden" name="academic_year" value="<?php echo htmlspecialchars($academic_year); ?>">
                <input type="hidden" name="tab" value="entry">
                <label>المادة:</label>
                <select name="entry_course_id" onchange="this.form.submit();">
                    <option value="">-- اختر المادة --</option>
                    <?php foreach ($courses_list as $c): ?>
                        <option value="<?php echo $c['id']; ?>" <?php echo isset($_GET['entry_course_id']) && (int)$_GET['entry_course_id'] === (int)$c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['code'] . ' - ' . $c['name_ar']); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
        <?php
        $entry_course_id = isset($_GET['entry_course_id']) ? (int)$_GET['entry_course_id'] : 0;
        $entry_students = $entry_course_id ? ($students_by_course[$entry_course_id] ?? []) : [];
        $entry_course = null;
        foreach ($courses_list as $c) { if ((int)$c['id'] === $entry_course_id) { $entry_course = $c; break; } }
        ?>
        <?php if ($entry_course && !empty($entry_students)): ?>
        <form method="POST">
            <input type="hidden" name="save_attendance" value="1">
            <input type="hidden" name="semester_id" value="<?php echo $semester_id; ?>">
            <input type="hidden" name="course_id" value="<?php echo $entry_course_id; ?>">
            <input type="hidden" name="college_id" value="<?php echo $college_id; ?>">
            <input type="hidden" name="major_id" value="<?php echo $major_id; ?>">
            <input type="hidden" name="semester_number" value="<?php echo $semester_number; ?>">
            <input type="hidden" name="academic_year" value="<?php echo htmlspecialchars($academic_year); ?>">
            <div class="attendance-header">
                <h2>إدخال الحضور — <?php echo htmlspecialchars($entry_course['name_ar']); ?></h2>
            </div>
            <div style="overflow-x: auto;">
                <table class="att-table">
                    <thead>
                        <tr>
                            <th>م</th>
                            <th>الرقم الجامعي</th>
                            <th>الاسم</th>
                            <?php for ($i = 1; $i <= ATTENDANCE_LECTURES_COUNT; $i++): ?>
                            <th class="att-lecture-col">م_<?php echo $i; ?></th>
                            <?php endfor; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sn = 1; foreach ($entry_students as $stu):
                            $rec = null;
                            $entry_lookup_ids = !empty($entry_course['_ids']) ? $entry_course['_ids'] : [$entry_course_id];
                            foreach ($entry_lookup_ids as $aid) {
                                $key = $stu['id'] . '_' . $aid;
                                if (!empty($attendance_records[$key])) {
                                    $rec = $attendance_records[$key];
                                    break;
                                }
                            }
                        ?>
                        <tr>
                            <td><?php echo $sn++; ?></td>
                            <td><?php echo htmlspecialchars($stu['student_number']); ?></td>
                            <td style="text-align: right;"><?php echo htmlspecialchars($stu['full_name_ar']); ?></td>
                            <?php for ($i = 1; $i <= ATTENDANCE_LECTURES_COUNT; $i++):
                                $col = 'lecture_' . $i;
                                $val = $rec && isset($rec[$col]) && $rec[$col] !== null ? (int)$rec[$col] : '';
                            ?>
                            <td>
                                <select name="attendance[<?php echo $stu['id']; ?>][<?php echo $i; ?>]" class="att-lecture-col" style="width: 100%;">
                                    <option value="" <?php echo $val === '' ? 'selected' : ''; ?>>—</option>
                                    <option value="1" <?php echo $val === 1 ? 'selected' : ''; ?>>حاضر</option>
                                    <option value="0" <?php echo $val === 0 ? 'selected' : ''; ?>>غائب</option>
                                </select>
                            </td>
                            <?php endfor; ?>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="no-print" style="margin-top: 15px;">
                <button type="submit" class="btn btn-primary">حفظ الحضور</button>
            </div>
        </form>
        <?php elseif ($entry_course_id && empty($entry_students)): ?>
        <p>لا يوجد طلاب مسجلون في هذه المادة لهذا الفصل.</p>
        <?php endif; ?>
        <?php endif; ?>

        <?php if ($tab === 'report'): ?>
        <!-- تقرير شامل: الجميع — المسموح وغير المسموح لهم بالجلوس لامتحان المادة -->
        <p class="no-print">التقرير يشمل <strong>جميع</strong> الطلاب المسجلين في كل مادة مع حالة السماح بالجلوس. الطالب غير مسموح له بالجلوس إذا كان غيابه ≥ <?php echo (int)(ATTENDANCE_ABSENCE_THRESHOLD_RATIO * 100); ?>% من جملة المحاضرات (<?php echo ATTENDANCE_LECTURES_COUNT; ?> محاضرة)، أي غياب <?php echo $attendance_threshold; ?> محاضرات فأكثر.</p>
        <?php foreach ($courses_list as $course): ?>
        <?php $list = $report_all_by_course[$course['id']] ?? []; ?>
        <div class="report-block">
            <h4><?php echo htmlspecialchars($course['name_ar']); ?> (<?php echo htmlspecialchars($course['code']); ?>)</h4>
            <?php if (empty($list)): ?>
            <p style="margin: 0;">لا يوجد طلاب مسجلون في هذه المادة لهذا الفصل.</p>
            <?php else: ?>
            <table class="att-table" style="max-width: 700px;">
                <thead>
                    <tr>
                        <th>م</th>
                        <th>الرقم الجامعي</th>
                        <th>الاسم</th>
                        <th>عدد الغياب</th>
                        <th>من أصل</th>
                        <th>الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1; foreach ($list as $item):
                        $is_allowed = $item['allowed'];
                        $not_recorded = !empty($item['not_recorded']);
                        if ($not_recorded) {
                            $status_text = 'لم يُسجّل الحضور';
                            $status_style = 'color: #757575;';
                            $row_style = 'background: #f5f5f5;';
                        } elseif ($is_allowed) {
                            $status_text = 'مسموح له بالجلوس';
                            $status_style = 'color: #2e7d32;';
                            $row_style = '';
                        } else {
                            $status_text = 'غير مسموح له بالجلوس';
                            $status_style = 'color: #c62828;';
                            $row_style = 'background: #ffebee;';
                        }
                    ?>
                    <tr style="<?php echo $row_style; ?>">
                        <td><?php echo $sn++; ?></td>
                        <td><?php echo htmlspecialchars($item['student']['student_number']); ?></td>
                        <td style="text-align: right;"><?php echo htmlspecialchars($item['student']['full_name_ar']); ?></td>
                        <td><?php echo $item['absent']; ?></td>
                        <td><?php echo $item['total']; ?></td>
                        <td style="font-weight: bold; <?php echo $status_style; ?>">
                            <?php echo $status_text; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        <div class="no-print" style="margin-top: 20px;">
            <button type="button" onclick="window.print();" class="btn btn-primary">طباعة التقرير</button>
        </div>
        <?php endif; ?>

        <?php endif; ?>

        <?php if (!$semester_id && ($college_id || $major_id || $semester_number || $academic_year)): ?>
        <p>لم يتم العثور على فصل دراسي مطابق. تأكد من اختيار الكلية والتخصص والفصل الدراسي والسنة.</p>
        <?php endif; ?>
    </div>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
