<?php
// admin_dashboard.php
require 'db.php';
require 'helpers.php';
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;

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* ---------- Config: centralize the interview list file ---------- */
const INTERVIEW_LIST_PAGE = 'applicants.php';

/* ---------- helpers ---------- */
function col_exists(mysqli $db, string $table, string $col): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param("ss", $table, $col);
  $st->execute();
  $ok = (bool)$st->get_result()->fetch_row();
  $st->close();
  return $ok;
}

// Scope WHERE - For single college system
$where = " WHERE 1=1 ";
$types = ''; $params = [];

// Add filter parameters
$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;

// Apply college filter first (if user has permission to filter by college)
if ($canAll && $filter_college_id && !empty($filter_college_id)) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $filter_college_id;
} elseif (!$canAll && $scopeCollege !== null) {
    // If user doesn't have permission to view all, use their assigned college
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
}

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

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

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

/* ---------- Top KPIs ---------- */
$sqlKpi = "
  SELECT
    COUNT(*) AS total,
    
    -- حالة المقابلة - حسب الشروط الجديدة
    SUM(CASE WHEN s.interview_status='accepted' THEN 1 ELSE 0 END) AS st_accepted,
    SUM(CASE WHEN s.interview_status='rejected' THEN 1 ELSE 0 END) AS st_rejected,
    SUM(CASE WHEN s.profile_completed=1 AND s.interview_status='pending' THEN 1 ELSE 0 END) AS st_pending,
    
    -- الحالة الطبية - حسب الشروط الجديدة
    SUM(CASE WHEN s.medically_fit=1 THEN 1 ELSE 0 END) AS med_fit,
    SUM(CASE WHEN s.medically_fit=0 THEN 1 ELSE 0 END) AS med_unfit,
    SUM(CASE WHEN s.profile_completed=1 AND s.medical_status='completed' THEN 1 ELSE 0 END) AS med_wait,
    
    -- إكمال الملف
    SUM(CASE WHEN s.profile_completed=1 THEN 1 ELSE 0 END) AS prof_ok,
    SUM(CASE WHEN (s.profile_completed IS NULL OR s.profile_completed<>1) THEN 1 ELSE 0 END) AS prof_no
  FROM students s
  $where
";
$st = $mysqli1->prepare($sqlKpi);
if ($types) $st->bind_param($types, ...$params);
$st->execute(); $kpi = $st->get_result()->fetch_assoc(); $st->close();
foreach (['total','st_pending','st_accepted','st_rejected','med_wait','med_fit','med_unfit','prof_ok','prof_no'] as $k)
  $kpi[$k] = (int)($kpi[$k] ?? 0);

/* ---------- By College ---------- */
$sqlByCollege = "
  SELECT c.id, c.name,
    COUNT(*) AS total,
    
    -- حالة المقابلة - حسب الشروط الجديدة
    SUM(CASE WHEN s.interview_status='accepted' THEN 1 ELSE 0 END) AS accepted,
    SUM(CASE WHEN s.interview_status='rejected' THEN 1 ELSE 0 END) AS rejected,
    SUM(CASE WHEN s.profile_completed=1 AND s.interview_status='pending' THEN 1 ELSE 0 END) AS pending,
    
    -- الحالة الطبية - حسب الشروط الجديدة
    SUM(CASE WHEN s.medically_fit=1 THEN 1 ELSE 0 END) AS med_fit,
    SUM(CASE WHEN s.medically_fit=0 THEN 1 ELSE 0 END) AS med_unfit,
    SUM(CASE WHEN s.profile_completed=1 AND s.medical_status='completed' THEN 1 ELSE 0 END) AS med_wait,
    
    -- إكمال الملف
    SUM(CASE WHEN s.profile_completed=1 THEN 1 ELSE 0 END) AS profile_ok
  FROM students s
  LEFT JOIN colleges c ON c.id = s.college_id
  $where
  GROUP BY c.id, c.name
  ORDER BY total DESC, c.name ASC
  LIMIT 20
";
$st = $mysqli1->prepare($sqlByCollege);
if ($types) $st->bind_param($types, ...$params);
$st->execute(); $byCollege = $st->get_result()->fetch_all(MYSQLI_ASSOC); $st->close();

/* ---------- By Batch ---------- */
$sqlByBatch = "
  SELECT b.id, b.value AS name,
    COUNT(*) AS total,
    
    -- حالة المقابلة
    SUM(CASE WHEN s.interview_status='accepted' THEN 1 ELSE 0 END) AS accepted,
    SUM(CASE WHEN s.interview_status='rejected' THEN 1 ELSE 0 END) AS rejected,
    SUM(CASE WHEN s.profile_completed=1 AND s.interview_status='pending' THEN 1 ELSE 0 END) AS pending,
    
    -- الحالة الطبية
    SUM(CASE WHEN s.medically_fit=1 THEN 1 ELSE 0 END) AS med_fit,
    SUM(CASE WHEN s.medically_fit=0 THEN 1 ELSE 0 END) AS med_unfit
  FROM students s
  LEFT JOIN batches b ON b.id = s.batch_id
  $where
  GROUP BY b.id, b.value
  ORDER BY total DESC, b.value ASC
  LIMIT 20
";
$st = $mysqli1->prepare($sqlByBatch);
if ($types) $st->bind_param($types, ...$params);
$st->execute(); $byBatch = $st->get_result()->fetch_all(MYSQLI_ASSOC); $st->close();

/* ---------- By Gender ---------- */
$sqlByGender = "
  SELECT 
    CASE 
      WHEN s.gender = 1 THEN 'ذكر'
      WHEN s.gender = 2 THEN 'أنثى'
      ELSE 'غير محدد'
    END AS gender_name,
    COUNT(*) AS total,
    SUM(CASE WHEN s.interview_status='accepted' THEN 1 ELSE 0 END) AS accepted,
    SUM(CASE WHEN s.interview_status='rejected' THEN 1 ELSE 0 END) AS rejected,
    SUM(CASE WHEN s.profile_completed=1 AND s.interview_status='pending' THEN 1 ELSE 0 END) AS pending
  FROM students s
  $where
  GROUP BY s.gender
  ORDER BY total DESC
