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

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

// Check committee access (session is already started in header/db)
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 = [];

// Check if filters were submitted
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

// Get filter parameters - only use them if filters were applied
if ($filters_applied) {
    $filter_college_id = $_GET['filter_college'] ?? null;
    $filter_section_id = $_GET['filter_section'] ?? null;
    $filter_program_id = $_GET['filter_program'] ?? null;
    $filter_batch_id = $_GET['filter_batch'] ?? null;
    $filter_semester_id = $_GET['filter_semester'] ?? null;
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_batch_id = null;
    $filter_semester_id = null;
}

// Build WHERE clause for filtering students
$where = " WHERE r.is_paid = 1 AND r.deleted_at IS NULL ";
$types = ''; 
$params = [];

// Apply scope restrictions
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
    // Auto-set the college filter if user has scope restriction
    if (!$filter_college_id) {
        $filter_college_id = $scopeCollege;
    }
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

// Apply filters ONLY if they were applied by user
if ($filters_applied) {
    if ($filter_college_id && !empty($filter_college_id)) {
        $where .= " AND s.college_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_college_id;
    }

    if ($filter_section_id && !empty($filter_section_id)) {
        $where .= " AND s.section_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_section_id;
    }

    if ($filter_program_id && !empty($filter_program_id)) {
        $where .= " AND s.program_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_program_id;
    }

    if ($filter_batch_id && !empty($filter_batch_id)) {
        $where .= " AND s.batch_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_batch_id;
    }

    if ($filter_semester_id && !empty($filter_semester_id)) {
        $where .= " AND r.semester_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_semester_id;
    }
}

// Get filtered students ONLY if filters were applied
if ($filters_applied) {
    $sqlStudents = "
        SELECT 
            s.student_id,
            s.student_name,
            s.student_name_eng,
            s.college_id,
            s.section_id,
            s.program_id,
            s.batch_id,
            c.name AS college_name,
            sec.name AS section_name,
            p.name AS program_name,
            b.value AS batch_name,
            sem.name AS semester_name,
            sem.code AS semester_code,
            r.payment_amount as total_paid,
            r.study_fees,
            r.registration_fees,
            r.insurance_fees,
            r.discount,
            r.penalty,
            r.stamp,
            r.payment_reference,
            r.created_at as registration_date,
            COUNT(DISTINCT pay.id) as payment_count
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id
        LEFT JOIN sections sec ON s.section_id = sec.id
        LEFT JOIN programs p ON s.program_id = p.id
        LEFT JOIN batches b ON s.batch_id = b.id
        INNER JOIN registrations r ON r.student_id = s.student_id
        LEFT JOIN semesters sem ON sem.id = r.semester_id
        LEFT JOIN payments pay ON pay.student_id = s.student_id AND pay.payment_reference = r.payment_reference
        {$where}
        GROUP BY s.student_id, r.id, sem.id
        ORDER BY r.created_at DESC, s.student_name
        LIMIT 1000
    ";

    $students_stmt = $mysqli1->prepare($sqlStudents);
    if ($types) {
        $students_stmt->bind_param($types, ...$params);
    }
    $students_stmt->execute();
    $students = $students_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $students_stmt->close();
} else {
    // No students to show initially
    $students = [];
}

// Get filter options
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$colleges_stmt->execute();
$colleges = $colleges_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$colleges_stmt->close();

// Get sections for the selected college
$sections = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $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);
    $sections_stmt->bind_param("i", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
}

// Get programs based on selected college and section
$programs = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $programs_where = "p.deleted_at IS NULL";
    $programs_params = [];
    $programs_types = "";
    
    if ($filter_section_id && !empty($filter_section_id)) {
        $programs_where .= " AND st.section_id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_section_id;
    }
    
    $programs_where .= " AND st.college_id = ?";
    $programs_types .= "i";
    $programs_params[] = $filter_college_id;
    
    $programs_sql = "
        SELECT DISTINCT p.id, p.name 
        FROM programs p 
        INNER JOIN students st ON p.id = st.program_id 
        WHERE {$programs_where} 
        ORDER BY p.name
    ";
    
    $programs_stmt = $mysqli1->prepare($programs_sql);
    if ($programs_types) {
        $programs_stmt->bind_param($programs_types, ...$programs_params);
    }
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
} else {
    $programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
}

$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id DESC");
$batches_stmt->execute();
$batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$batches_stmt->close();

// Get semesters
$semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
$semesters_stmt->execute();
$semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$semesters_stmt->close();

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

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

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

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

$semester_name = "";
if ($filter_semester_id) {
    foreach ($semesters as $semester) {
        if ($semester['id'] == $filter_semester_id) {
            $semester_name = $semester['name'] . ' (' . $semester['code'] . ')';
            break;
        }
    }
}

