<?php
// /admission3333/reports/lectureattendance.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../helpers.php';

// Set charset for mysqli connection to prevent SQL injection
$mysqli1->set_charset("utf8mb4");

// Check committee access
if (!isset($_SESSION['committee_id'])) {
    header('Location: ../login.php');
    exit;
}

require_committee();

$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;

// Initialize variables
$students = [];
$error_message = '';
$success_message = '';

// Validate and sanitize input parameters
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

// Get and validate filter parameters - with proper sanitization
$filter_semester_id = isset($_GET['filter_semester']) && ctype_digit($_GET['filter_semester']) ? (int)$_GET['filter_semester'] : null;
$filter_college_id = isset($_GET['filter_college']) && ctype_digit($_GET['filter_college']) ? (int)$_GET['filter_college'] : null;
$filter_section_id = isset($_GET['filter_section']) && ctype_digit($_GET['filter_section']) ? (int)$_GET['filter_section'] : null;
$filter_program_id = isset($_GET['filter_program']) && ctype_digit($_GET['filter_program']) ? (int)$_GET['filter_program'] : null;
$filter_specialization_id = isset($_GET['filter_specialization']) && ctype_digit($_GET['filter_specialization']) ? (int)$_GET['filter_specialization'] : null; // NEW
$filter_batch_id = isset($_GET['filter_batch']) && ctype_digit($_GET['filter_batch']) ? (int)$_GET['filter_batch'] : null;

// Apply scope restrictions
if (!$canAll && $scopeCollege !== null) {
    // Force college filter to user's scope
    $filter_college_id = $scopeCollege;
} elseif (!$canAll && $scopeCollege === null) {
    // No access
    $filter_college_id = -1; // This will return no results
}

// Get semester name for display
$semester_name = '';
if ($filter_semester_id && $filter_semester_id > 0) {
    $semester_sql = "SELECT name, code FROM semesters WHERE id = ? AND deleted_at IS NULL";
    $st_sem = $mysqli1->prepare($semester_sql);
    if ($st_sem) {
        $st_sem->bind_param("i", $filter_semester_id);
        $st_sem->execute();
        $semester_result = $st_sem->get_result();
        $semester_data = $semester_result->fetch_assoc();
        if ($semester_data) {
            $semester_name = $semester_data['name'] . ' (' . $semester_data['code'] . ')';
        }
        $st_sem->close();
    }
}

// Build query to get students
if ($filters_applied) {
    // Base query with specialization added
    $sql = "SELECT DISTINCT
        s.student_id,
        s.student_name,
        s.student_name_eng,
        sec.name as section_name,
        sp.specialization_name_ar as specialization_name, -- NEW
        b.value as batch_name,
        p.name as program_name,
        c.name as college_name
    FROM students s
    LEFT JOIN sections sec ON sec.id = s.section_id AND sec.deleted_at IS NULL
    LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_id AND sp.deleted_at IS NULL -- NEW
    LEFT JOIN batches b ON b.id = s.batch_id AND b.deleted_at IS NULL
    LEFT JOIN programs p ON p.id = s.program_id AND p.deleted_at IS NULL
    LEFT JOIN colleges c ON c.id = s.college_id AND c.deleted_at IS NULL
    WHERE s.deleted_at IS NULL";

    $params = [];
    $types = '';

    // Apply scope restrictions
    if (!$canAll && $scopeCollege !== null && $scopeCollege > 0) {
        $sql .= " AND s.college_id = ?";
        $params[] = $scopeCollege;
        $types .= 'i';
    } elseif (!$canAll && $scopeCollege === null) {
        $sql .= " AND 1=0"; // No access
    }

    // Apply filters - with validation
    if ($filter_college_id && $filter_college_id > 0) {
        $sql .= " AND s.college_id = ?";
        $params[] = $filter_college_id;
        $types .= 'i';
    }

    if ($filter_section_id && $filter_section_id > 0) {
        $sql .= " AND s.section_id = ?";
        $params[] = $filter_section_id;
        $types .= 'i';
    }

    if ($filter_program_id && $filter_program_id > 0) {
        $sql .= " AND s.program_id = ?";
        $params[] = $filter_program_id;
        $types .= 'i';
    }
    
    // NEW: Apply specialization filter
    if ($filter_specialization_id && $filter_specialization_id > 0) {
        $sql .= " AND s.specialization_id = ?";
        $params[] = $filter_specialization_id;
        $types .= 'i';
    }

    if ($filter_batch_id && $filter_batch_id > 0) {
        $sql .= " AND s.batch_id = ?";
        $params[] = $filter_batch_id;
        $types .= 'i';
    }

    // Join with registrations if semester filter is applied
    if ($filter_semester_id && $filter_semester_id > 0) {
        $sql .= " AND EXISTS (
            SELECT 1 FROM registrations r 
            WHERE r.student_id = s.student_id 
            AND r.semester_id = ? 
            AND r.deleted_at IS NULL
        )";
        $params[] = $filter_semester_id;
        $types .= 'i';
    }

    $sql .= " ORDER BY s.student_name LIMIT 500";

    // Prepare and execute the query
    $st = $mysqli1->prepare($sql);
    if ($st) {
        if (!empty($params)) {
            $st->bind_param($types, ...$params);
        }
        $st->execute();
        $result = $st->get_result();
        while ($row = $result->fetch_assoc()) {
            $students[] = $row;
        }
        $st->close();
    } else {
        $error_message = "حدث خطأ في جلب بيانات الطلاب";
    }
} else {
    $students = [];
}

