<?php
// /admission3333/committee_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;
}

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

// Scope WHERE - For single college system
$where = " WHERE 1=1 ";
$types = ''; $params = [];
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 college filter
if ($filter_college_id && !empty($filter_college_id)) {
  $where .= " AND s.college_id = ? ";
  $types .= 'i'; 
  $params[] = $filter_college_id;
}

// 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 Section ---------- */
$sqlBySection = "
  SELECT sec.id, sec.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 sections sec ON sec.id = s.section_id
  $where
  GROUP BY sec.id, sec.name
  ORDER BY total DESC, sec.name ASC
  LIMIT 50
";
$st = $mysqli1->prepare($sqlBySection);
if ($types) $st->bind_param($types, ...$params);
$st->execute(); $bySection = $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 50
";
$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.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 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 250
  ";
  $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.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 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 300
  ";
  $st = $mysqli1->prepare($sqlRecent);
  if ($types !== '') { 
    $st->bind_param($types, ...$params); 
  }
}
$st->execute();
$recentAccepted = $st->get_result()->fetch_all(MYSQLI_ASSOC);
$st->close();

// 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");
$batches_stmt->execute();
$batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$batches_stmt->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;
  }
  .ajax-loading {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    display: none;
  }
  .form-group {
    position: relative;
  }
</style>