";
$st = $mysqli1->prepare($sqlByGender);
if ($types) $st->bind_param($types, ...$params);
$st->execute(); $byGender = $st->get_result()->fetch_all(MYSQLI_ASSOC); $st->close();

/* ---------- Recent Students (with profile completion filter) ---------- */
/* Search param */
$q = trim((string)($_GET['q'] ?? ''));

/* Completed-only toggle (default ON = '1') */
$onlyCompleted = ($_GET['completed'] ?? '1') === '1';

/* Medical status filter */
$medicalFilter = $_GET['medical'] ?? 'all';

if ($q !== '') {
  // Search by student_id or name (Arabic/English) within scope
  $sqlRecent = "
    SELECT 
      s.student_id, s.student_name, s.student_name_eng, 
      s.college_id, c.name AS college_name,
      s.section_id, sec.name AS section_name,
      s.batch_id, b.value AS batch_name,
      s.gender,
      s.interview_status as current_status,
      s.medically_fit,
      s.medical_status,
      COALESCE(s.profile_completed, 0) as profile_completed
    FROM students s
    LEFT JOIN colleges c ON c.id=s.college_id
    LEFT JOIN sections sec ON sec.id=s.section_id
    LEFT JOIN batches b ON b.id=s.batch_id
    $where
      AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?)
      " . ($onlyCompleted ? " AND COALESCE(s.profile_completed,0)=1 " : "") . "
      " . ($medicalFilter !== 'all' ? 
          ($medicalFilter === 'fit' ? " AND s.medically_fit=1 " : 
           ($medicalFilter === 'unfit' ? " AND s.medically_fit=0 " : 
            " AND (s.medically_fit IS NULL OR s.medically_fit='') ")) 
          : "") . "
    ORDER BY s.student_id DESC
    LIMIT 50
  ";
  $st = $mysqli1->prepare($sqlRecent);
  $kw = '%'.$q.'%';
  if ($types !== '') {
    $bindTypes = $types . 'sss';
    $bindArgs  = array_merge($params, [$kw,$kw,$kw]);
    $st->bind_param($bindTypes, ...$bindArgs);
  } else {
    $st->bind_param('sss', $kw,$kw,$kw);
  }
} else {
  // Default: show latest students in scope with optional profile completion filter
  $sqlRecent = "
    SELECT 
      s.student_id, s.student_name, s.student_name_eng, 
      s.college_id, c.name AS college_name,
      s.section_id, sec.name AS section_name,
      s.batch_id, b.value AS batch_name,
      s.gender,
      s.interview_status as current_status,
      s.medically_fit,
      s.medical_status,
      COALESCE(s.profile_completed, 0) as profile_completed
    FROM students s
    LEFT JOIN colleges c ON c.id=s.college_id
    LEFT JOIN sections sec ON sec.id=s.section_id
    LEFT JOIN batches b ON b.id=s.batch_id
    $where
      " . ($onlyCompleted ? " AND COALESCE(s.profile_completed,0)=1 " : "") . "
      " . ($medicalFilter !== 'all' ? 
          ($medicalFilter === 'fit' ? " AND s.medically_fit=1 " : 
           ($medicalFilter === 'unfit' ? " AND s.medically_fit=0 " : 
            " AND (s.medically_fit IS NULL OR s.medically_fit='') ")) 
          : "") . "
    ORDER BY s.student_id DESC
    LIMIT 50
  ";
  $st = $mysqli1->prepare($sqlRecent);
  if ($types !== '') { 
    $st->bind_param($types, ...$params); 
  }
}
$st->execute();
$recentAccepted = $st->get_result()->fetch_all(MYSQLI_ASSOC);
$st->close();