// Get filter options with prepared statements
$colleges = [];
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($colleges_stmt) {
    $colleges_stmt->execute();
    $colleges_result = $colleges_stmt->get_result();
    while ($row = $colleges_result->fetch_assoc()) {
        $colleges[] = $row;
    }
    $colleges_stmt->close();
}

// Get sections for the selected college
$sections = [];
if ($filter_college_id && $filter_college_id > 0) {
    $sections_sql = "
        SELECT DISTINCT s.id, s.name, s.parent
        FROM sections s 
        WHERE s.parent = ? AND s.deleted_at IS NULL 
        ORDER BY s.name
    ";
    $sections_stmt = $mysqli1->prepare($sections_sql);
    if ($sections_stmt) {
        $sections_stmt->bind_param("i", $filter_college_id);
        $sections_stmt->execute();
        $sections_result = $sections_stmt->get_result();
        while ($row = $sections_result->fetch_assoc()) {
            $sections[] = $row;
        }
        $sections_stmt->close();
    }
}

// Get programs based on selected college and section
$programs = [];
$programs_query = "
    SELECT DISTINCT p.id, p.name 
    FROM programs p 
    WHERE p.deleted_at IS NULL
";

$programs_params = [];
$programs_types = "";

if ($filter_program_id && $filter_program_id > 0) {
    $programs_query .= " AND p.id = ?";
    $programs_types .= "i";
    $programs_params[] = $filter_program_id;
}

$programs_query .= " ORDER BY p.name";

$programs_stmt = $mysqli1->prepare($programs_query);
if ($programs_stmt) {
    if (!empty($programs_params)) {
        $programs_stmt->bind_param($programs_types, ...$programs_params);
    }
    $programs_stmt->execute();
    $programs_result = $programs_stmt->get_result();
    while ($row = $programs_result->fetch_assoc()) {
        $programs[] = $row;
    }
    $programs_stmt->close();
}

// NEW: Get specializations based on selected section and program
$specializations = [];
if ($filter_section_id && $filter_section_id > 0 && $filter_program_id && $filter_program_id > 0) {
    $specializations_sql = "
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    if ($specializations_stmt) {
        $specializations_stmt->bind_param("ii", $filter_section_id, $filter_program_id);
        $specializations_stmt->execute();
        $specializations_result = $specializations_stmt->get_result();
        while ($row = $specializations_result->fetch_assoc()) {
            $specializations[] = $row;
        }
        $specializations_stmt->close();
    }
} elseif ($filter_section_id && $filter_section_id > 0) {
    // Get specializations by section only
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    if ($specializations_stmt) {
        $specializations_stmt->bind_param("i", $filter_section_id);
        $specializations_stmt->execute();
        $specializations_result = $specializations_stmt->get_result();
        while ($row = $specializations_result->fetch_assoc()) {
            $specializations[] = $row;
        }
        $specializations_stmt->close();
    }
} elseif ($filter_program_id && $filter_program_id > 0) {
    // Get specializations by program only
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    if ($specializations_stmt) {
        $specializations_stmt->bind_param("i", $filter_program_id);
        $specializations_stmt->execute();
        $specializations_result = $specializations_stmt->get_result();
        while ($row = $specializations_result->fetch_assoc()) {
            $specializations[] = $row;
        }
        $specializations_stmt->close();
    }
}

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

// Get semesters
$semesters = [];
$semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
if ($semesters_stmt) {
    $semesters_stmt->execute();
    $semesters_result = $semesters_stmt->get_result();
    while ($row = $semesters_result->fetch_assoc()) {
        $semesters[] = $row;
    }
    $semesters_stmt->close();
}

// Get filter names for display
$college_name = "";
if ($filter_college_id && $filter_college_id > 0) {
    foreach ($colleges as $college) {
        if ($college['id'] == $filter_college_id) {
            $college_name = $college['name'];
            break;
        }
    }
}

$section_name = "";
if ($filter_section_id && $filter_section_id > 0 && !empty($sections)) {
    foreach ($sections as $section) {
        if ($section['id'] == $filter_section_id) {
            $section_name = $section['name'];
            break;
        }
    }
}

$program_name = "";
if ($filter_program_id && $filter_program_id > 0) {
    foreach ($programs as $program) {
        if ($program['id'] == $filter_program_id) {
            $program_name = $program['name'];
            break;
        }
    }
}

// NEW: Get specialization name for display
$specialization_name = "";
if ($filter_specialization_id && $filter_specialization_id > 0 && !empty($specializations)) {
    foreach ($specializations as $spec) {
        if ($spec['specialization_id'] == $filter_specialization_id) {
            $specialization_name = $spec['specialization_name_ar'];
            break;
        }
    }
}

$batch_name = "";
if ($filter_batch_id && $filter_batch_id > 0) {
    foreach ($batches as $batch) {
        if ($batch['id'] == $filter_batch_id) {
            $batch_name = $batch['value'];
            break;
        }
    }
}