// Include header with correct path
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', system-ui, -apple-system, 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;
        }
        .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);
        }
        .total-row {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .total-row td {
            border-top: 2px solid #dee2e6;
        }
        .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; }
        @media print {
            .no-print { display: none !important; }
            body { font-size: 12px; }
            .summary-card { 
                break-inside: avoid;
                margin-bottom: 10px;
                padding: 10px;
            }
            .summary-card .number { font-size: 1.5rem; }
            table { font-size: 10px; }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4 no-print">
            <h3 class="mb-0 fw-bold">تقرير الطلاب المسجلين كاملاً</h3>
            <div class="ms-auto">
                <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="../committee_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?php if (!$filters_applied): ?>
            <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-3 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="<?= $college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                                <?= e($college['name']) ?>
                                            </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-3 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' : '' ?>>
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !empty($sections)): ?>
                                            <?php foreach ($sections as $section): ?>
                                                <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                    <?= e($section['name']) ?>
                                                </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">
                                        <option value="">جميع البرامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= $program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                                <?= e($program['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book"></i>
                                    </span>
                                </div>
                            </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="<?= $batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                                <?= e($batch['value']) ?>
                                            </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="<?= $semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                                <?= e($semester['name'] . ' (' . $semester['code'] . ')') ?>
                                            </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="registered_students.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-success"><?= number_format(count($students)) ?></span>
                                </div>
                                
                                <!-- Show selected college and section -->
                                <?php if ($filter_college_id && $college_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">الكلية:</span>
                                        <span class="badge bg-primary bg-opacity-10 text-primary">
                                            <?= e($college_name) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_section_id && $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">
                                            <?= e($section_name) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_program_id && $program_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">البرنامج:</span>
                                        <span class="badge bg-warning bg-opacity-10 text-warning">
                                            <?= e($program_name) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_batch_id && $batch_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">الدفعة:</span>
                                        <span class="badge bg-info bg-opacity-10 text-info">
                                            <?= e($batch_name) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_semester_id && $semester_name): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">الفصل الدراسي:</span>
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary">
                                            <?= e($semester_name) ?>
                                        </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): ?>
            <!-- Summary Cards -->
            <div class="row mb-4 no-print">
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-success"><?= number_format(count($students)) ?></div>
                        <div class="label">إجمالي الطلاب المسجلين</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-primary">
                            <?php
                            $totalPayments = array_sum(array_column($students, 'payment_count'));
                            echo number_format($totalPayments);
                            ?>
                        </div>
                        <div class="label">إجمالي السداديات</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-info">
                            <?php
                            $totalAmount = array_sum(array_column($students, 'total_paid'));
                            echo number_format($totalAmount, 0);
                            ?> 
                        </div>
                        <div class="label">إجمالي المبالغ المدفوعة</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-warning">
                            <?php
                            $totalStudyFees = array_sum(array_column($students, 'study_fees'));
                            echo number_format($totalStudyFees, 0);
                            ?> 
                        </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>
                                    البرنامج: <?= e($program_name) ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="d-flex gap-2">
                            <button class="btn btn-success btn-sm" onclick="exportToExcel()">
                                <i class="fas fa-file-excel me-1"></i>
                                تصدير لإكسل
                            </button>
                            <button class="btn btn-danger btn-sm" onclick="window.print()">
                                <i class="fas fa-print me-1"></i>
                                طباعة التقرير
                            </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-list-check me-2 text-success"></i>
                        قائمة الطلاب المسجلين كاملاً
                        <?php if ($program_name): ?>
                            <span class="chip warning ms-2">
                                <i class="fas fa-graduation-cap me-1"></i>
                                <?= e($program_name) ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($semester_name): ?>
                            <span class="chip secondary ms-2">
                                <i class="fas fa-calendar-alt me-1"></i>
                                <?= e($semester_name) ?>
                            </span>
                        <?php endif; ?>
                    </h6>
                    <div class="ms-auto">
                        <span class="badge bg-success">
                            <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>
                                <th>الكلية</th>
                                <th>القسم</th>
                                <th>البرنامج</th>
                                <th>الدفعة</th>
                                <th>الفصل الدراسي</th>
                                <th class="text-end">عدد السداديات</th>
                                <th class="text-end">إجمالي المدفوع</th>
                                <th class="no-print">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($students)): ?>
                                <tr>
                                    <td colspan="11" class="text-center text-muted py-4">
                                        <i class="fas fa-info-circle me-2"></i>
                                        لا توجد بيانات للعرض بناءً على عوامل التصفية المحددة
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php 
                                $totalPayments = 0;
                                $totalAmount = 0;
                                ?>
                                <?php foreach ($students as $index => $student): ?>
                                    <?php
                                    $totalPayments += $student['payment_count'];
                                    $totalAmount += $student['total_paid'];
                                    ?>
                                    <tr>
                                        <td class="fw-bold"><?= $index + 1 ?></td>
                                        <td><code><?= e($student['student_id']) ?></code></td>
                                        <td class="text-right" style="text-align: right; direction: rtl;">
                                            <?= e($student['student_name'] ?: $student['student_name_eng']) ?>
                                        </td>
                                        <td><?= e($student['college_name']) ?></td>
                                        <td><?= e($student['section_name']) ?></td>
                                        <td>
                                            <span class="chip primary">
                                                <i class="fas fa-graduation-cap me-1"></i>
                                                <?= e($student['program_name']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary">
                                                <?= e($student['batch_name']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="chip info">
                                                <i class="fas fa-calendar-alt me-1"></i>
                                                <?= e($student['semester_name'] ?? 'غير محدد') ?>
                                            </span>
                                        </td>
                                        <td class="text-end">
                                            <span class="badge bg-primary">
                                                <?= number_format($student['payment_count']) ?>
                                            </span>
                                        </td>
                                        <td class="text-end fw-bold text-success">
                                            <?= number_format($student['total_paid'] ?? 0, 0) ?> 
                                        </td>
                                        <td class="no-print">
                                            <div class="btn-group btn-group-sm">
                                                <a href="../committee_student_profile.php?student_id=<?= urlencode($student['student_id']) ?>" 
                                                   class="btn btn-outline-primary"
                                                   target="_blank">
                                                    <i class="fas fa-eye me-1"></i>
                                                    عرض الملف
                                                </a>
                                                <a href="../student_payments.php?student_id=<?= urlencode($student['student_id']) ?>&reference=<?= urlencode($student['payment_reference']) ?>" 
                                                   class="btn btn-outline-success"
                                                   target="_blank">
                                                    <i class="fas fa-receipt me-1"></i>
                                                    السداديات
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                
                                <!-- Total Row -->
                                <tr class="total-row">
                                    <td colspan="8" class="text-end fw-bold">
                                        <i class="fas fa-calculator me-2"></i>الإجمالي:
                                    </td>
                                    <td class="text-end fw-bold">
                                        <span class="badge bg-primary"><?= number_format($totalPayments) ?></span>
                                    </td>
                                    <td class="text-end fw-bold text-success">
                                        <?= number_format($totalAmount, 0) ?> 
                                    </td>
                                    <td class="no-print"></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // Simple section loading - reload page when college changes
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            // Reset section select
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                return;
            }
            
            // Create a form and submit it to reload the page
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            // 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 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);
            }
            
            // Add current semester if exists
            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);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // Export to Excel function
        function exportToExcel() {
            // Get the table
            const table = document.getElementById('studentsTable');
            
            if (!table) {
                alert('لا توجد بيانات للتصدير');
                return;
            }
            
            // Remove the "الإجراءات" column for export
            const exportTable = table.cloneNode(true);
            const actionsTh = exportTable.querySelector('th:nth-last-child(1)');
            if (actionsTh && actionsTh.textContent.includes('الإجراءات')) {
                actionsTh.remove();
            }
            
            // Remove actions column from all rows
            const rows = exportTable.querySelectorAll('tr');
            rows.forEach(row => {
                const lastTd = row.querySelector('td:nth-last-child(1)');
                if (lastTd && lastTd.closest('.no-print')) {
                    lastTd.remove();
                }
            });
            
            // Create a new workbook
            const wb = XLSX.utils.book_new();
            
            // Create worksheet from table
            const ws = XLSX.utils.table_to_sheet(exportTable);
            
            // Set column widths
            const wscols = [
                {wch: 5},   // #
                {wch: 15},  // Student ID
                {wch: 25},  // Student Name
                {wch: 15},  // College
                {wch: 15},  // Section
                {wch: 15},  // Program
                {wch: 10},  // Batch
                {wch: 15},  // Semester
                {wch: 15},  // Payment Count
                {wch: 15},  // Total Paid
            ];
            ws['!cols'] = wscols;
            
            // Add worksheet to workbook
            XLSX.utils.book_append_sheet(wb, ws, "الطلاب المسجلين");
            
            // Generate filename
            let filename = "الطلاب_المسجلين_كاملاً";
            <?php if ($program_name): ?>
                filename += "_<?= e($program_name) ?>";
            <?php endif; ?>
            <?php if ($semester_name): ?>
                filename += "_<?= e($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);
        }
        
        // Print function
        function printReport() {
            window.print();
        }
        
        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            const collegeSelect = document.getElementById('filter_college');
            const sectionSelect = document.getElementById('filter_section');
            
            // Enable/disable section select based on college selection
            if (collegeSelect && sectionSelect) {
                if (!collegeSelect.value) {
                    sectionSelect.disabled = true;
                } else {
                    sectionSelect.disabled = false;
                }
            }
        });
    </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>