<div class="container py-4">
  <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>

    <!-- Section Distribution -->
    <div class="col-md-4">
      <div class="dash-card">
        <h6 class="fw-bold mb-3">التوزيع حسب الأقسام</h6>
        <canvas id="sectionChart" height="200"></canvas>
        <div class="mt-3 text-center">
          <div class="small text-muted">
            أعلى ٥ أقسام حسب عدد الطلبات
          </div>
        </div>
      </div>
    </div>

    <!-- Batch Distribution -->
    <div class="col-md-4">
      <div class="dash-card">
        <h6 class="fw-bold mb-3">التوزيع حسب الدفعات</h6>
        <canvas id="batchChart" height="200"></canvas>
        <div class="mt-3 text-center">
          <div class="small text-muted">
            توزيع الطلبات على الدفعات
          </div>
        </div>
      </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 class="small text-muted">
            توزيع الطلبات حسب الجنس
          </div>
        </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
      }
    }
  });

  // Section Distribution Chart
  const topSections = <?= json_encode(array_slice($bySection, 0, 5)) ?>;
  const sectionChart = new Chart(document.getElementById('sectionChart'), {
    type: 'bar',
    data: {
      labels: topSections.map(section => section.name || `قسم #${section.id}`).slice(0, 5),
      datasets: [{
        label: 'عدد الطلبات',
        data: topSections.map(section => section.total).slice(0, 5),
        backgroundColor: 'rgba(59, 130, 246, 0.8)',
        borderColor: 'rgb(59, 130, 246)',
        borderWidth: 1,
        borderRadius: 6,
      }]
    },
    options: {
      indexAxis: 'y',
      responsive: true,
      plugins: {
        legend: { display: false }
      },
      scales: {
        x: {
          beginAtZero: true
        }
      },
      animation: {
        duration: 2000,
        easing: 'easeOutBounce'
      }
    }
  });

  // Batch Distribution Chart
  const batchData = <?= json_encode($byBatch) ?>;
  const batchChart = new Chart(document.getElementById('batchChart'), {
    type: 'doughnut',
    data: {
      labels: batchData.map(batch => batch.name || `دفعة #${batch.id}`),
      datasets: [{
        data: batchData.map(batch => batch.total),
        backgroundColor: [
          'rgba(16, 185, 129, 0.8)',
          'rgba(59, 130, 246, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(139, 92, 246, 0.8)',
          'rgba(236, 72, 153, 0.8)'
        ],
        borderColor: [
          'rgb(16, 185, 129)',
          'rgb(59, 130, 246)',
          'rgb(245, 158, 11)',
          'rgb(139, 92, 246)',
          'rgb(236, 72, 153)'
        ],
        borderWidth: 2,
        hoverOffset: 8
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            usePointStyle: true,
            padding: 15
          }
        }
      },
      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">
          <!-- 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'] ?>" <?= (isset($_GET['filter_college']) && $_GET['filter_college'] == $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'] ?>" <?= (isset($_GET['filter_section']) && $_GET['filter_section'] == $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 class="ajax-loading" id="sectionLoading" style="display: none;">
                  <i class="fas fa-spinner fa-spin"></i>
                </div>
              </div>
              <?php if (!$filter_college_id): ?>
                <small class="text-muted">الرجاء اختيار كلية أولاً</small>
              <?php endif; ?>
            </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" id="filter_program">
                  <option value="">جميع البرامج</option>
                  <?php foreach ($programs as $program): ?>
                    <option value="<?= $program['id'] ?>" <?= (isset($_GET['filter_program']) && $_GET['filter_program'] == $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-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 foreach ($batches as $batch): ?>
                    <option value="<?= $batch['id'] ?>" <?= (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $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>
          
          <!-- 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>
              <!-- Gear Icon for Advanced Settings - Direct link to registration.php -->
              <a href="registration.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 ($filter_college_id && !empty($filter_college_id)): 
              $hasActiveFilters = true;
              $selected_college = null;
              foreach ($colleges as $college) {
                if ($college['id'] == $filter_college_id) {
                  $selected_college = $college;
                  break;
                }
              }
            ?>
              <div class="summary-item">
                <span class="summary-label">الكلية:</span>
                <span class="summary-value">
                  <span class="badge bg-primary bg-opacity-10 text-primary">
                    <?= e($selected_college['name'] ?? '') ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if ($filter_section_id && !empty($filter_section_id) && $filter_college_id && !empty($sections)): 
              $hasActiveFilters = true;
              $selected_section = null;
              foreach ($sections as $section) {
                if ($section['id'] == $filter_section_id) {
                  $selected_section = $section;
                  break;
                }
              }
            ?>
              <div class="summary-item">
                <span class="summary-label">القسم:</span>
                <span class="summary-value">
                  <span class="badge bg-success bg-opacity-10 text-success">
                    <?= e($selected_section['name'] ?? '') ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if ($filter_program_id && !empty($filter_program_id)): 
              $hasActiveFilters = true;
              $selected_program = null;
              foreach ($programs as $program) {
                if ($program['id'] == $filter_program_id) {
                  $selected_program = $program;
                  break;
                }
              }
            ?>
              <div class="summary-item">
                <span class="summary-label">البرنامج:</span>
                <span class="summary-value">
                  <span class="badge bg-info bg-opacity-10 text-info">
                    <?= e($selected_program['name'] ?? '') ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if ($filter_batch_id && !empty($filter_batch_id)): 
              $hasActiveFilters = true;
              $selected_batch = null;
              foreach ($batches as $batch) {
                if ($batch['id'] == $filter_batch_id) {
                  $selected_batch = $batch;
                  break;
                }
              }
            ?>
              <div class="summary-item">
                <span class="summary-label">الدفعة:</span>
                <span class="summary-value">
                  <span class="badge bg-warning bg-opacity-10 text-warning">
                    <?= e($selected_batch['value'] ?? '') ?>
                  </span>
                </span>
              </div>
            <?php endif; ?>
            
            <?php if (!$hasActiveFilters): ?>
              <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; ?>
            
            <?php if ($hasActiveFilters): ?>
              <div class="summary-item mt-3 pt-3 border-top">
                <span class="summary-label">عدد الطلاب:</span>
                <span class="summary-value fw-bold text-primary">
                  <?= number_format($kpi['total']) ?>
                </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 section data
    $statusFilter = $_GET['status'] ?? 'all';
    $filteredBySection = $bySection;
    
    if ($statusFilter !== 'all' && in_array($statusFilter, ['pending', 'accepted', 'rejected'])) {
      $filteredBySection = array_filter($bySection, function($section) use ($statusFilter) {
        return ($section[$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($filteredBySection)): ?>
            <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 ($filteredBySection 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) ?>?section=<?= $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) ?>?section=<?= $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) ?>?section=<?= $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>
  
  <!-- Reports Card -->
  <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 style="width:110px"></th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$recentAccepted): ?>
            <tr><td colspan="9" 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['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>
// Load sections when college changes - SIMPLE VERSION WITHOUT AJAX
function loadSections(collegeId) {
    const sectionSelect = document.getElementById('filter_section');
    const sectionLoading = document.getElementById('sectionLoading');
    
    // Reset section select
    sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
    
    if (!collegeId || collegeId === '') {
        sectionSelect.disabled = true;
        return;
    }
    
    // Show loading indicator
    sectionSelect.disabled = true;
    sectionLoading.style.display = 'block';
    
    // Instead of AJAX, we'll use a simple form submission to reload the page
    // Create a form and submit it
    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 current section if exists
    const currentSection = "<?= isset($_GET['filter_section']) ? $_GET['filter_section'] : '' ?>";
    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 = "<?= isset($_GET['filter_program']) ? $_GET['filter_program'] : '' ?>";
    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 = "<?= isset($_GET['filter_batch']) ? $_GET['filter_batch'] : '' ?>";
    if (currentBatch) {
        const batchInput = document.createElement('input');
        batchInput.type = 'hidden';
        batchInput.name = 'filter_batch';
        batchInput.value = currentBatch;
        form.appendChild(batchInput);
    }
    
    // Add completed parameter
    const completedInput = document.createElement('input');
    completedInput.type = 'hidden';
    completedInput.name = 'completed';
    completedInput.value = "<?= $onlyCompleted ? '1' : '0' ?>";
    form.appendChild(completedInput);
    
    // Add medical parameter
    const medicalInput = document.createElement('input');
    medicalInput.type = 'hidden';
    medicalInput.name = 'medical';
    medicalInput.value = "<?= e($_GET['medical'] ?? 'all') ?>";
    form.appendChild(medicalInput);
    
    // Add search parameter if exists
    const currentSearch = "<?= e($q ?? '') ?>";
    if (currentSearch) {
        const searchInput = document.createElement('input');
        searchInput.type = 'hidden';
        searchInput.name = 'q';
        searchInput.value = currentSearch;
        form.appendChild(searchInput);
    }
    
    // Add status parameter if exists
    const currentStatus = "<?= isset($_GET['status']) ? $_GET['status'] : '' ?>";
    if (currentStatus) {
        const statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'status';
        statusInput.value = currentStatus;
        form.appendChild(statusInput);
    }
    
    document.body.appendChild(form);
    form.submit();
}
</script>

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