include __DIR__ . '/../header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>سجل حضور المحاضرات - تقرير</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .filter-icon {
            width: 40px;
            height: 40px;
            background: #3b82f6;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .filter-status {
            font-size: 0.85rem;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
        }
        .filter-status.applied {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        .filter-status.not-applied {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .info-message {
            background-color: #f0f9ff;
            border: 1px solid #bae6fd;
            color: #0369a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .warning-message {
            background-color: #fee2e2;
            border: 1px solid #f87171;
            color: #991b1b;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .summary-card {
            background: white;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            border: 1px solid #e0e0e0;
            text-align: center;
        }
        .summary-card .number {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 5px;
        }
        .summary-card .label {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .badge-custom {
            padding: 5px 10px;
            border-radius: 20px;
            font-weight: 500;
        }
        .form-select, .form-control {
            border-radius: 8px;
            border: 1px solid #ced4da;
        }
        .form-select:focus, .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25);
        }
        .btn-primary {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            border: none;
            border-radius: 8px;
            padding: 8px 20px;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #2563eb, #1d4ed8);
        }
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
        }
        .chip {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .chip.success { background: #d4edda; color: #155724; }
        .chip.info { background: #d1ecf1; color: #0c5460; }
        .chip.warning { background: #fff3cd; color: #856404; }
        .chip.primary { background: #dbeafe; color: #1e3a8a; }
        .chip.secondary { background: #e9ecef; color: #495057; }
        .chip.blue { background: #d0ebff; color: #0c63e4; border: 1px solid #a5d8ff; }
        .chip.green { background: #d3f9d8; color: #2b8a3e; border: 1px solid #b2f2bb; }
        .chip.purple { background: #f3e8ff; color: #7e22ce; border: 1px solid #e9d5ff; } /* NEW */
        
        /* Print styles */
        @media print {
            body { 
                font-size: 12px !important; 
                direction: rtl;
                padding: 0;
                margin: 0;
            }
            
            .no-print { 
                display: none !important; 
            }
            
            .print-only { 
                display: block !important; 
            }
            
            .print-header {
                text-align: center;
                margin-bottom: 20px;
                padding-bottom: 15px;
            }
            
            .print-info {
                font-size: 11px;
                color: #666;
                margin-bottom: 10px;
            }
            
            .print-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 10px;
            }
            
            .print-table th {
                background-color: #f0f0f0 !important;
                border: 1px solid #000 !important;
                padding: 6px 4px !important;
                font-weight: bold !important;
                text-align: center !important;
            }
            
            .print-table td {
                border: 1px solid #000 !important;
                padding: 5px 4px !important;
                text-align: center !important;
            }
            
            .print-table .text-right {
                text-align: right !important;
                padding-right: 10px !important;
            }
            
            .print-footer {
                margin-top: 20px;
                padding-top: 10px;
                border-top: 1px solid #000;
                font-size: 10px;
                text-align: center;
                color: #666;
            }
            
            /* Hide all elements except print content */
            body > *:not(.print-container) {
                display: none !important;
            }
        }
        
        .print-container {
            display: none;
        }
        
        .banner-img {
            max-width: 100%;
            height: auto;
            margin-bottom: 15px;
        }
        
        .student-name-cell {
            text-align: right !important;
            direction: rtl !important;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding-right: 15px !important;
        }
        
        /* RTL Fixes */
        .ms-auto {
            margin-right: auto !important;
            margin-left: 0 !important;
        }
        
        .me-1, .me-2, .me-3 {
            margin-left: 0.25rem !important;
            margin-right: 0 !important;
        }
        
        .ms-1, .ms-2, .ms-3 {
            margin-right: 0.25rem !important;
            margin-left: 0 !important;
        }
        
        .border-end-0 {
            border-left: 0 !important;
            border-right: 1px solid #ced4da !important;
        }
        
        .border-start-0 {
            border-right: 0 !important;
            border-left: 1px solid #ced4da !important;
        }
        
        .input-group-text {
            border-radius: 0 8px 8px 0 !important;
        }
        
        .form-control {
            border-radius: 8px 0 0 8px !important;
        }
        
        .input-group {
            flex-direction: row-reverse;
        }
        
        .btn-group {
            flex-direction: row-reverse;
        }
        
        .d-flex {
            flex-direction: row;
        }
        
        .fa-arrow-right {
            transform: scaleX(-1);
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4 no-print">
            <h3 class="mb-0 fw-bold">
                <i class="fas fa-chalkboard-teacher ms-2 text-primary"></i>
                سجل حضور المحاضرات
            </h3>
            <div class="ms-auto d-flex align-items-center">
                <span class="filter-status <?= $filters_applied ? 'applied' : 'not-applied' ?> me-2">
                    <i class="fas fa-<?= $filters_applied ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
                    <?= $filters_applied ? 'تم تطبيق التصفية' : 'لم يتم تطبيق أي تصفية' ?>
                </span>
                <a class="btn btn-outline-secondary" href="../admin_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?php if ($error_message): ?>
            <div class="warning-message no-print">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?= htmlspecialchars($error_message, ENT_QUOTES, 'UTF-8') ?>
            </div>
        <?php endif; ?>

        <?php if (!$filters_applied && !$error_message): ?>
            <div class="info-message no-print">
                <i class="fas fa-info-circle me-2"></i>
                <strong>تنبيه:</strong> لم يتم تطبيق أي تصفية. الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية" لعرض الطلاب.
            </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="card card-arabic p-4 mb-4 no-print">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-3">
                        <div class="filter-icon me-2">
                            <i class="fas fa-filter"></i>
                        </div>
                        <h6 class="fw-bold mb-0 text-dark">تصفية الطلاب لحضور المحاضرات</h6>
                        <div class="ms-3">
                            <span class="badge bg-light text-dark border">
                                <i class="fas fa-sliders-h me-1"></i>
                                <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                            </span>
                        </div>
                    </div>
                    
                    <form method="get" class="row g-3 align-items-end" id="filterForm">
                        <!-- Hidden field to indicate filters were applied -->
                        <input type="hidden" name="filter_applied" value="1">
                        
                        <!-- College Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-university me-1"></i>
                                    الكلية
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <?php 
                                            // Don't show college filter if user has scope restriction
                                            if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                                continue;
                                            }
                                            ?>
                                            <option value="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Section Filter (Dependent on College) -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-layer-group me-1"></i>
                                    القسم
                                </label>
                                <div class="input-group input-group-sm position-relative">
                                    <select class="form-control border-end-0" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?> onchange="loadSpecializations()">
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !empty($sections)): ?>
                                            <?php foreach ($sections as $section): ?>
                                                <option value="<?= (int)$section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                                <?php if (!$filter_college_id): ?>
                                    <small class="text-muted">الرجاء اختيار كلية أولاً</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Program Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-graduation-cap me-1"></i>
                                    البرنامج
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_program" id="filter_program" onchange="loadSpecializations()">
                                        <option value="">جميع البرامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= (int)$program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- NEW: Specialization Filter (Dependent on Section and Program) -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-microscope me-1"></i>
                                    التخصص
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization" <?= (!$filter_section_id || !$filter_program_id) ? 'disabled' : '' ?>>
                                        <option value="">جميع التخصصات</option>
                                        <?php if (!empty($specializations)): ?>
                                            <?php foreach ($specializations as $spec): ?>
                                                <option value="<?= (int)$spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-microscope"></i>
                                    </span>
                                </div>
                                <small class="text-muted spec-hint" id="specHint">
                                    <?php if (!$filter_section_id || !$filter_program_id): ?>
                                        الرجاء اختيار القسم والبرنامج أولاً
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-users me-1"></i>
                                    الدفعة
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_batch">
                                        <option value="">جميع الدفعات</option>
                                        <?php foreach ($batches as $batch): ?>
                                            <option value="<?= (int)$batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Semester Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-calendar-alt me-1"></i>
                                    الفصل الدراسي
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_semester">
                                        <option value="">جميع الفصول</option>
                                        <?php foreach ($semesters as $semester): ?>
                                            <option value="<?= (int)$semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($semester['name'] . ' (' . $semester['code'] . ')', ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-12">
                            <div class="d-flex gap-2 pt-2">
                                <button type="submit" class="btn btn-primary btn-sm px-3">
                                    <i class="fas fa-filter me-1"></i>
                                    تطبيق التصفية
                                </button>
                                <a href="lectureattendance.php" class="btn btn-outline-secondary btn-sm px-3">
                                    <i class="fas fa-sync-alt me-1"></i>
                                    إعادة تعيين
                                </a>
                                <?php if ($filters_applied): ?>
                                    <span class="badge bg-success align-self-center px-3 py-2">
                                        <i class="fas fa-check me-1"></i>
                                        تم تطبيق التصفية
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- Filter Summary -->
                <div class="col-md-4">
                    <div class="bg-light rounded p-3 h-100">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fas fa-info-circle me-2 <?= $filters_applied ? 'text-primary' : 'text-secondary' ?>"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        <div class="small">
                            <?php if ($filters_applied): ?>
                                <div class="mb-2">
                                    <strong>عدد الطلاب:</strong> 
                                    <span class="badge bg-primary"><?= number_format(count($students)) ?></span>
                                </div>
                                
                                <!-- Show selected semester -->
                                <?php if ($filter_semester_id && $filter_semester_id > 0 && $semester_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">الفصل الدراسي:</span>
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary">
                                            <?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <!-- Show selected college and section -->
                                <?php if ($filter_college_id && $filter_college_id > 0 && $college_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">الكلية:</span>
                                        <span class="badge bg-primary bg-opacity-10 text-primary">
                                            <?= htmlspecialchars($college_name, ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_section_id && $filter_section_id > 0 && $section_name && $filter_college_id && !empty($sections)): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">القسم:</span>
                                        <span class="badge bg-success bg-opacity-10 text-success">
                                            <?= htmlspecialchars($section_name, ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_program_id && $filter_program_id > 0 && $program_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">البرنامج:</span>
                                        <span class="badge bg-warning bg-opacity-10 text-warning">
                                            <?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <!-- NEW: Show selected specialization -->
                                <?php if ($filter_specialization_id && $filter_specialization_id > 0 && $specialization_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">التخصص:</span>
                                        <span class="badge bg-purple bg-opacity-10 text-purple" style="color: #7e22ce; background-color: #f3e8ff;">
                                            <?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_batch_id && $filter_batch_id > 0 && $batch_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">الدفعة:</span>
                                        <span class="badge bg-info bg-opacity-10 text-info">
                                            <?= htmlspecialchars($batch_name, ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-1 mt-3">شروط التصفية:</div>
                                <ul class="small mb-0 ps-3">
                                    <li>جميع الطلاب بناءً على عوامل التصفية</li>
                                    <li>الطلاب غير المحذوفين فقط</li>
                                    <?php if (!$canAll && $scopeCollege !== null): ?>
                                        <li>نطاق الكلية محدود</li>
                                    <?php endif; ?>
                                </ul>
                            <?php else: ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-filter fa-2x text-muted mb-3"></i>
                                    <p class="text-muted mb-0">لم يتم تطبيق أي تصفية بعد</p>
                                    <p class="text-muted small">الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية"</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Report Content -->
        <?php if ($filters_applied): ?>
            <!-- Subject Information Card -->
            <div class="card card-arabic p-4 mb-4 no-print">
                <div class="d-flex align-items-center mb-3">
                    <div class="filter-icon me-2" style="background: #10b981;">
                        <i class="fas fa-info-circle"></i>
                    </div>
                    <h6 class="fw-bold mb-0 text-dark">معلومات المادة والمحاضر</h6>
                </div>
                
                <form id="subjectInfoForm" class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-book me-1"></i>
                            اسم المادة
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control border-end-0" id="subject_name" placeholder="أدخل اسم المادة" maxlength="255">
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-book-open"></i>
                            </span>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-chalkboard-teacher me-1"></i>
                            اسم المحاضر
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control border-end-0" id="teacher_name" placeholder="أدخل اسم المحاضر" maxlength="255">
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-user-tie"></i>
                            </span>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Summary Cards -->
            <div class="row mb-4 no-print">
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-primary"><?= number_format(count($students)) ?></div>
                        <div class="label">إجمالي الطلاب</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-success">10</div>
                        <div class="label">عدد المحاضرات</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-info">
                            <?= number_format(count($students) * 10) ?>
                        </div>
                        <div class="label">إجمالي الخانات</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-warning" style="font-size: 1.1rem;">
                            <?= $program_name ? htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') : 'جميع البرامج' ?>
                            <?php if ($specialization_name): ?>
                                <br><small class="text-purple" style="color: #7e22ce;"><?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?></small>
                            <?php endif; ?>
                        </div>
                        <div class="label">البرنامج / التخصص</div>
                    </div>
                </div>
            </div>

            <!-- Export and Print Options -->
            <div class="row mb-4 no-print">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>
                                آخر تحديث: <?= date('Y-m-d H:i:s') ?>
                                <?php if ($program_name): ?>
                                    | <i class="fas fa-graduation-cap me-1"></i>
                                    البرنامج: <?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?>
                                <?php endif; ?>
                                <?php if ($specialization_name): ?>
                                    | <i class="fas fa-microscope me-1"></i>
                                    التخصص: <?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?>
                                <?php endif; ?>
                                <?php if ($semester_name): ?>
                                    | <i class="fas fa-calendar-alt me-1"></i>
                                    الفصل: <?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="d-flex gap-2">
                            <button class="btn btn-success btn-sm" onclick="exportToExcel()" <?= empty($students) ? 'disabled' : '' ?>>
                                <i class="fas fa-file-excel me-1"></i>
                                تصدير لإكسل
                            </button>
                            <button class="btn btn-danger btn-sm" onclick="printReportPDF()" <?= empty($students) ? 'disabled' : '' ?>>
                                <i class="fas fa-print me-1"></i>
                                طباعة PDF
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Students Table -->
            <div class="card card-arabic p-4">
                <div class="d-flex align-items-center mb-3">
                    <h6 class="fw-bold mb-0">
                        <i class="fas fa-chalkboard-teacher me-2 text-primary"></i>
                        سجل حضور المحاضرات
                        <?php if ($program_name): ?>
                            <span class="chip warning ms-2">
                                <i class="fas fa-graduation-cap me-1"></i>
                                <?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <!-- NEW: Show specialization badge if selected -->
                        <?php if ($specialization_name): ?>
                            <span class="chip purple ms-2">
                                <i class="fas fa-microscope me-1"></i>
                                <?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($semester_name): ?>
                            <span class="chip primary ms-2">
                                <i class="fas fa-calendar-alt me-1"></i>
                                <?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                    </h6>
                    <div class="ms-auto">
                        <span class="badge bg-primary">
                            <i class="fas fa-users me-1"></i>
                            <?= number_format(count($students)) ?> طالب
                        </span>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped student-table" id="studentsTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                
                                <?php for ($i = 1; $i <= 10; $i++): ?>
                                    <th class="text-center">محاضرة <?= $i ?></th>
                                <?php endfor; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($students)): ?>
                                <tr>
                                    <td colspan="14" class="text-center text-muted py-4"> <!-- Updated colspan from 13 to 14 -->
                                        <i class="fas fa-info-circle me-2"></i>
                                        لا توجد بيانات للعرض بناءً على عوامل التصفية المحددة
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($students as $index => $student): ?>
                                    <tr>
                                        <td class="fw-bold"><?= $index + 1 ?></td>
                                        <td>
                                            <code><?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?></code>
                                        </td>
                                        <td class="text-right student-name-cell">
                                            <?= htmlspecialchars($student['student_name'] ?: $student['student_name_eng'], ENT_QUOTES, 'UTF-8') ?>
                                        </td>
                                      
                                        <?php for ($i = 1; $i <= 10; $i++): ?>
                                            <td class="text-center" style="height: 45px; background-color: #f8f9fa; vertical-align: middle;">
                                                <!-- Empty column for attendance marking -->
                                            </td>
                                        <?php endfor; ?>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
        
        <!-- Hidden Print Container -->
        <div class="print-container" id="printContainer">
            <div class="print-header">
                <!-- Banner Image -->
                <img src="../img/banar3.jpg" alt="Banner" class="banner-img" onerror="this.style.display='none'">
                
                <h2>سجل حضور المحاضرات</h2>
                <div class="print-info" id="printSubjectInfo">
                    <!-- Subject information will be filled by JavaScript -->
                </div>
            </div>
            
            <table class="print-table">
                <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="15%">رقم الطالب</th>
                        <th width="25%">اسم الطالب</th>
                       
                        <?php for ($i = 1; $i <= 10; $i++): ?>
                            <th width="4%">م <?= $i ?></th>
                        <?php endfor; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($students)): ?>
                        <tr>
                            <td colspan="14" class="text-center"> <!-- Updated colspan from 13 to 14 -->
                                لا توجد بيانات للعرض
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($students as $index => $student): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="text-right">
                                    <?= htmlspecialchars($student['student_name'] ?: $student['student_name_eng'], ENT_QUOTES, 'UTF-8') ?>
                                </td>
                                
                                <?php for ($i = 1; $i <= 10; $i++): ?>
                                    <td></td>
                                <?php endfor; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            
            <div class="print-footer">
                تم إنشاء التقرير تلقائياً من نظام إدارة القبول والتسجيل<br>
                الصفحة 1 من 1
            </div>
        </div>
    </div>

    <script>
        // Simple section loading - reload page when college changes
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            // Reset section select
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            sectionSelect.disabled = true;
            
            // Reset specialization select
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            specSelect.disabled = true;
            if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
            
            if (!collegeId || collegeId === '') {
                return;
            }
            
            // Create a form and submit it to reload the page
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            // Add current semester
            const currentSemester = "<?= $filter_semester_id ?>";
            if (currentSemester) {
                const semesterInput = document.createElement('input');
                semesterInput.type = 'hidden';
                semesterInput.name = 'filter_semester';
                semesterInput.value = currentSemester;
                form.appendChild(semesterInput);
            }
            
            // Add college parameter
            const collegeInput = document.createElement('input');
            collegeInput.type = 'hidden';
            collegeInput.name = 'filter_college';
            collegeInput.value = collegeId;
            form.appendChild(collegeInput);
            
            // Add filter_applied parameter
            const appliedInput = document.createElement('input');
            appliedInput.type = 'hidden';
            appliedInput.name = 'filter_applied';
            appliedInput.value = '1';
            form.appendChild(appliedInput);
            
            // Add current section if exists
            const currentSection = "<?= $filter_section_id ?>";
            if (currentSection) {
                const sectionInput = document.createElement('input');
                sectionInput.type = 'hidden';
                sectionInput.name = 'filter_section';
                sectionInput.value = currentSection;
                form.appendChild(sectionInput);
            }
            
            // Add current program if exists
            const currentProgram = "<?= $filter_program_id ?>";
            if (currentProgram) {
                const programInput = document.createElement('input');
                programInput.type = 'hidden';
                programInput.name = 'filter_program';
                programInput.value = currentProgram;
                form.appendChild(programInput);
            }
            
            // Add current specialization if exists
            const currentSpecialization = "<?= $filter_specialization_id ?>";
            if (currentSpecialization) {
                const specInput = document.createElement('input');
                specInput.type = 'hidden';
                specInput.name = 'filter_specialization';
                specInput.value = currentSpecialization;
                form.appendChild(specInput);
            }
            
            // Add current batch if exists
            const currentBatch = "<?= $filter_batch_id ?>";
            if (currentBatch) {
                const batchInput = document.createElement('input');
                batchInput.type = 'hidden';
                batchInput.name = 'filter_batch';
                batchInput.value = currentBatch;
                form.appendChild(batchInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // NEW: Load specializations dynamically
        function loadSpecializations() {
            const sectionId = document.getElementById('filter_section').value;
            const programId = document.getElementById('filter_program').value;
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            if (!sectionId || !programId) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
                return;
            }
            
            // Show loading
            specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
            specSelect.disabled = false;
            if (specHint) specHint.innerHTML = 'جاري تحميل التخصصات...';
            
            // Fetch specializations via AJAX
            fetch(`../ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
                .then(response => response.json())
                .then(data => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            // Check if this specialization was previously selected
                            const urlParams = new URLSearchParams(window.location.search);
                            const selectedSpec = urlParams.get('filter_specialization');
                            if (selectedSpec && selectedSpec == spec.specialization_id) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                        if (specHint) specHint.innerHTML = `${data.length} تخصص متاح`;
                    } else {
                        if (specHint) specHint.innerHTML = 'لا توجد تخصصات متاحة';
                    }
                    
                    specSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    specSelect.disabled = false;
                    if (specHint) specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        // Export to Excel function
        function exportToExcel() {
            if (!<?= $filters_applied ? 'true' : 'false' ?>) {
                alert('الرجاء تطبيق التصفية أولاً لعرض الطلاب');
                return;
            }
            
            if (<?= count($students) ?> === 0) {
                alert('لا توجد بيانات للتصدير');
                return;
            }
            
            // Get subject information and sanitize
            const subjectName = sanitizeInput(document.getElementById('subject_name').value) || 'غير محدد';
            const teacherName = sanitizeInput(document.getElementById('teacher_name').value) || 'غير محدد';
            const semesterName = "<?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?>";
            const programName = "<?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?>";
            const specializationName = "<?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?>";
            
            // Get the table
            const table = document.getElementById('studentsTable');
            
            if (!table) {
                alert('لا توجد بيانات للتصدير');
                return;
            }
            
            // Create a new workbook
            const wb = XLSX.utils.book_new();
            
            // Create worksheet from table
            const ws = XLSX.utils.table_to_sheet(table);
            
            // Add subject information as first rows
            const subjectInfo = [
                [`سجل حضور المحاضرات`],
                [`اسم المادة: ${subjectName} | اسم المحاضر: ${teacherName}`],
                [`الفصل الدراسي: ${semesterName}`],
                [`البرنامج: ${programName} ${specializationName ? '| التخصص: ' + specializationName : ''}`],
                [`تاريخ التصدير: ${new Date().toLocaleDateString('ar-EG')}`],
                [''], // Empty row for spacing
            ];
            
            // Convert table to array and add subject info at the beginning
            const tableArray = XLSX.utils.sheet_to_json(ws, {header: 1});
            const combinedArray = [...subjectInfo, ...tableArray];
            
            // Create new worksheet with combined data
            const newWs = XLSX.utils.aoa_to_sheet(combinedArray);
            
            // Set column widths
            const wscols = [
                {wch: 5},   // #
                {wch: 15},  // Student ID
                {wch: 25},  // Student Name
                {wch: 20},  // Specialization (NEW)
            ];
            // Add widths for 10 lecture columns
            for (let i = 0; i < 10; i++) {
                wscols.push({wch: 10}); // Each lecture column
            }
            newWs['!cols'] = wscols;
            
            // Add worksheet to workbook
            XLSX.utils.book_append_sheet(wb, newWs, "سجل حضور المحاضرات");
            
            // Generate filename
            let filename = "سجل_حضور_المحاضرات";
            <?php if ($program_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $program_name) ?>";
            <?php endif; ?>
            <?php if ($specialization_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $specialization_name) ?>";
            <?php endif; ?>
            <?php if ($semester_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $semester_name) ?>";
            <?php endif; ?>
            filename += "_<?= date('Y-m-d') ?>.xlsx";
            
            // Clean filename (remove special characters)
            filename = filename.replace(/[<>:"/\\|?*]+/g, '_');
            
            // Save the file
            XLSX.writeFile(wb, filename);
        }
        
        // PDF Print function
        function printReportPDF() {
            if (!<?= $filters_applied ? 'true' : 'false' ?>) {
                alert('الرجاء تطبيق التصفية أولاً لعرض الطلاب');
                return;
            }
            
            if (<?= count($students) ?> === 0) {
                alert('لا توجد بيانات للطباعة');
                return;
            }
            
            // Get subject information and sanitize
            const subjectName = sanitizeInput(document.getElementById('subject_name').value) || 'غير محدد';
            const teacherName = sanitizeInput(document.getElementById('teacher_name').value) || 'غير محدد';
            const semesterName = "<?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?>";
            const programName = "<?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?>";
            const specializationName = "<?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?>";
            const collegeName = "<?= htmlspecialchars($college_name, ENT_QUOTES, 'UTF-8') ?>";
            const sectionName = "<?= htmlspecialchars($section_name, ENT_QUOTES, 'UTF-8') ?>";
            
            // Create a new window for printing
            const printWindow = window.open('', '_blank', 'width=1200,height=800');
            
            if (!printWindow) {
                alert('الرجاء السماح بالنوافذ المنبثقة');
                return;
            }
            
            // Get the print container HTML
            const printContainer = document.getElementById('printContainer').innerHTML;
            
            // Update subject info in print container
            const printInfo = `
                اسم المادة: ${subjectName} | اسم المحاضر: ${teacherName}<br>
                الفصل الدراسي: ${semesterName}<br>
                <?php if ($college_name): ?>الكلية: <?= htmlspecialchars($college_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                <?php if ($section_name): ?>القسم: <?= htmlspecialchars($section_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                <?php if ($program_name): ?>البرنامج: <?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                <?php if ($specialization_name): ?>التخصص: <?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                تاريخ الطباعة: ${new Date().toLocaleDateString('ar-EG')}<br>
            `;
            
            // Replace the subject info div content
            const updatedPrintContainer = printContainer.replace(
                '<div class="print-info" id="printSubjectInfo">',
                `<div class="print-info" id="printSubjectInfo">${printInfo}`
            );
            
            // Create the print content
            const printContent = `
                <!DOCTYPE html>
                <html dir="rtl">
                <head>
                    <meta charset="UTF-8">
                    <title>سجل حضور المحاضرات</title>
                    <style>
                        @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap');
                        
                        * {
                            font-family: 'Cairo', sans-serif !important;
                            box-sizing: border-box;
                        }
                        
                        body {
                            margin: 0;
                            padding: 15mm;
                            direction: rtl;
                            background: white;
                            font-size: 12px;
                        }
                        
                        .print-header {
                            text-align: center;
                            margin-bottom: 20px;
                            padding-bottom: 10px;
                        }
                        
                        .banner-img {
                            max-width: 100%;
                            height: auto;
                            margin-bottom: 15px;
                        }
                        
                        .print-header h2 {
                            font-size: 20px;
                            margin: 5px 0;
                            font-weight: bold;
                            color: #000;
                        }
                        
                        .print-info {
                            font-size: 11px;
                            color: #666;
                            margin-top: 10px;
                            line-height: 1.6;
                        }
                        
                        .print-table {
                            width: 100%;
                            border-collapse: collapse;
                            font-size: 10px;
                            margin-top: 15px;
                        }
                        
                        .print-table th {
                            background-color: #f0f0f0;
                            border: 1px solid #000;
                            padding: 8px 5px;
                            font-weight: bold;
                            text-align: center;
                            font-size: 11px;
                        }
                        
                        .print-table td {
                            border: 1px solid #000;
                            padding: 6px 5px;
                            text-align: center;
                        }
                        
                        .print-table .text-right {
                            text-align: right;
                            padding-right: 10px;
                        }
                        
                        .print-footer {
                            margin-top: 20px;
                            padding-top: 10px;
                            border-top: 1px solid #666;
                            font-size: 10px;
                            text-align: center;
                            color: #666;
                            line-height: 1.6;
                        }
                        
                        @media print {
                            @page {
                                size: A4 landscape;
                                margin: 15mm;
                            }
                            
                            body { 
                                margin: 0;
                                padding: 0;
                            }
                            
                            .print-table {
                                font-size: 9px;
                            }
                            
                            .print-table th, 
                            .print-table td {
                                padding: 5px 3px;
                            }
                        }
                    </style>
                </head>
                <body>
                    ${updatedPrintContainer}
                </body>
                </html>
            `;
            
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            // Trigger print after content is loaded
            printWindow.onload = function() {
                printWindow.focus();
                setTimeout(function() {
                    printWindow.print();
                }, 500);
            };
        }
        
        // Helper function to sanitize input
        function sanitizeInput(input) {
            if (!input) return '';
            return input.replace(/[<>"']/g, '');
        }
        
        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            const collegeSelect = document.getElementById('filter_college');
            const sectionSelect = document.getElementById('filter_section');
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            // Enable/disable section select based on college selection
            if (collegeSelect && sectionSelect) {
                if (!collegeSelect.value) {
                    sectionSelect.disabled = true;
                    if (specSelect) specSelect.disabled = true;
                    if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
                } else {
                    sectionSelect.disabled = false;
                }
            }
            
            // Check if we need to load specializations on page load
            const sectionId = "<?= $filter_section_id ?>";
            const programId = "<?= $filter_program_id ?>";
            
            if (sectionId && programId && specSelect && specHint) {
                specSelect.disabled = false;
                
                // Update hint based on data
                const specCount = <?= count($specializations) ?>;
                if (specCount > 0) {
                    specHint.innerHTML = `${specCount} تخصص متاح`;
                } else {
                    specHint.innerHTML = 'لا توجد تخصصات متاحة';
                }
            }
            
            // Load saved subject and teacher names from localStorage (sanitize on load)
            const savedSubject = localStorage.getItem('lecture_subject');
            const savedTeacher = localStorage.getItem('lecture_teacher');
            
            if (savedSubject) {
                document.getElementById('subject_name').value = sanitizeInput(savedSubject.substring(0, 255));
            }
            if (savedTeacher) {
                document.getElementById('teacher_name').value = sanitizeInput(savedTeacher.substring(0, 255));
            }
            
            // Save subject and teacher names when they change
            document.getElementById('subject_name').addEventListener('input', function() {
                // Limit to 255 characters
                if (this.value.length > 255) {
                    this.value = this.value.substring(0, 255);
                }
                localStorage.setItem('lecture_subject', sanitizeInput(this.value));
            });
            
            document.getElementById('teacher_name').addEventListener('input', function() {
                // Limit to 255 characters
                if (this.value.length > 255) {
                    this.value = this.value.substring(0, 255);
                }
                localStorage.setItem('lecture_teacher', sanitizeInput(this.value));
            });
            
            // Fix arrow icons for RTL
            document.querySelectorAll('.fa-arrow-right').forEach(function(icon) {
                icon.style.transform = 'scaleX(-1)';
            });
        });
    </script>
    
    <!-- Load SheetJS library for Excel export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</body>
</html>