/* ---------- UI ---------- */
include 'header.php';
?>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<style>
  body, h1,h2,h3,h4,h5,h6, p, a, button, label { font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; }
  .dash-card{border:1px solid #e5e7eb;border-radius:16px;padding:16px;background:#fff;box-shadow:0 10px 24px rgba(0,0,0,.06);}
  .kpi{display:flex;gap:16px;flex-wrap:wrap}
  .kpi .item{flex:1;min-width:180px;border-radius:14px;padding:14px;background:linear-gradient(135deg,#1F3A2E,#3E6B54);color:#fff}
  .kpi .item .n{font-size:1.8rem;font-weight:800}
  .tbl th, .tbl td{vertical-align:middle}
  .chip{display:inline-block;padding:.2rem .5rem;border-radius:999px;font-size:.85rem}
  .chip.green{background:#d1fae5;color:#065f46}
  .chip.gray{background:#e5e7eb;color:#1f2937}
  .chip.red{background:#fee2e2;color:#991b1b}
  .chip.blue{background:#dbeafe;color:#1e3a8a}
  .chip.orange{background:#fed7aa;color:#9a3412}
  .chip.purple{background:#e9d5ff;color:#7e22ce}
  .chart-legend {
    font-size: 0.8rem;
  }
  .legend-item {
    padding: 4px 8px;
    border-radius: 6px;
    transition: background-color 0.2s;
  }
  .legend-item:hover {
    background-color: #f8f9fa;
  }
  .progress {
    border-radius: 10px;
    background-color: #e9ecef;
  }
  .progress-bar {
    border-radius: 10px;
    transition: width 0.6s ease;
  }
  .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-summary-card {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 10px;
    padding: 15px;
    height: 100%;
  }
  .summary-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dee2e6;
    color: #495057;
    font-size: 0.9rem;
  }
  .summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    padding: 6px 0;
  }
  .summary-label {
    font-size: 0.8rem;
    font-weight: 600;
    color: #6c757d;
  }
  .summary-value {
    font-size: 0.8rem;
    font-weight: 600;
  }
  .vr {
    width: 1px;
    background: #dee2e6;
    margin: 0 8px;
  }
  .college-distribution {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .college-progress {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .college-name {
    min-width: 150px;
    font-weight: 600;
  }
  .progress-container {
    flex: 1;
  }
  .college-count {
    min-width: 60px;
    text-align: right;
    font-weight: 600;
  }
</style>

<div class="container py-4" dir="rtl">
  <div class="d-flex align-items-center mb-3">
    <h3 class="mb-0 fw-bold">لوحة التحكم</h3>
    <div class="ms-auto">
      <span class="chip blue">مرحباً، <?= e($committeeName ?: 'عضو اللجنة') ?></span>
      <?php if (!$canAll && $scopeCollege !== null): ?>
        <span class="chip gray">النطاق: كلية محددة</span>
      <?php else: ?>
        <span class="chip gray">النطاق: جميع الكليات</span>
      <?php endif; ?>
      <a class="btn btn-sm btn-outline-secondary ms-2" href="<?= e(INTERVIEW_LIST_PAGE) ?>">قائمة المقابلات</a>
      <a class="btn btn-sm btn-outline-secondary" href="medical_list.php">قائمة الفحص الطبي</a>
    </div>
  </div>

  <!-- KPIs -->
  <div class="kpi mb-4">
    <div class="item">
      <div class="n"><?= number_format($kpi['total']) ?></div>
      <div>إجمالي الطلبات</div>
    </div>
    <div class="item" style="background:linear-gradient(135deg,#065f46,#10b981)">
      <div class="n"><?= number_format($kpi['st_accepted']) ?></div>
      <div>تم قبولها</div>
    </div>
    <div class="item" style="background:linear-gradient(135deg,#6b7280,#9ca3af)">
      <div class="n"><?= number_format($kpi['st_pending']) ?></div>
      <div>قيد الانتظار</div>
    </div>
    <div class="item" style="background:linear-gradient(135deg,#991b1b,#ef4444)">
      <div class="n"><?= number_format($kpi['st_rejected']) ?></div>
      <div>مرفوضة</div>
    </div>
  </div>

  <!-- Charts -->
  <div class="row g-3 mb-4">
    <!-- Interview Status - Enhanced -->
    <div class="col-md-6">
      <div class="dash-card">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h6 class="fw-bold mb-0">حالة المقابلات</h6>
          <div class="text-muted small">
            إجمالي: <?= number_format($kpi['total']) ?>
          </div>
        </div>
        <div class="row align-items-center">
          <div class="col-7">
            <canvas id="statusChart" height="220"></canvas>
          </div>
          <div class="col-5">
            <div class="chart-legend">
              <div class="legend-item d-flex align-items-center mb-2">
                <div class="legend-color me-2" style="background: linear-gradient(135deg, #10b981, #059669); width: 12px; height: 12px; border-radius: 50%;"></div>
                <span class="small">مقبول</span>
                <span class="ms-auto fw-bold"><?= number_format($kpi['st_accepted']) ?></span>
              </div>
              <div class="legend-item d-flex align-items-center mb-2">
                <div class="legend-color me-2" style="background: linear-gradient(135deg, #6b7280, #4b5563); width: 12px; height: 12px; border-radius: 50%;"></div>
                <span class="small">قيد الانتظار</span>
                <span class="ms-auto fw-bold"><?= number_format($kpi['st_pending']) ?></span>
              </div>
              <div class="legend-item d-flex align-items-center mb-2">
                <div class="legend-color me-2" style="background: linear-gradient(135deg, #ef4444, #dc2626); width: 12px; height: 12px; border-radius: 50%;"></div>
                <span class="small">مرفوض</span>
                <span class="ms-auto fw-bold"><?= number_format($kpi['st_rejected']) ?></span>
              </div>
              <div class="mt-3 p-2 rounded" style="background: #f8f9fa;">
                <div class="small text-center">
                  <div>نسبة القبول</div>
                  <div class="fw-bold text-success">
                    <?= $kpi['total'] > 0 ? number_format(($kpi['st_accepted'] / $kpi['total']) * 100, 1) : 0 ?>%
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Medical Examination - Enhanced -->
    <div class="col-md-6">
      <div class="dash-card">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h6 class="fw-bold mb-0">الفحص الطبي</h6>
          <div class="text-muted small">
            تم الفحص: <?= number_format($kpi['med_fit'] + $kpi['med_unfit']) ?>
          </div>
        </div>
        <div class="row align-items-center">
          <div class="col-7">
            <canvas id="medicalChart" height="220"></canvas>
          </div>
          <div class="col-5">
            <div class="chart-legend">
              <div class="legend-item d-flex align-items-center mb-2">
                <div class="legend-color me-2" style="background: linear-gradient(135deg, #10b981, #059669); width: 12px; height: 12px; border-radius: 50%;"></div>
                <span class="small">لائق طبياً</span>
                <span class="ms-auto fw-bold"><?= number_format($kpi['med_fit']) ?></span>
              </div>
              <div class="legend-item d-flex align-items-center mb-2">
                <div class="legend-color me-2" style="background: linear-gradient(135deg, #f59e0b, #d97706); width: 12px; height: 12px; border-radius: 50%;"></div>
                <span class="small">بانتظار الفحص</span>
                <span class="ms-auto fw-bold"><?= number_format($kpi['med_wait']) ?></span>
              </div>
              <div class="legend-item d-flex align-items-center mb-2">
                <div class="legend-color me-2" style="background: linear-gradient(135deg, #ef4444, #dc2626); width: 12px; height: 12px; border-radius: 50%;"></div>
                <span class="small">غير لائق</span>
                <span class="ms-auto fw-bold"><?= number_format($kpi['med_unfit']) ?></span>
              </div>
              <div class="mt-3 p-2 rounded" style="background: #f8f9fa;">
                <div class="small text-center">
                  <div>نسبة اللائقين</div>
                  <div class="fw-bold text-success">
                    <?= ($kpi['med_fit'] + $kpi['med_unfit']) > 0 ? number_format(($kpi['med_fit'] / ($kpi['med_fit'] + $kpi['med_unfit'])) * 100, 1) : 0 ?>%
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- College Distribution -->
    <div class="col-md-8">
      <div class="dash-card">
        <h6 class="fw-bold mb-3">توزيع الطلاب حسب الكليات</h6>
        <div class="college-distribution">
          <?php 
          $topColleges = array_slice($byCollege, 0, 10);
          foreach ($topColleges as $college): 
            $percentage = $kpi['total'] > 0 ? ($college['total'] / $kpi['total']) * 100 : 0;
            $barColor = $percentage > 20 ? 'bg-success' : ($percentage > 10 ? 'bg-primary' : 'bg-info');
          ?>
            <div class="college-progress">
              <div class="college-name"><?= e($college['name'] ?: 'كلية #' . $college['id']) ?></div>
              <div class="progress-container">
                <div class="progress" style="height: 20px;">
                  <div class="progress-bar <?= $barColor ?>" role="progressbar" 
                       style="width: <?= $percentage ?>%" 
                       aria-valuenow="<?= $percentage ?>" 
                       aria-valuemin="0" 
                       aria-valuemax="100">
                    <span class="progress-text" style="font-size: 0.75rem; padding: 0 5px;">
                      <?= number_format($percentage, 1) ?>%
                    </span>
                  </div>
                </div>
              </div>
              <div class="college-count"><?= number_format($college['total']) ?></div>
            </div>
          <?php endforeach; ?>
        </div>
        <?php if (count($byCollege) > 8): ?>
          <div class="mt-2 text-center">
            <small class="text-muted">عرض <?= count($topColleges) ?> من <?= count($byCollege) ?> كلية</small>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Gender Distribution -->
    <div class="col-md-4">
      <div class="dash-card">
        <h6 class="fw-bold mb-3">توزيع الطلاب حسب الجنس</h6>
        <canvas id="genderChart" height="200"></canvas>
        <div class="mt-3 text-center">
          
        </div>
      </div>
    </div>
  </div>

  <script>
  // Enhanced Interview Status Chart
  const statusChart = new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
      labels: ['مقبول', 'قيد الانتظار', 'مرفوض'],
      datasets: [{
        data: [<?= $kpi['st_accepted'] ?>, <?= $kpi['st_pending'] ?>, <?= $kpi['st_rejected'] ?>],
        backgroundColor: [
          'rgba(16, 185, 129, 0.8)',
          'rgba(107, 114, 128, 0.8)',
          'rgba(239, 68, 68, 0.8)'
        ],
        borderColor: [
          'rgb(16, 185, 129)',
          'rgb(107, 114, 128)',
          'rgb(239, 68, 68)'
        ],
        borderWidth: 2,
        hoverBackgroundColor: [
          'rgba(16, 185, 129, 1)',
          'rgba(107, 114, 128, 1)',
          'rgba(239, 68, 68, 1)'
        ],
        hoverOffset: 8
      }]
    },
    options: {
      responsive: true,
      cutout: '70%',
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: function(context) {
              const total = <?= $kpi['total'] ?>;
              const value = context.raw;
              const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
              return `${context.label}: ${value} (${percentage}%)`;
            }
          }
        }
      },
      animation: {
        animateScale: true,
        animateRotate: true
      }
    }
  });

  // Enhanced Medical Chart
  const medicalChart = new Chart(document.getElementById('medicalChart'), {
    type: 'pie',
    data: {
      labels: ['لائق طبياً', 'بانتظار الفحص', 'غير لائق'],
      datasets: [{
        data: [<?= $kpi['med_fit'] ?>, <?= $kpi['med_wait'] ?>, <?= $kpi['med_unfit'] ?>],
        backgroundColor: [
          'rgba(16, 185, 129, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(239, 68, 68, 0.8)'
        ],
        borderColor: [
          'rgb(16, 185, 129)',
          'rgb(245, 158, 11)',
          'rgb(239, 68, 68)'
        ],
        borderWidth: 2,
        hoverOffset: 12
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: function(context) {
              const total = <?= $kpi['total'] ?>;
              const value = context.raw;
              const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
              return `${context.label}: ${value} (${percentage}%)`;
            }
          }
        }
      },
      animation: {
        animateScale: true,
        animateRotate: true
      }
    }
  });

  // Gender Distribution Chart
  const genderData = <?= json_encode($byGender) ?>;
  const genderChart = new Chart(document.getElementById('genderChart'), {
    type: 'pie',
    data: {
      labels: genderData.map(g => g.gender_name),
      datasets: [{
        data: genderData.map(g => g.total),
        backgroundColor: [
          'rgba(59, 130, 246, 0.8)',
          'rgba(236, 72, 153, 0.8)',
          'rgba(107, 114, 128, 0.8)'
        ],
        borderColor: [
          'rgb(59, 130, 246)',
          'rgb(236, 72, 153)',
          'rgb(107, 114, 128)'
        ],
        borderWidth: 2,
        hoverOffset: 12
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            usePointStyle: true,
            padding: 15
          }
        }
      },
      animation: {
        animateScale: true,
        animateRotate: true
      }
    }
  });
  </script>

  <!-- Filter Card -->
  <div class="dash-card mb-4">
    <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>
              نظام التصفية
            </span>
          </div>
        </div>
        
        <form method="get" class="row g-3 align-items-end" id="filterForm">
          <?php if ($canAll): ?>
          <!-- College Filter (Only for users with can_view_all = 1) -->
          <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
                  // Fetch colleges for filter
                  $filter_colleges_sql = "SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name";
                  $filter_colleges_result = $mysqli1->query($filter_colleges_sql);
                  while ($college = $filter_colleges_result->fetch_assoc()) {
                    $selected = (isset($_GET['filter_college']) && $_GET['filter_college'] == $college['id']) ? 'selected' : '';
                    echo "<option value=\"{$college['id']}\" $selected>" . e($college['name']) . "</option>";
                  }
                  ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-building"></i>
                </span>
              </div>
            </div>
          </div>
          <?php else: ?>
            <input type="hidden" name="filter_college" value="<?= $scopeCollege ?>">
          <?php endif; ?>
          
          <!-- Section 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-layer-group me-1"></i>
                القسم
              </label>
              <div class="input-group input-group-sm">
                <select class="form-control border-end-0" name="filter_section" id="filter_section">
                  <option value="">جميع الأقسام</option>
                  <?php
                  // Fetch sections based on selected college or all sections
                  $selected_college_id = $canAll ? ($_GET['filter_college'] ?? null) : $scopeCollege;
                  if ($selected_college_id) {
                    $sections_sql = "SELECT id, name FROM sections WHERE parent = ? ORDER BY name";
                    $sections_stmt = $mysqli1->prepare($sections_sql);
                    $sections_stmt->bind_param("i", $selected_college_id);
                    $sections_stmt->execute();
                    $sections_result = $sections_stmt->get_result();
                    while ($section = $sections_result->fetch_assoc()) {
                      $selected = (isset($_GET['filter_section']) && $_GET['filter_section'] == $section['id']) ? 'selected' : '';
                      echo "<option value=\"{$section['id']}\" $selected>" . e($section['name']) . "</option>";
                    }
                    $sections_stmt->close();
                  } else {
                    // Show all sections if no college selected
                    $all_sections_sql = "SELECT id, name FROM sections ORDER BY name";
                    $all_sections_result = $mysqli1->query($all_sections_sql);
                    while ($section = $all_sections_result->fetch_assoc()) {
                      $selected = (isset($_GET['filter_section']) && $_GET['filter_section'] == $section['id']) ? 'selected' : '';
                      echo "<option value=\"{$section['id']}\" $selected>" . e($section['name']) . "</option>";
                    }
                  }
                  ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-building"></i>
                </span>
              </div>
            </div>
          </div>
          
          <!-- Program 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-graduation-cap me-1"></i>
                البرنامج
              </label>
              <div class="input-group input-group-sm">
                <select class="form-control border-end-0" name="filter_program">
                  <option value="">جميع البرامج</option>
                  <?php
                  // Fetch programs from programs table
                  $filter_programs_sql = "SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name";
                  $filter_programs_result = $mysqli1->query($filter_programs_sql);
                  while ($program = $filter_programs_result->fetch_assoc()) {
                    $selected = (isset($_GET['filter_program']) && $_GET['filter_program'] == $program['id']) ? 'selected' : '';
                    echo "<option value=\"{$program['id']}\" $selected>" . e($program['name']) . "</option>";
                  }
                  ?>
                </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-3 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
                  // Fetch batches for filter
                  $filter_batches_sql = "SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id";
                  $filter_batches_result = $mysqli1->query($filter_batches_sql);
                  while ($batch = $filter_batches_result->fetch_assoc()) {
                    $selected = (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $batch['id']) ? 'selected' : '';
                    echo "<option value=\"{$batch['id']}\" $selected>" . e($batch['value']) . "</option>";
                  }
                  ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-calendar-alt"></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="committee_dashboard.php" class="btn btn-outline-secondary btn-sm px-3">
                <i class="fas fa-sync-alt me-1"></i>
                إعادة تعيين
              </a>
              <div class="vr mx-2"></div>
  
              <a href="registration.php" class="btn btn-outline-info btn-sm px-3">
                <i class="fas fa-cog me-1"></i>
                إعدادات متقدمة
              </a>
                            <a href="generalsetting.php" class="btn btn-outline-info btn-sm px-3">
                <i class="fas fa-cog me-1"></i>
                إعدادت الرسوم
              </a>
              
                                          <a href="user_control.php" class="btn btn-outline-info btn-sm px-3">
                <i class="fas fa-cog me-1"></i>
                إعدادت المستخدمين
              </a>
            </div>
          </div>
        </form>
      </div>
      
      <!-- Filter Summary -->
      <div class="col-md-4">
        <div class="filter-summary-card">
          <div class="summary-header">
            <i class="fas fa-info-circle me-2"></i>
            <span class="fw-semibold">ملخص التصفية</span>
          </div>
          <div class="summary-content">
            <?php
            $hasActiveFilters = false;
            
            if ($canAll && isset($_GET['filter_college']) && !empty($_GET['filter_college'])): 
              $hasActiveFilters = true;
              $selected_college_id = (int)$_GET['filter_college'];
              $college_name = $mysqli1->query("SELECT name FROM colleges WHERE id = $selected_college_id")->fetch_assoc()['name'] ?? '';
            ?>
              <div class="summary-item">
                <span class="summary-label">الكلية:</span>
                <span class="summary-value">
                  <span class="badge bg-primary bg-opacity-10 text-primary">
                    <?= e($college_name) ?>
                  </span>
                </span>
              </div>
            <?php elseif (!$canAll && $scopeCollege !== null): ?>
              <div class="summary-item">
                <span class="summary-label">الكلية:</span>
                <span class="summary-value">
                  <span class="badge bg-primary bg-opacity-10 text-primary">
                    <?php 
                    $college_name = $mysqli1->query("SELECT name FROM colleges WHERE id = $scopeCollege")->fetch_assoc()['name'] ?? '';
                    echo e($college_name);
                    ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['filter_section']) && !empty($_GET['filter_section'])): 
              $hasActiveFilters = true;
              $selected_section_id = (int)$_GET['filter_section'];
              $section_name = $mysqli1->query("SELECT name FROM sections WHERE id = $selected_section_id")->fetch_assoc()['name'] ?? '';
            ?>
              <div class="summary-item">
                <span class="summary-label">القسم:</span>
                <span class="summary-value">
                  <span class="badge bg-success bg-opacity-10 text-success">
                    <?= e($section_name) ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['filter_program']) && !empty($_GET['filter_program'])): 
              $hasActiveFilters = true;
              $selected_program_id = (int)$_GET['filter_program'];
              $program_name = $mysqli1->query("SELECT name FROM programs WHERE id = $selected_program_id")->fetch_assoc()['name'] ?? '';
            ?>
              <div class="summary-item">
                <span class="summary-label">البرنامج:</span>
                <span class="summary-value">
                  <span class="badge bg-info bg-opacity-10 text-info">
                    <?= e($program_name) ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['filter_batch']) && !empty($_GET['filter_batch'])): 
              $hasActiveFilters = true;
              $selected_batch_id = (int)$_GET['filter_batch'];
              $batch_name = $mysqli1->query("SELECT value FROM batches WHERE id = $selected_batch_id")->fetch_assoc()['value'] ?? '';
            ?>
              <div class="summary-item">
                <span class="summary-label">الدفعة:</span>
                <span class="summary-value">
                  <span class="badge bg-warning bg-opacity-10 text-warning">
                    <?= e($batch_name) ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if (!$hasActiveFilters && $canAll): ?>
              <div class="summary-item">
                <span class="summary-label">الحالة:</span>
                <span class="summary-value">
                  <span class="badge bg-secondary bg-opacity-10 text-secondary">
                    جميع الكليات
                  </span>
                </span>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- التقارير حسب الكليات -->
  <div class="dash-card mb-4">
    <div class="d-flex align-items-center mb-3">
      <h6 class="fw-bold mb-0">التقارير حسب الكليات</h6>
      <div class="ms-auto">
        <!-- Status Filter Buttons -->
        <div class="btn-group" role="group" aria-label="Status filter">
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'all'])) ?>" 
             class="btn btn-sm <?= ($_GET['status'] ?? 'all') === 'all' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            الكل
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'pending'])) ?>" 
             class="btn btn-sm <?= ($_GET['status'] ?? '') === 'pending' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            قيد الانتظار
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'accepted'])) ?>" 
             class="btn btn-sm <?= ($_GET['status'] ?? '') === 'accepted' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            المقبولين
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'rejected'])) ?>" 
             class="btn btn-sm <?= ($_GET['status'] ?? '') === 'rejected' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            المرفوضين
          </a>
        </div>
      </div>
    </div>

    <?php
    // Apply status filter to college data
    $statusFilter = $_GET['status'] ?? 'all';
    $filteredByCollege = $byCollege;
    
    if ($statusFilter !== 'all' && in_array($statusFilter, ['pending', 'accepted', 'rejected'])) {
      $filteredByCollege = array_filter($byCollege, function($college) use ($statusFilter) {
        return ($college[$statusFilter] ?? 0) > 0;
      });
    }
    ?>

    <div class="table-responsive">
      <table class="table table-sm tbl">
        <thead class="table-light">
          <tr>
            <th>الكلية</th>
            <th class="text-end">الإجمالي</th>
            <th class="text-end">مقبول</th>
            <th class="text-end">قيد الانتظار</th>
            <th class="text-end">مرفوض</th>
            <th class="text-end">لائق</th>
            <th class="text-end">غير لائق</th>
            <th class="text-end">انتظار طبي</th>
            <th class="text-end">ملف مكتمل</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($filteredByCollege)): ?>
            <tr>
              <td colspan="9" class="text-center text-muted py-3">
                <?php if ($statusFilter !== 'all'): ?>
                  لا توجد كليات تحتوي على طلبات <?= e($statusFilter === 'accepted' ? 'مقبولة' : ($statusFilter === 'pending' ? 'قيد الانتظار' : 'مرفوضة')) ?>
                <?php else: ?>
                  لا توجد بيانات لعرضها.
                <?php endif; ?>
              </td>
            </tr>
          <?php else: foreach ($filteredByCollege as $r): ?>
            <tr>
              <td><?= e($r['name'] ?: ('كلية #'.$r['id'])) ?></td>
              <td class="text-end"><?= number_format($r['total']) ?></td>
              <td class="text-end">
                <?php if ($r['accepted'] > 0): ?>
                  <a href="<?= e(INTERVIEW_LIST_PAGE) ?>?college=<?= $r['id'] ?>&status=accepted" class="text-decoration-none">
                    <?= number_format($r['accepted']) ?>
                  </a>
                <?php else: ?>
                  <?= number_format($r['accepted']) ?>
                <?php endif; ?>
              </td>
              <td class="text-end">
                <?php if ($r['pending'] > 0): ?>
                  <a href="<?= e(INTERVIEW_LIST_PAGE) ?>?college=<?= $r['id'] ?>&status=pending" class="text-decoration-none">
                    <?= number_format($r['pending']) ?>
                  </a>
                <?php else: ?>
                  <?= number_format($r['pending']) ?>
                <?php endif; ?>
              </td>
              <td class="text-end">
                <?php if ($r['rejected'] > 0): ?>
                  <a href="<?= e(INTERVIEW_LIST_PAGE) ?>?college=<?= $r['id'] ?>&status=rejected" class="text-decoration-none">
                    <?= number_format($r['rejected']) ?>
                  </a>
                <?php else: ?>
                  <?= number_format($r['rejected']) ?>
                <?php endif; ?>
              </td>
              <td class="text-end"><?= number_format($r['med_fit']) ?></td>
              <td class="text-end"><?= number_format($r['med_unfit']) ?></td>
              <td class="text-end"><?= number_format($r['med_wait']) ?></td>
              <td class="text-end"><?= number_format($r['profile_ok']) ?></td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>

    <?php if ($statusFilter !== 'all'): ?>
      <div class="mt-2 text-center">
        <a href="committee_dashboard.php?<?= http_build_query(array_diff_key($_GET, ['status'=>''])) ?>" 
           class="btn btn-sm btn-outline-secondary">
          إلغاء التصفية وعرض جميع الكليات
        </a>
      </div>
    <?php endif; ?>
  </div>

  <!-- التقارير الإضافية -->
  <div class="dash-card mb-4">
    <div class="d-flex align-items-center mb-3">
      <div class="filter-icon me-2">
        <i class="fas fa-chart-line"></i>
      </div>
      <h6 class="fw-bold mb-0 text-dark">التقارير والإحصائيات</h6>
      <div class="ms-auto">
        <span class="badge bg-light text-dark border">
          <i class="fas fa-file-alt me-1"></i>
          نظام التقارير
        </span>
      </div>
    </div>

    <!-- Registration Reports -->
    <div class="kpi mb-4">
      <a href="reports/registered_students.php" class="item" style="background:linear-gradient(135deg,#1F3A2E,#3E6B54); text-decoration:none; cursor:pointer">
        <div class="n">
          <i class="fas fa-check-circle me-2"></i>
        </div>
        <div>الطلاب المسجلين كاملاً</div>
        <small class="opacity-75">جميع الرسوم مسددة</small>
      </a>
      <a href="reports/unregistered_students.php" class="item" style="background:linear-gradient(135deg,#7c2d12,#dc2626); text-decoration:none; cursor:pointer">
        <div class="n">
          <i class="fas fa-times-circle me-2"></i>
        </div>
        <div>الطلاب غير المسجلين</div>
        <small class="opacity-75">لم يسددوا أي رسوم</small>
      </a>
      <a href="reports/partially_registered.php" class="item" style="background:linear-gradient(135deg,#78350f,#d97706); text-decoration:none; cursor:pointer">
        <div class="n">
          <i class="fas fa-exclamation-circle me-2"></i>
        </div>
        <div>مسجلين جزئياً</div>
        <small class="opacity-75">سددوا بعض الرسوم</small>
      </a>
    </div>

    <!-- Attendance Reports -->
    <div class="kpi mb-4">
      <a href="reports/lecture_attendance.php" class="item" style="background:linear-gradient(135deg,#065f46,#10b981); text-decoration:none; cursor:pointer">
        <div class="n">
          <i class="fas fa-chalkboard-teacher me-2"></i>
        </div>
        <div>حضور المحاضرات</div>
        <small class="opacity-75">سجل الحضور اليومي</small>
      </a>
      <a href="reports/exam_attendance.php" class="item" style="background:linear-gradient(135deg,#1e3a8a,#3b82f6); text-decoration:none; cursor:pointer">
        <div class="n">
          <i class="fas fa-file-signature me-2"></i>
        </div>
        <div>حضور الامتحان</div>
        <small class="opacity-75">نتائج وتوقيعات الطلاب</small>
      </a>
    </div>
  </div>

  <!-- آخر الطلبات / المكتملين -->
  <div class="dash-card">
    <div class="d-flex align-items-center justify-content-between">
      <h6 class="fw-bold mb-0">آخر الطلبات / المكتملين</h6>

      <div class="d-flex align-items-center gap-2" style="flex-wrap:wrap">
        <!-- Medical Status Filter -->
        <div class="btn-group" role="group" aria-label="Medical status filter">
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'all'])) ?>"
             class="btn btn-sm <?= ($_GET['medical'] ?? 'all') === 'all' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            جميع الحالات الطبية
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'fit'])) ?>"
             class="btn btn-sm <?= ($_GET['medical'] ?? '') === 'fit' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            لائق
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'unfit'])) ?>"
             class="btn btn-sm <?= ($_GET['medical'] ?? '') === 'unfit' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            غير لائق
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'pending'])) ?>"
             class="btn btn-sm <?= ($_GET['medical'] ?? '') === 'pending' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            انتظار فحص
          </a>
        </div>

        <!-- Completed toggle -->
        <div class="btn-group" role="group" aria-label="Completed filter">
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['completed'=>'1'])) ?>"
             class="btn btn-sm <?= $onlyCompleted ? 'btn-primary' : 'btn-outline-secondary' ?>">
            مكتمل الملف فقط
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['completed'=>'0'])) ?>"
             class="btn btn-sm <?= !$onlyCompleted ? 'btn-primary' : 'btn-outline-secondary' ?>">
            الكل (بغض النظر عن الملف)
          </a>
        </div>

        <!-- Search form -->
        <form class="d-flex gap-2" method="get" action="committee_dashboard.php" style="max-width:520px">
          <!-- Preserve filter parameters -->
          <input type="hidden" name="filter_college" value="<?= e($_GET['filter_college'] ?? '') ?>">
          <input type="hidden" name="filter_section" value="<?= e($_GET['filter_section'] ?? '') ?>">
          <input type="hidden" name="filter_program" value="<?= e($_GET['filter_program'] ?? '') ?>">
          <input type="hidden" name="filter_batch" value="<?= e($_GET['filter_batch'] ?? '') ?>">
          <input type="hidden" name="completed" value="<?= $onlyCompleted ? '1' : '0' ?>">
          <input type="hidden" name="medical" value="<?= e($_GET['medical'] ?? 'all') ?>">
          <input
            type="text"
            class="form-control form-control-sm"
            name="q"
            placeholder="بحث بالاسم أو الرقم الجامعي"
            value="<?= e($q ?? '') ?>"
            aria-label="بحث بالاسم أو الرقم الجامعي"
          >
          <button class="btn btn-sm btn-primary" type="submit">بحث</button>
          <?php if (!empty($q) || ($_GET['medical'] ?? 'all') !== 'all' || !empty($_GET['filter_college']) || !empty($_GET['filter_section']) || !empty($_GET['filter_program']) || !empty($_GET['filter_batch'])): ?>
            <a class="btn btn-sm btn-outline-secondary" href="committee_dashboard.php?completed=<?= $onlyCompleted ? '1' : '0' ?>">مسح</a>
          <?php endif; ?>
        </form>
      </div>
    </div>

    <?php if (!empty($q) || ($_GET['medical'] ?? 'all') !== 'all' || !empty($_GET['filter_college']) || !empty($_GET['filter_section']) || !empty($_GET['filter_program']) || !empty($_GET['filter_batch'])): ?>
      <div class="text-muted small mt-2">
        <?php if (!empty($q)): ?>
          عدد النتائج: <?= number_format(count($recentAccepted)) ?> لـ "<?= e($q) ?>"
        <?php endif; ?>
        <?php if (($_GET['medical'] ?? 'all') !== 'all'): ?>
          <?php if (!empty($q)): ?> | <?php endif; ?>
          التصفية الطبية: 
          <?= e([
            'fit' => 'لائق فقط',
            'unfit' => 'غير لائق فقط', 
            'pending' => 'بانتظار الفحص فقط'
          ][$_GET['medical']] ?? '') ?>
        <?php endif; ?>
        <?php if (!empty($_GET['filter_college']) || !empty($_GET['filter_section']) || !empty($_GET['filter_program']) || !empty($_GET['filter_batch'])): ?>
          <?php if (!empty($q) || ($_GET['medical'] ?? 'all') !== 'all'): ?> | <?php endif; ?>
          التصفية: 
          <?php
          $filter_parts = [];
          if (!empty($_GET['filter_college'])) {
            $college_name = $mysqli1->query("SELECT name FROM colleges WHERE id = " . (int)$_GET['filter_college'])->fetch_assoc()['name'] ?? '';
            $filter_parts[] = "كلية: " . e($college_name);
          }
          if (!empty($_GET['filter_section'])) {
            $section_name = $mysqli1->query("SELECT name FROM sections WHERE id = " . (int)$_GET['filter_section'])->fetch_assoc()['name'] ?? '';
            $filter_parts[] = "قسم: " . e($section_name);
          }
          if (!empty($_GET['filter_program'])) {
            $program_name = $mysqli1->query("SELECT name FROM programs WHERE id = " . (int)$_GET['filter_program'])->fetch_assoc()['name'] ?? '';
            $filter_parts[] = "برنامج: " . e($program_name);
          }
          if (!empty($_GET['filter_batch'])) {
            $batch_name = $mysqli1->query("SELECT value FROM batches WHERE id = " . (int)$_GET['filter_batch'])->fetch_assoc()['value'] ?? '';
            $filter_parts[] = "دفعة: " . e($batch_name);
          }
          echo implode('، ', $filter_parts);
          ?>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <div class="table-responsive">
      <table class="table table-sm">
        <thead class="table-light">
          <tr>
            <th>الطالب</th>
            <th>الرقم</th>
            <th>الكلية</th>
            <th>القسم</th>
            <th>الدفعة</th>
            <th>الجنس</th>
            <th>حالة المقابلة</th>
            <th>الملف</th>
            <th>الحالة الطبية</th>
            <th style="width:110px"></th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$recentAccepted): ?>
            <tr><td colspan="10" class="text-center text-muted py-3">— لا توجد نتائج —</td></tr>
          <?php else: foreach ($recentAccepted as $r): ?>
            <tr>
              <td><?= e($r['student_name'] ?: $r['student_name_eng'] ?: '—') ?></td>
              <td><code><?= e($r['student_id']) ?></code></td>
              <td><?= e($r['college_name'] ?: $r['college_id']) ?></td>
              <td><?= e($r['section_name'] ?: $r['section_id']) ?></td>
              <td><?= e($r['batch_name'] ?: $r['batch_id']) ?></td>
              <td>
                <?php 
                $gender = $r['gender'] ?? 0;
                $genderText = $gender == 1 ? 'ذكر' : ($gender == 2 ? 'أنثى' : 'غير محدد');
                $genderClass = $gender == 1 ? 'chip blue' : ($gender == 2 ? 'chip purple' : 'chip gray');
                ?>
                <span class="<?= $genderClass ?>"><?= e($genderText) ?></span>
              </td>
              <td>
                <?php 
                $status = $r['current_status'] ?? 'pending';
                $statusClass = [
                  'accepted' => 'chip green',
                  'pending'  => 'chip gray',
                  'rejected' => 'chip red'
                ][$status] ?? 'chip gray';
                $statusText = [
                  'accepted' => 'مقبول',
                  'pending'  => 'قيد الانتظار',
                  'rejected' => 'مرفوض'
                ][$status] ?? $status;
                ?>
                <span class="<?= $statusClass ?>"><?= e($statusText) ?></span>
              </td>
              <td>
                <?php 
                $profileStatus = $r['profile_completed'] ?? 0;
                $profileClass = $profileStatus ? 'chip green' : 'chip gray';
                $profileText = $profileStatus ? 'مكتمل' : 'غير مكتمل';
                ?>
                <span class="<?= $profileClass ?>"><?= e($profileText) ?></span>
              </td>
              <td>
                <?php 
                // Corrected Medical Status Display based on requirements
                $medically_fit = $r['medically_fit'];
                $medical_status = $r['medical_status'] ?? '';
                
                if ($medically_fit == 1) {
                    $medClass = 'chip green';
                    $medText = 'لائق';
                } elseif ($medically_fit == 0) {
                    $medClass = 'chip red';
                    $medText = 'غير لائق';
                } else {
                    $medClass = 'chip orange';
                    $medText = 'انتظار فحص';
                }
                ?>
                <span class="<?= $medClass ?>"><?= e($medText) ?></span>
              </td>
              <td>
                <div class="btn-group" role="group">
                  <a class="btn btn-sm btn-primary" href="interview_review.php?student_id=<?= urlencode($r['student_id']) ?>">مقابلة</a>
                  <a class="btn btn-sm btn-info" href="committee_student_profile.php?student_id=<?= urlencode($r['student_id']) ?>">الملف</a>
                </div>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
// Function to load sections based on selected college
function loadSections(collegeId) {
    const sectionSelect = document.getElementById('filter_section');
    
    if (!collegeId || collegeId === '') {
        // Show all sections
        fetch('get_sections.php?all=1')
            .then(response => response.json())
            .then(sections => {
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                sections.forEach(section => {
                    sectionSelect.innerHTML += `<option value="${section.id}">${section.name}</option>`;
                });
            });
    } else {
        // Fetch sections for selected college
        fetch(`get_sections.php?college_id=${collegeId}`)
            .then(response => response.json())
            .then(sections => {
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                sections.forEach(section => {
                    sectionSelect.innerHTML += `<option value="${section.id}">${section.name}</option>`;
                });
            });
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // If college filter is selected, load its sections
    const collegeSelect = document.getElementById('filter_college');
    if (collegeSelect && collegeSelect.value) {
        loadSections(collegeSelect.value);
    }
});
</script>

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