<?php
session_start();

// Check if user is logged in
if (empty($_SESSION['committee_id'])) {
    header("Location: committee_login.php?role=committee");
    exit;
}

// Check if user has permission to access committee dashboard
// Only allow role_id = 1 (admin) or 2 (registrar)
$user_role_id = $_SESSION['committee_role_id'] ?? 0;
if (!in_array($user_role_id, [1, 2])) {
    // Destroy session and redirect to login
    session_destroy();
    header("Location: committee_login.php?role=committee");
    exit;
}

// Optional: Store role names for display
$role_names = [
    1 => 'مدير النظام',
    2 => 'مسجل الكلية'
];
$user_role_name = $role_names[$user_role_id] ?? 'مستخدم';
?>
<?php
// /admission3333/committee_dashboard.php
require 'db.php';
require 'helpers.php';
require_committee();

require 'committee_session.php';

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

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

// دالة آمنة للتحقق من صحة الأرقام
function safe_int($value, $default = null) {
    if ($value === null || $value === '') return $default;
    $int = filter_var($value, FILTER_VALIDATE_INT);
    return $int !== false ? $int : $default;
}

// دالة آمنة للنصوص
function safe_string($value, $max_length = 255) {
    if ($value === null) return '';
    return substr(trim((string)$value), 0, $max_length);
}

// Add filter parameters from the filter card - مع التحقق الآمن
$filter_college_id = isset($_GET['filter_college']) && $_GET['filter_college'] !== '' ? safe_int($_GET['filter_college']) : null;
$filter_section_id = isset($_GET['filter_section']) && $_GET['filter_section'] !== '' ? safe_int($_GET['filter_section']) : null;
$filter_program_id = isset($_GET['filter_program']) && $_GET['filter_program'] !== '' ? safe_int($_GET['filter_program']) : null;
$filter_batch_id = isset($_GET['filter_batch']) && $_GET['filter_batch'] !== '' ? safe_int($_GET['filter_batch']) : null;
$filter_specialization_id = isset($_GET['filter_specialization']) && $_GET['filter_specialization'] !== '' ? safe_int($_GET['filter_specialization']) : 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 specialization filter
if ($filter_specialization_id && !empty($filter_specialization_id)) {
  $where .= " AND s.specialization_id = ? ";
  $types .= 'i'; 
  $params[] = $filter_specialization_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,
    -- الطلاب الذين ليس لديهم نتيجة فحص طبي (medically_fit IS NULL OR medically_fit = '')
    SUM(CASE WHEN (s.medically_fit IS NULL OR s.medically_fit = '') 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);

/* ---------- Get registration statistics based on the logic from reports ---------- */

// Get partially registered students (have both paid and unpaid registrations)
$partiallyQuery = "
    SELECT COUNT(DISTINCT s.student_id) as count
    FROM students s
    WHERE s.deleted_at IS NULL
    AND EXISTS (
        SELECT 1
        FROM registrations r
        WHERE r.student_id = s.student_id
        AND r.deleted_at IS NULL
        GROUP BY r.student_id
        HAVING 
            SUM(CASE WHEN r.is_paid = 1 THEN 1 ELSE 0 END) > 0
            AND SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) > 0
    )
";

// Get fully registered students (all registrations paid)
$fullyQuery = "
    SELECT COUNT(DISTINCT s.student_id) as count
    FROM students s
    WHERE s.deleted_at IS NULL
    AND EXISTS (
        SELECT 1
        FROM registrations r
        WHERE r.student_id = s.student_id
        AND r.deleted_at IS NULL
        GROUP BY r.student_id
        HAVING 
            SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = 0
            AND COUNT(r.id) > 0
    )
";

// Get unregistered students (no paid registrations)
$unregisteredQuery = "
    SELECT COUNT(DISTINCT s.student_id) as count
    FROM students s
    WHERE s.deleted_at IS NULL
    AND NOT EXISTS (
        SELECT 1
        FROM registrations r
        WHERE r.student_id = s.student_id
        AND r.deleted_at IS NULL
        AND r.is_paid = 1
    )
";

// Build WHERE conditions for all queries
$whereConditions = [];
$whereParams = [];
$whereTypes = "";

if (!$canAll && $scopeCollege !== null) {
    $whereConditions[] = "s.college_id = ?";
    $whereTypes .= "i";
    $whereParams[] = $scopeCollege;
}

if ($filter_college_id && !empty($filter_college_id)) {
    $whereConditions[] = "s.college_id = ?";
    $whereTypes .= "i";
    $whereParams[] = $filter_college_id;
}

if ($filter_section_id && !empty($filter_section_id)) {
    $whereConditions[] = "s.section_id = ?";
    $whereTypes .= "i";
    $whereParams[] = $filter_section_id;
}

if ($filter_program_id && !empty($filter_program_id)) {
    $whereConditions[] = "s.program_id = ?";
    $whereTypes .= "i";
    $whereParams[] = $filter_program_id;
}

if ($filter_specialization_id && !empty($filter_specialization_id)) {
    $whereConditions[] = "s.specialization_id = ?";
    $whereTypes .= "i";
    $whereParams[] = $filter_specialization_id;
}

if ($filter_batch_id && !empty($filter_batch_id)) {
    $whereConditions[] = "s.batch_id = ?";
    $whereTypes .= "i";
    $whereParams[] = $filter_batch_id;
}

// Add WHERE conditions to queries if any
if (!empty($whereConditions)) {
    $whereClause = " AND " . implode(" AND ", $whereConditions);
    $partiallyQuery .= $whereClause;
    $fullyQuery .= $whereClause;
    $unregisteredQuery .= $whereClause;
}

// Execute partially registered query
$partiallyCount = 0;
$partiallyStmt = $mysqli1->prepare($partiallyQuery);
if ($partiallyStmt) {
    if (!empty($whereParams)) {
        $partiallyStmt->bind_param($whereTypes, ...$whereParams);
    }
    $partiallyStmt->execute();
    $partiallyResult = $partiallyStmt->get_result();
    $partiallyCount = $partiallyResult->fetch_assoc()['count'] ?? 0;
    $partiallyStmt->close();
}

// Execute fully registered query
$fullyCount = 0;
$fullyStmt = $mysqli1->prepare($fullyQuery);
if ($fullyStmt) {
    if (!empty($whereParams)) {
        $fullyStmt->bind_param($whereTypes, ...$whereParams);
    }
    $fullyStmt->execute();
    $fullyResult = $fullyStmt->get_result();
    $fullyCount = $fullyResult->fetch_assoc()['count'] ?? 0;
    $fullyStmt->close();
}

// Execute unregistered query
$unregisteredCount = 0;
$unregisteredStmt = $mysqli1->prepare($unregisteredQuery);
if ($unregisteredStmt) {
    if (!empty($whereParams)) {
        $unregisteredStmt->bind_param($whereTypes, ...$whereParams);
    }
    $unregisteredStmt->execute();
    $unregisteredResult = $unregisteredStmt->get_result();
    $unregisteredCount = $unregisteredResult->fetch_assoc()['count'] ?? 0;
    $unregisteredStmt->close();
}

// Add the new counts to the kpi array
$kpi['partially_registered'] = (int)($partiallyCount);
$kpi['fully_registered'] = (int)($fullyCount);
$kpi['unregistered'] = (int)($unregisteredCount);

/* ---------- 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.medically_fit IS NULL OR s.medically_fit = '') 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 10
";
$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,
    SUM(CASE WHEN (s.medically_fit IS NULL OR s.medically_fit = '') THEN 1 ELSE 0 END) AS med_wait
  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 10
";
$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 = safe_string($_GET['q'] ?? '', 100);

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

/* Medical status filter - مع التحقق الآمن */
$medicalFilter = $_GET['medical'] ?? 'all';
$allowed_medical = ['all', 'fit', 'unfit', 'pending'];
if (!in_array($medicalFilter, $allowed_medical)) {
    $medicalFilter = '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,
      s.specialization_id,
      sp.specialization_name_ar AS specialization_name,
      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
    LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_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 10
  ";
  $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,
      s.specialization_id,
      sp.specialization_name_ar AS specialization_name,
      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
    LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_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 10
  ";
  $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 - مع التحقق الآمن من SQL Injection
$colleges_sql = "SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name";
$colleges_stmt = $mysqli1->prepare($colleges_sql);
$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_sql = "SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name";
    $programs_stmt = $mysqli1->prepare($programs_sql);
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
}

// Get specializations based on selected college, section, and program
$specializations = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $spec_where = "deleted_at IS NULL";
    $spec_params = [];
    $spec_types = "";
    
    if ($filter_section_id && !empty($filter_section_id)) {
        $spec_where .= " AND section_id = ?";
        $spec_types .= "i";
        $spec_params[] = $filter_section_id;
    }
    
    if ($filter_program_id && !empty($filter_program_id)) {
        $spec_where .= " AND program_id = ?";
        $spec_types .= "i";
        $spec_params[] = $filter_program_id;
    }
    
    $spec_where .= " AND college_id = ?";
    $spec_types .= "i";
    $spec_params[] = $filter_college_id;
    
    $specializations_sql = "
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE {$spec_where} 
        ORDER BY specialization_name_ar
    ";
    
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    if ($spec_types) {
        $specializations_stmt->bind_param($spec_types, ...$spec_params);
    }
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
}

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

/* ---------- Status filter for section table ---------- */
$statusFilter = $_GET['status'] ?? 'all';
$allowed_status = ['all', 'pending', 'accepted', 'rejected'];
if (!in_array($statusFilter, $allowed_status)) {
    $statusFilter = '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;
  });
}

/* ---------- 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', 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;
  }
  
  /* Enhanced Reports CSS */
  .nav-tabs {
    border-bottom: 2px solid #e9ecef;
    margin-bottom: 1.5rem;
  }
  
  .nav-tabs .nav-link {
    border: none;
    color: #6c757d;
    font-weight: 600;
    padding: 0.75rem 1.25rem;
    position: relative;
    margin-bottom: -2px;
  }
  
  .nav-tabs .nav-link:hover {
    color: #495057;
    background-color: rgba(0,0,0,.02);
  }
  
  .nav-tabs .nav-link.active {
    color: #3b82f6;
    background-color: transparent;
    border: none;
    border-bottom: 3px solid #3b82f6;
  }
  
  .report-card {
    transition: all 0.3s ease;
    height: 100%;
    border-radius: 12px;
    overflow: hidden;
  }
  
  .report-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(0,0,0,0.1) !important;
  }
  
  .report-icon {
    transition: all 0.3s ease;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
  }
  
  .report-card:hover .report-icon {
    transform: scale(1.1);
  }
  
  .hover-lift {
    transition: transform 0.2s ease;
  }
  
  .hover-lift:hover {
    transform: translateY(-3px);
  }
  
  .bg-purple {
    background-color: #8b5cf6 !important;
  }
  
  .bg-teal {
    background-color: #14b8a6 !important;
  }
  
  .bg-indigo {
    background-color: #4f46e5 !important;
  }
  
  .bg-pink {
    background-color: #ec4899 !important;
  }
  
  .text-purple {
    color: #8b5cf6 !important;
  }
  
  .text-teal {
    color: #14b8a6 !important;
  }
  
  .text-indigo {
    color: #4f46e5 !important;
  }
  
  .text-pink {
    color: #ec4899 !important;
  }
  
  .bg-opacity-10 {
    background-color: rgba(var(--bs-primary-rgb), 0.1) !important;
  }
  
  .bg-success.bg-opacity-10 {
    background-color: rgba(var(--bs-success-rgb), 0.1) !important;
  }
  
  .bg-danger.bg-opacity-10 {
    background-color: rgba(var(--bs-danger-rgb), 0.1) !important;
  }
  
  .bg-warning.bg-opacity-10 {
    background-color: rgba(var(--bs-warning-rgb), 0.1) !important;
  }
  
  .bg-info.bg-opacity-10 {
    background-color: rgba(var(--bs-info-rgb), 0.1) !important;
  }
  
  .bg-purple.bg-opacity-10 {
    background-color: rgba(139, 92, 246, 0.1) !important;
  }
  
  .bg-teal.bg-opacity-10 {
    background-color: rgba(20, 184, 166, 0.1) !important;
  }
  
  .bg-indigo.bg-opacity-10 {
    background-color: rgba(79, 70, 229, 0.1) !important;
  }
  
  .bg-pink.bg-opacity-10 {
    background-color: rgba(236, 72, 153, 0.1) !important;
  }
  
  /* Progress bar styles */
  .progress {
    background-color: #e9ecef;
    border-radius: 10px;
    overflow: hidden;
  }
  
  .progress-bar {
    border-radius: 10px;
    transition: width 0.6s ease;
  }
  
  /* Badge styles */
  .badge {
    font-weight: 500;
    padding: 0.35em 0.65em;
    font-size: 0.75em;
  }
  
  /* Card body padding */
  .card-body {
    padding: 1.25rem;
  }
  
  /* Reports grid */
  .reports-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1rem;
  }
  
  /* Quick stats */
  .quick-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 0.75rem;
    margin-bottom: 1.5rem;
  }
  
  .stat-card {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 1rem;
    text-align: center;
    border: 1px solid #e9ecef;
  }
  
  .stat-number {
    font-size: 1.5rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
  }
  
  .stat-label {
    font-size: 0.85rem;
    color: #6c757d;
  }
  
  
  
  /************************       جديد *********************************/
  
  
  /* تحسينات التبويبات - تقارير ذكية وجذابة */

/* تنسيقات التبويبات الرئيسية */
.reports-tabs-modern {
    border-bottom: none;
    margin-bottom: 1.8rem;
    gap: 0.5rem;
    flex-wrap: wrap;
    background: #f8fafc;
    padding: 0.6rem;
    border-radius: 50px;
    display: inline-flex;
    width: auto;
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.02);
}

.reports-tabs-modern .nav-item {
    margin: 0;
    flex: 0 0 auto;
}

.reports-tabs-modern .nav-link {
    border: none;
    color: #475569;
    font-weight: 600;
    padding: 0.8rem 1.5rem;
    border-radius: 40px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    background: transparent;
    display: flex;
    align-items: center;
    gap: 0.6rem;
    font-size: 0.95rem;
    position: relative;
    overflow: hidden;
}

.reports-tabs-modern .nav-link i {
    font-size: 1.1rem;
    transition: all 0.3s ease;
    color: #64748b;
}

.reports-tabs-modern .nav-link:hover {
    background: rgba(59, 130, 246, 0.05);
    color: #1e293b;
    transform: translateY(-2px);
}

.reports-tabs-modern .nav-link:hover i {
    color: #3b82f6;
    transform: scale(1.1);
}

.reports-tabs-modern .nav-link.active {
    background: linear-gradient(135deg, #3b82f6, #8b5cf6);
    color: white;
    box-shadow: 0 8px 16px -4px rgba(59, 130, 246, 0.3);
}

.reports-tabs-modern .nav-link.active i {
    color: white;
    transform: scale(1.05);
}

/* عداد التبويب */
.tab-badge {
    background: rgba(0,0,0,0.08);
    color: inherit;
    padding: 0.2rem 0.6rem;
    border-radius: 30px;
    font-size: 0.7rem;
    font-weight: 600;
    margin-right: 0.3rem;
    transition: all 0.3s ease;
}

.reports-tabs-modern .nav-link.active .tab-badge {
    background: rgba(255,255,255,0.2);
    color: white;
}

/* تنسيقات البطاقات داخل التبويبات */
.tab-pane-modern {
    animation: fadeSlideIn 0.4s ease forwards;
}

@keyframes fadeSlideIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* تنسيقات مجموعة البطاقات */
.reports-grid-modern {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1rem;
    margin-top: 1rem;
}

/* تنسيقات البطاقة المحسنة */
.report-card-enhanced {
    background: white;
    border-radius: 20px;
    padding: 1.2rem;
    box-shadow: 0 4px 12px rgba(0,0,0,0.03);
    border: 1px solid rgba(0,0,0,0.05);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.report-card-enhanced::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 15px;
    background: linear-gradient(90deg, var(--card-primary), var(--card-secondary));
    opacity: 0.8;
}

.report-card-enhanced:hover {
    transform: translateY(-4px);
    box-shadow: 0 20px 30px -8px rgba(0,0,0,0.15);
    border-color: rgba(var(--card-rgb), 0.2);
}

.report-card-enhanced .card-header-custom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1rem;
}

.report-card-enhanced .card-icon {
    width: 48px;
    height: 48px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    background: rgba(var(--card-rgb), 0.12);
    color: rgb(var(--card-rgb));
    transition: all 0.3s ease;
}

.report-card-enhanced:hover .card-icon {
    transform: scale(1.1) rotate(5deg);
    background: rgb(var(--card-rgb));
    color: white;
}

.report-card-enhanced .card-badge {
    background: rgba(0,0,0,0.03);
    padding: 0.25rem 0.8rem;
    border-radius: 30px;
    font-size: 0.7rem;
    color: #64748b;
    border: 1px solid rgba(0,0,0,0.05);
    font-weight: 600;
}

.report-card-enhanced .card-title {
    font-size: 1rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.3rem;
}

.report-card-enhanced .card-description {
    font-size: 0.8rem;
    color: #64748b;
    margin-bottom: 1rem;
    line-height: 1.4;
}

.report-card-enhanced .card-stats {
    margin-top: auto;
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    padding-top: 0.8rem;
    border-top: 1px dashed rgba(0,0,0,0.08);
}

.report-card-enhanced .stat-number {
    font-size: 1.4rem;
    font-weight: 800;
    color: #0f172a;
    line-height: 1;
}

.report-card-enhanced .stat-label {
    font-size: 0.7rem;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.report-card-enhanced .card-link {
    text-decoration: none;
    color: inherit;
    display: flex;
    flex-direction: column;
    height: 100%;
}

/* ألوان البطاقات */
:root {
    --card-rgb: 59, 130, 246; /* أزرق افتراضي */
    --card-primary: #3b82f6;
    --card-secondary: #8b5cf6;
}

.card-blue { --card-rgb: 59, 130, 246; --card-primary: #3b82f6; --card-secondary: #60a5fa; }
.card-green { --card-rgb: 16, 185, 129; --card-primary: #10b981; --card-secondary: #34d399; }
.card-red { --card-rgb: 239, 68, 68; --card-primary: #ef4444; --card-secondary: #f87171; }
.card-yellow { --card-rgb: 245, 158, 11; --card-primary: #f59e0b; --card-secondary: #fbbf24; }
.card-purple { --card-rgb: 139, 92, 246; --card-primary: #8b5cf6; --card-secondary: #a78bfa; }
.card-teal { --card-rgb: 20, 184, 166; --card-primary: #14b8a6; --card-secondary: #2dd4bf; }
.card-pink { --card-rgb: 236, 72, 153; --card-primary: #ec4899; --card-secondary: #f472b6; }
.card-indigo { --card-rgb: 79, 70, 229; --card-primary: #4f46e5; --card-secondary: #6366f1; }

/* تنسيقات متجاوبة */
@media (max-width: 768px) {
    .reports-tabs-modern {
        padding: 0.4rem;
        border-radius: 40px;
    }
    
    .reports-tabs-modern .nav-link {
        padding: 0.5rem 1rem;
        font-size: 0.85rem;
    }
    
    .reports-tabs-modern .nav-link i {
        font-size: 0.9rem;
    }
    
    .reports-grid-modern {
        grid-template-columns: 1fr;
    }
    
    .report-card-enhanced .stat-number {
        font-size: 1.2rem;
    }
}
  
  /* ===== تحسينات بطاقات KPIs ===== */
#kpi-cards {
    margin-bottom: 1.5rem;
}

.kpi-card {
    background: #fff;
    border-radius: 24px;
    padding: 1.25rem 1.25rem 0.75rem 1.25rem;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.02);
    border: 1px solid rgba(0, 0, 0, 0.03);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.kpi-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 20px;
    background: linear-gradient(90deg, var(--card-primary), var(--card-secondary));
    opacity: 0.8;
}

.kpi-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 20px 30px -10px rgba(0, 0, 0, 0.15);
    border-color: rgba(var(--card-rgb), 0.2);
}

/* ألوان البطاقات */
.kpi-card.total {
    --card-rgb: 59, 130, 246;
    --card-primary: #3b82f6;
    --card-secondary: #60a5fa;
}

.kpi-card.accepted {
    --card-rgb: 16, 185, 129;
    --card-primary: #10b981;
    --card-secondary: #34d399;
}

.kpi-card.pending {
    --card-rgb: 107, 114, 128;
    --card-primary: #6b7280;
    --card-secondary: #9ca3af;
}

.kpi-card.rejected {
    --card-rgb: 239, 68, 68;
    --card-primary: #ef4444;
    --card-secondary: #f87171;
}

/* المحتوى الداخلي */
.kpi-card-inner {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 0.75rem;
}

/* أيقونة البطاقة */
.kpi-icon-wrapper {
    flex-shrink: 0;
}

.kpi-icon {
    width: 56px;
    height: 56px;
    border-radius: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    background: rgba(var(--card-rgb), 0.12);
    color: rgb(var(--card-rgb));
    transition: all 0.3s ease;
}

.kpi-card:hover .kpi-icon {
    transform: scale(1.1) rotate(5deg);
    background: rgb(var(--card-rgb));
    color: white;
}

/* محتوى الأرقام */
.kpi-content {
    flex-grow: 1;
}

.kpi-value {
    font-size: 2.2rem;
    font-weight: 800;
    line-height: 1.2;
    color: #1e293b;
    margin-bottom: 0.15rem;
}

.kpi-label {
    font-size: 0.9rem;
    color: #64748b;
    font-weight: 500;
}

/* مؤشر الاتجاه */
.kpi-trend {
    margin-right: auto;
}

.trend-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.35rem 0.75rem;
    border-radius: 30px;
    font-size: 0.75rem;
    font-weight: 600;
    background: rgba(0, 0, 0, 0.03);
    color: #475569;
    white-space: nowrap;
}

.trend-badge.positive {
    background: rgba(16, 185, 129, 0.1);
    color: #065f46;
}

.trend-badge.neutral {
    background: rgba(107, 114, 128, 0.1);
    color: #4b5563;
}

.trend-badge.negative {
    background: rgba(239, 68, 68, 0.1);
    color: #991b1b;
}

/* تذييل البطاقة */
.kpi-footer {
    margin-top: auto;
    padding-top: 0.75rem;
    border-top: 2px solid rgba(0, 0, 0, 0.05);
    
}

.kpi-footer-text {
    font-size: 0.7rem;
    color: #94a3b8;
    display: flex;
    align-items: center;
}

.kpi-footer-text i {
    font-size: 0.6rem;
    color: #94a3b8;
}

/* تأثير hover على التذييل */
.kpi-card:hover .kpi-footer-text {
    color: #64748b;
}

.kpi-card:hover .kpi-footer-text i {
    color: rgb(var(--card-rgb));
}

/* تنسيقات متجاوبة */
@media (max-width: 768px) {
    .kpi-value {
        font-size: 1.8rem;
    }
    
    .kpi-icon {
        width: 48px;
        height: 48px;
        font-size: 1.5rem;
    }
    
    .trend-badge {
        padding: 0.25rem 0.5rem;
        font-size: 0.7rem;
    }
}

@media (max-width: 576px) {
    .kpi-card-inner {
        flex-wrap: wrap;
    }
    
    .kpi-trend {
        margin-right: 0;
        width: 100%;
        text-align: left;
    }
}
  
</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; ?>
    </div>
    <div class="d-flex gap-2">
    <!-- Logout Button -->
    <a href="admin_logout.php" class="btn" style="background: linear-gradient(135deg, #0056B3, #003366); border: none; border-radius: 10px; padding: 8px 20px; color: white; font-weight: 500;">
        <i class="fas fa-sign-out-alt ms-2"></i>
        تسجيل الخروج
    </a>
</div>
  </div>

  <!-- KPIs -->
<!-- KPIs - بطاقات محسنة 2026 -->
<div class="row g-3 mb-4" id="kpi-cards">
    <!-- بطاقة إجمالي الطلاب -->
    <div class="col-lg-3 col-md-6">
        <div class="kpi-card total">
            <div class="kpi-card-inner">
                <div class="kpi-icon-wrapper">
                    <div class="kpi-icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
                <div class="kpi-content">
                    <div class="kpi-value"><?= number_format($kpi['total']) ?></div>
                    <div class="kpi-label">إجمالي الطلاب</div>
                </div>
                <div class="kpi-trend">
                    <span class="trend-badge">
                        <i class="fas fa-arrow-up"></i> +12%
                    </span>
                </div>
            </div>
            <div class="kpi-footer">
                <span class="kpi-footer-text">
                    <i class="fas fa-clock me-1"></i> آخر تحديث: الآن
                </span>
            </div>
        </div>
    </div>

    <!-- بطاقة المقبولين -->
    <div class="col-lg-3 col-md-6">
        <div class="kpi-card accepted">
            <div class="kpi-card-inner">
                <div class="kpi-icon-wrapper">
                    <div class="kpi-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
                <div class="kpi-content">
                    <div class="kpi-value"><?= number_format($kpi['st_accepted']) ?></div>
                    <div class="kpi-label">تم قبولهم</div>
                </div>
                <div class="kpi-trend">
                    <span class="trend-badge positive">
                        <i class="fas fa-arrow-up"></i> +5%
                    </span>
                </div>
            </div>
            <div class="kpi-footer">
                <span class="kpi-footer-text">
                    <i class="fas fa-percentage me-1"></i> 
                    <?= $kpi['total'] > 0 ? number_format(($kpi['st_accepted'] / $kpi['total']) * 100, 1) : 0 ?>% من الإجمالي
                </span>
            </div>
        </div>
    </div>

    <!-- بطاقة قيد الانتظار -->
    <div class="col-lg-3 col-md-6">
        <div class="kpi-card pending">
            <div class="kpi-card-inner">
                <div class="kpi-icon-wrapper">
                    <div class="kpi-icon">
                        <i class="fas fa-hourglass-half"></i>
                    </div>
                </div>
                <div class="kpi-content">
                    <div class="kpi-value"><?= number_format($kpi['st_pending']) ?></div>
                    <div class="kpi-label">قيد الانتظار</div>
                </div>
                <div class="kpi-trend">
                    <span class="trend-badge neutral">
                        <i class="fas fa-minus"></i> 0%
                    </span>
                </div>
            </div>
            <div class="kpi-footer">
                <span class="kpi-footer-text">
                    <i class="fas fa-clock me-1"></i> 
                    <?= $kpi['total'] > 0 ? number_format(($kpi['st_pending'] / $kpi['total']) * 100, 1) : 0 ?>% في الانتظار
                </span>
            </div>
        </div>
    </div>

    <!-- بطاقة المرفوضين -->
    <div class="col-lg-3 col-md-6">
        <div class="kpi-card rejected">
            <div class="kpi-card-inner">
                <div class="kpi-icon-wrapper">
                    <div class="kpi-icon">
                        <i class="fas fa-times-circle"></i>
                    </div>
                </div>
                <div class="kpi-content">
                    <div class="kpi-value"><?= number_format($kpi['st_rejected']) ?></div>
                    <div class="kpi-label">مرفوضين</div>
                </div>
                <div class="kpi-trend">
                    <span class="trend-badge negative">
                        <i class="fas fa-arrow-down"></i> -2%
                    </span>
                </div>
            </div>
            <div class="kpi-footer">
                <span class="kpi-footer-text">
                    <i class="fas fa-exclamation-circle me-1"></i> 
                    <?= $kpi['total'] > 0 ? number_format(($kpi['st_rejected'] / $kpi['total']) * 100, 1) : 0 ?>% مرفوض
                </span>
            </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 - FIXED: Using med_wait instead of st_pending
  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" dir="rtl">
    <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-2 col-md-4">
            <div class="form-group">
              <label class="form-label fw-semibold text-muted mb-2">
                <i class="fas fa-university me-1"></i>
                الكلية
              </label>
              <div class="input-group input-group-sm">
                <select class="form-control border-end-0" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                  <option value="">جميع الكليات</option>
                  <?php foreach ($colleges as $college): ?>
                    <?php 
                    // Don't show college filter if user has scope restriction
                    if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                      continue;
                    }
                    ?>
                    <option value="<?= $college['id'] ?>" <?= $filter_college_id == $college['id'] ? 'selected' : '' ?>>
                      <?= e($college['name']) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-building"></i>
                </span>
              </div>
            </div>
          </div>
          
          <!-- Section Filter (Dependent on College) -->
          <div class="col-lg-2 col-md-4">
            <div class="form-group">
              <label class="form-label fw-semibold text-muted mb-2">
                <i class="fas fa-layer-group me-1"></i>
                القسم
              </label>
              <div class="input-group input-group-sm position-relative">
                <select class="form-control border-end-0" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?>>
                  <option value="">جميع الأقسام</option>
                  <?php if ($filter_college_id && !empty($sections)): ?>
                    <?php foreach ($sections as $section): ?>
                      <option value="<?= $section['id'] ?>" <?= $filter_section_id == $section['id'] ? 'selected' : '' ?>>
                        <?= e($section['name']) ?>
                      </option>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-building"></i>
                </span>
                <div 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-2 col-md-4">
            <div class="form-group">
              <label class="form-label fw-semibold text-muted mb-2">
                <i class="fas fa-graduation-cap me-1"></i>
                البرنامج
              </label>
              <div class="input-group input-group-sm">
                <select class="form-control border-end-0" name="filter_program" id="filter_program" onchange="loadSpecializations()">
                  <option value="">جميع البرامج</option>
                  <?php foreach ($programs as $program): ?>
                    <option value="<?= $program['id'] ?>" <?= $filter_program_id == $program['id'] ? 'selected' : '' ?>>
                      <?= e($program['name']) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-book"></i>
                </span>
              </div>
            </div>
          </div>
          
          <!-- Specialization Filter - NEW -->
          <div class="col-lg-2 col-md-4">
            <div class="form-group">
              <label class="form-label fw-semibold text-muted mb-2">
                <i class="fas fa-microscope me-1"></i>
                التخصص
              </label>
              <div class="input-group input-group-sm">
                <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization">
                  <option value="">جميع التخصصات</option>
                  <?php if (!empty($specializations)): ?>
                    <?php foreach ($specializations as $spec): ?>
                      <option value="<?= $spec['specialization_id'] ?>" <?= $filter_specialization_id == $spec['specialization_id'] ? 'selected' : '' ?>>
                        <?= e($spec['specialization_name_ar']) ?>
                      </option>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-microscope"></i>
                </span>
              </div>
              <div class="ajax-loading" id="specLoading" style="display: none;">
                <i class="fas fa-spinner fa-spin"></i>
              </div>
            </div>
          </div>
          
          <!-- Batch Filter -->
          <div class="col-lg-2 col-md-4">
            <div class="form-group">
              <label class="form-label fw-semibold text-muted mb-2">
                <i class="fas fa-users me-1"></i>
                الدفعة
              </label>
              <div class="input-group input-group-sm">
                <select class="form-control border-end-0" name="filter_batch">
                  <option value="">جميع الدفعات</option>
                  <?php foreach ($batches as $batch): ?>
                    <option value="<?= $batch['id'] ?>" <?= $filter_batch_id == $batch['id'] ? 'selected' : '' ?>>
                      <?= e($batch['value']) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <span class="input-group-text bg-light border-start-0">
                  <i class="fas fa-calendar-alt"></i>
                </span>
              </div>
            </div>
          </div>
          
          <!-- Action Buttons -->
          <div class="col-lg-2 col-md-4">
            <div class="d-flex gap-2 pt-2">
              <button type="submit" class="btn btn-primary btn-sm px-3 w-100">
                <i class="fas fa-filter me-1"></i>
                تطبيق
              </button>
              <a href="committee_dashboard.php" class="btn btn-outline-secondary btn-sm px-3" title="إعادة تعيين">
                <i class="fas fa-sync-alt 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_specialization_id && !empty($filter_specialization_id)): 
              $hasActiveFilters = true;
              $selected_spec = null;
              foreach ($specializations as $spec) {
                if ($spec['specialization_id'] == $filter_specialization_id) {
                  $selected_spec = $spec;
                  break;
                }
              }
            ?>
              <div class="summary-item">
                <span class="summary-label">التخصص:</span>
                <span class="summary-value">
                  <span class="badge bg-purple bg-opacity-10 text-purple">
                    <?= e($selected_spec['specialization_name_ar'] ?? '') ?>
                  </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 " dir="rtl">
    <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 <?= $statusFilter === 'all' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            الكل
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'pending'])) ?>" 
             class="btn btn-sm <?= $statusFilter === 'pending' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            قيد الانتظار
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'accepted'])) ?>" 
             class="btn btn-sm <?= $statusFilter === 'accepted' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            المقبولين
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['status' => 'rejected'])) ?>" 
             class="btn btn-sm <?= $statusFilter === 'rejected' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            المرفوضين
          </a>
        </div>
      </div>
    </div>

    <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>
  
  <!-- التقارير والإحصائيات - تبويبات وبطاقات محسنة 2026 -->
<div class="dash-card mb-4" dir="rtl">
    <div class="d-flex align-items-center mb-4">
        <div class="filter-icon me-2" style="background: linear-gradient(135deg, #6366f1, #8b5cf6);">
            <i class="fas fa-chart-pie"></i>
        </div>
        <div>
            <h6 class="fw-bold mb-0 text-dark">التقارير والإحصائيات</h6>
            <p class="text-muted small mb-0">تصفح التقارير حسب الفئة</p>
        </div>
        <div class="ms-auto">
            <span class="badge bg-light text-dark border px-3 py-2">
                <i class="fas fa-sync-alt me-1 fa-spin"></i>
                تحديث لحظي
            </span>
        </div>
    </div>

    <!-- تبويبات محسنة بشكل دائري (Pills) -->
    <ul class="nav reports-tabs-modern" id="reportsEnhancedTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="all-tab-enhanced" data-bs-toggle="tab" data-bs-target="#all-enhanced" type="button" role="tab">
                <i class="fas fa-th-large"></i>
                <span>الاكثر أهمية</span>
                <span class="tab-badge">8</span>
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="registration-tab-enhanced" data-bs-toggle="tab" data-bs-target="#registration-enhanced" type="button" role="tab">
                <i class="fas fa-user-graduate"></i>
                <span>القيد والتسجيل</span>
                <span class="tab-badge">4</span>
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="medical-tab-enhanced" data-bs-toggle="tab" data-bs-target="#medical-enhanced" type="button" role="tab">
                <i class="fas fa-heartbeat"></i>
                <span>التقارير الطبية</span>
                <span class="tab-badge">4</span>
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="attendance-tab-enhanced" data-bs-toggle="tab" data-bs-target="#attendance-enhanced" type="button" role="tab">
                <i class="fas fa-calendar-check"></i>
                <span>الحضور</span>
                <span class="tab-badge">2</span>
            </button>
        </li>
    </ul>

    <!-- محتوى التبويبات المحسن -->
    <div class="tab-content tab-pane-modern" id="reportsEnhancedContent">
        
        <!-- تبويب الكل -->
        <div class="tab-pane fade show active" id="all-enhanced" role="tabpanel">
            <div class="reports-grid-modern">
                
                
                  <!--  :  إدارة تسجيلات الطلاب  -->
                <div class="report-card-enhanced card-pink">
                    <a href="registration.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-file-certificate"></i></div>
                            <span class="card-badge">تسجيل</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">إدارة تسجيلات الطلاب  </h6>
                            <p class="card-description"> إدارة تسجيلات الطلاب والإجراءات  </p>
                        </div>
                        <div class="card-stats">
                          <span class="stat-number"><?= number_format($kpi['total'] ?? 0) ?></span>
                            <span class="stat-label">طالب</span>
                        </div>
                    </a>
                </div>
                
                <!-- بطاقة 1: شهادات القيد - أزرق -->
                <div class="report-card-enhanced card-blue">
                    <a href="registration_certificate_dashboard.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-file-certificate"></i>
                            </div>
                            <span class="card-badge">قيد</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">شهادات القيد</h6>
                            <p class="card-description">إدارة وتحرير شهادات القيد للطلاب</p>
                        </div>
                        <div class="card-stats">
                             <span class="stat-number">-</span>
                             <span class="stat-label">-</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 2: قائمة الطلاب الذين أكملوا سداد الرسوم - أخضر -->
                <div class="report-card-enhanced card-green">
                    <a href="reports/registered_students.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <span class="card-badge">مسجل</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">قائمة الطلاب الذين أكملوا سداد الرسوم</h6>
                            <p class="card-description">جميع الرسوم مسددة ومكتملة</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['fully_registered'] ?? 0) ?></span>
                            <span class="stat-label">مسجل كامل</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 3: الطلاب غير المسجلين - أحمر -->
                <div class="report-card-enhanced card-red">
                    <a href="reports/unregistered_students.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-times-circle"></i>
                            </div>
                            <span class="card-badge">غير مسجل</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">الطلاب غير المسجلين</h6>
                            <p class="card-description">لم يسددوا أي رسوم بعد</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['unregistered'] ?? 0) ?></span>
                            <span class="stat-label">غير مسجل</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 4: قائمة الطلاب الذين لم يكملوا سداد الرسوم - أصفر -->
                <div class="report-card-enhanced card-yellow">
                    <a href="reports/partially_registered.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-exclamation-circle"></i>
                            </div>
                            <span class="card-badge">جزئي</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">قائمة الطلاب الذين لم يكملوا سداد الرسوم</h6>
                            <p class="card-description">سددوا بعض الرسوم فقط</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['partially_registered'] ?? 0) ?></span>
                            <span class="stat-label">مسجل جزئي</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 5: شهادات الأرانيك - بنفسجي -->
                <div class="report-card-enhanced card-purple">
                    <a href="medical_certificate_dashboard.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-file-medical-alt"></i>
                            </div>
                            <span class="card-badge">طبي</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">شهادات الأرانيك المرضية</h6>
                            <p class="card-description">إصدار الأرانيك المرضية</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number">-</span>
                            <span class="stat-label">-</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 6: الطلاب اللائقين - أخضر (إحصائيات) -->
                <div class="report-card-enhanced card-green">
                    <div class="card-link" style="cursor: default;">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-heartbeat"></i>
                            </div>
                            <span class="card-badge">لائق</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">الطلاب اللائقين طبياً</h6>
                            <p class="card-description">حاصلين على لياقة طبية</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['med_fit'] ?? 0) ?></span>
                            <span class="stat-label">لائق</span>
                        </div>
                    </div>
                </div>

                <!-- بطاقة 7: الطلاب غير اللائقين - أحمر -->
                <div class="report-card-enhanced card-red">
                    <div class="card-link" style="cursor: default;">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-procedures"></i>
                            </div>
                            <span class="card-badge">غير لائق</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">الطلاب غير اللائقين</h6>
                            <p class="card-description">بحاجة لمتابعة طبية</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['med_unfit'] ?? 0) ?></span>
                            <span class="stat-label">غير لائق</span>
                        </div>
                    </div>
                </div>

                <!-- بطاقة 8: بانتظار الفحص - فيروزي -->
                <div class="report-card-enhanced card-teal">
                    <div class="card-link" style="cursor: default;">
                        <div class="card-header-custom">
                            <div class="card-icon">
                                <i class="fas fa-clock"></i>
                            </div>
                            <span class="card-badge">انتظار</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">بانتظار الفحص الطبي</h6>
                            <p class="card-description">لم يكملوا الفحص الطبي</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['med_wait'] ?? 0) ?></span>
                            <span class="stat-label">بانتظار</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- تبويب القيد والتسجيل -->
        <div class="tab-pane fade" id="registration-enhanced" role="tabpanel">
            <div class="reports-grid-modern">
                
                          <!--  :  إدارة تسجيلات الطلاب  -->
                <div class="report-card-enhanced card-pink">
                    <a href="registration.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-file-certificate"></i></div>
                            <span class="card-badge">تسجيل</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">إدارة تسجيلات الطلاب  </h6>
                            <p class="card-description"> إدارة تسجيلات الطلاب والإجراءات  </p>
                        </div>
                        <div class="card-stats">
                          <span class="stat-number"><?= number_format($kpi['total'] ?? 0) ?></span>
                            <span class="stat-label">طالب</span>
                        </div>
                    </a>
                </div>
                
                <!-- بطاقة 1: شهادات القيد -->
                <div class="report-card-enhanced card-blue">
                    <a href="registration_certificate_dashboard.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-file-certificate"></i></div>
                            <span class="card-badge">قيد</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">شهادات القيد</h6>
                            <p class="card-description">إدارة وتحرير شهادات القيد</p>
                        </div>
                        <div class="card-stats">
                              <span class="stat-number">-</span>
                            <span class="stat-label">-</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 2: قائمة الطلاب الذين أكملوا سداد الرسوم -->
                <div class="report-card-enhanced card-green">
                    <a href="reports/registered_students.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-check-circle"></i></div>
                            <span class="card-badge">مسجل</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">قائمة الطلاب الذين أكملوا سداد الرسوم</h6>
                            <p class="card-description">جميع الرسوم مسددة ومكتملة</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['fully_registered'] ?? 0) ?></span>
                            <span class="stat-label">مسجل كامل</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 3: الطلاب غير المسجلين -->
                <div class="report-card-enhanced card-red">
                    <a href="reports/unregistered_students.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-times-circle"></i></div>
                            <span class="card-badge">غير مسجل</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">الطلاب غير المسجلين</h6>
                            <p class="card-description">لم يسددوا أي رسوم</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['unregistered'] ?? 0) ?></span>
                            <span class="stat-label">غير مسجل</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 4: قائمة الطلاب الذين لم يكملوا سداد الرسوم -->
                <div class="report-card-enhanced card-yellow">
                    <a href="reports/partially_registered.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-exclamation-circle"></i></div>
                            <span class="card-badge">جزئي</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">قائمة الطلاب الذين لم يكملوا سداد الرسوم</h6>
                            <p class="card-description">سددوا بعض الرسوم فقط</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['partially_registered'] ?? 0) ?></span>
                            <span class="stat-label">مسجل جزئي</span>
                        </div>
                    </a>
                </div>
            </div>
        </div>

        <!-- تبويب التقارير الطبية -->
        <div class="tab-pane fade" id="medical-enhanced" role="tabpanel">
            <div class="reports-grid-modern">
                <!-- بطاقة 1: شهادات الأرانيك -->
                <div class="report-card-enhanced card-purple">
                    <a href="medical_certificate_dashboard.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-file-medical-alt"></i></div>
                            <span class="card-badge">طبي</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">شهادات الأرانيك</h6>
                            <p class="card-description">إصدار الأرانيك المرضية</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number">-</span>
                            <span class="stat-label">-</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 2: الطلاب اللائقين -->
                <div class="report-card-enhanced card-green">
                    <div class="card-link" style="cursor: default;">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-heartbeat"></i></div>
                            <span class="card-badge">لائق</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">الطلاب اللائقين</h6>
                            <p class="card-description">حاصلين على لياقة طبية</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['med_fit'] ?? 0) ?></span>
                            <span class="stat-label">لائق</span>
                        </div>
                    </div>
                </div>

                <!-- بطاقة 3: الطلاب غير اللائقين -->
                <div class="report-card-enhanced card-red">
                    <div class="card-link" style="cursor: default;">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-procedures"></i></div>
                            <span class="card-badge">غير لائق</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">غير اللائقين</h6>
                            <p class="card-description">بحاجة لمتابعة طبية</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['med_unfit'] ?? 0) ?></span>
                            <span class="stat-label">غير لائق</span>
                        </div>
                    </div>
                </div>

                <!-- بطاقة 4: بانتظار الفحص -->
                <div class="report-card-enhanced card-teal">
                    <div class="card-link" style="cursor: default;">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-clock"></i></div>
                            <span class="card-badge">انتظار</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">بانتظار الفحص</h6>
                            <p class="card-description">لم يكملوا الفحص الطبي</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number"><?= number_format($kpi['med_wait'] ?? 0) ?></span>
                            <span class="stat-label">بانتظار</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- تبويب الحضور -->
        <div class="tab-pane fade" id="attendance-enhanced" role="tabpanel">
            <div class="reports-grid-modern">
                <!-- بطاقة 1: حضور المحاضرات -->
                <div class="report-card-enhanced card-indigo">
                    <a href="reports/lecture_attendance.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-chalkboard-teacher"></i></div>
                            <span class="card-badge">محاضرات</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">حضور المحاضرات</h6>
                            <p class="card-description">سجل الحضور اليومي للطلاب</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number">-</span>
                            <span class="stat-label">-</span>
                        </div>
                    </a>
                </div>

                <!-- بطاقة 2: حضور الامتحان -->
                <div class="report-card-enhanced card-pink">
                    <a href="reports/exam_attendance.php" class="card-link">
                        <div class="card-header-custom">
                            <div class="card-icon"><i class="fas fa-file-signature"></i></div>
                            <span class="card-badge">امتحانات</span>
                        </div>
                        <div class="card-content">
                            <h6 class="card-title">حضور الامتحان</h6>
                            <p class="card-description">نتائج وتوقيعات الامتحانات</p>
                        </div>
                        <div class="card-stats">
                            <span class="stat-number">-</span>
                            <span class="stat-label">-</span>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- رسالة عند عدم وجود بيانات -->
    <?php if (empty($kpi['total'])): ?>
    <div class="text-center text-muted py-4">
        <i class="fas fa-chart-line fa-3x mb-3 opacity-25"></i>
        <p>لا توجد إحصائيات لعرضها حالياً</p>
    </div>
    <?php endif; ?>
</div>

<!-- إضافة JavaScript لتفعيل تأثيرات التبويبات -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // تفعيل التبويبات مع تأثيرات إضافية
    const tabs = document.querySelectorAll('.reports-tabs-modern .nav-link');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // إزالة الكلاس النشط من جميع التبويبات
            tabs.forEach(t => t.classList.remove('active'));
            
            // إضافة الكلاس النشط للتبويب المحدد
            this.classList.add('active');
            
            // الحصول على الهدف
            const target = this.getAttribute('data-bs-target');
            
            // إخفاء جميع محتويات التبويبات
            document.querySelectorAll('.tab-pane').forEach(pane => {
                pane.classList.remove('show', 'active');
            });
            
            // إظهار المحتوى المحدد
            const targetPane = document.querySelector(target);
            if (targetPane) {
                targetPane.classList.add('show', 'active');
            }
        });
    });
    
    // تأثير ظهور تدريجي للبطاقات عند التمرير
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -10px 0px'
    };
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);
    
    document.querySelectorAll('.report-card-enhanced').forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        observer.observe(card);
    });
});
</script>
  
  <!-- آخر الطلبات / المكتملين -->
  <div class="dash-card" dir="rtl">
    <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 <?= $medicalFilter === 'all' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            جميع الحالات الطبية
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'fit'])) ?>"
             class="btn btn-sm <?= $medicalFilter === 'fit' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            لائق
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'unfit'])) ?>"
             class="btn btn-sm <?= $medicalFilter === 'unfit' ? 'btn-primary' : 'btn-outline-secondary' ?>">
            غير لائق
          </a>
          <a href="committee_dashboard.php?<?= http_build_query(array_merge($_GET, ['medical'=>'pending'])) ?>"
             class="btn btn-sm <?= $medicalFilter === '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_specialization" value="<?= e($_GET['filter_specialization'] ?? '') ?>">
          <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) || $medicalFilter !== 'all' || !empty($filter_college_id) || !empty($filter_section_id) || !empty($filter_program_id) || !empty($filter_specialization_id) || !empty($filter_batch_id)): ?>
            <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) || $medicalFilter !== 'all' || !empty($filter_college_id) || !empty($filter_section_id) || !empty($filter_program_id) || !empty($filter_specialization_id) || !empty($filter_batch_id)): ?>
      <div class="text-muted small mt-2">
        <?php if (!empty($q)): ?>
          عدد النتائج: <?= number_format(count($recentAccepted)) ?> لـ "<?= e($q) ?>"
        <?php endif; ?>
        <?php if ($medicalFilter !== 'all'): ?>
          <?php if (!empty($q)): ?> | <?php endif; ?>
          التصفية الطبية: 
          <?= e([
            'fit' => 'لائق فقط',
            'unfit' => 'غير لائق فقط', 
            'pending' => 'بانتظار الفحص فقط'
          ][$medicalFilter] ?? '') ?>
        <?php endif; ?>
        <?php if (!empty($filter_college_id) || !empty($filter_section_id) || !empty($filter_program_id) || !empty($filter_specialization_id) || !empty($filter_batch_id)): ?>
          <?php if (!empty($q) || $medicalFilter !== 'all'): ?> | <?php endif; ?>
          التصفية: 
          <?php
          $filter_parts = [];
          if (!empty($filter_college_id)) {
            $college_name = $mysqli1->query("SELECT name FROM colleges WHERE id = " . (int)$filter_college_id)->fetch_assoc()['name'] ?? '';
            $filter_parts[] = "كلية: " . e($college_name);
          }
          if (!empty($filter_section_id)) {
            $section_name = $mysqli1->query("SELECT name FROM sections WHERE id = " . (int)$filter_section_id)->fetch_assoc()['name'] ?? '';
            $filter_parts[] = "قسم: " . e($section_name);
          }
          if (!empty($filter_program_id)) {
            $program_name = $mysqli1->query("SELECT name FROM programs WHERE id = " . (int)$filter_program_id)->fetch_assoc()['name'] ?? '';
            $filter_parts[] = "برنامج: " . e($program_name);
          }
          if (!empty($filter_specialization_id)) {
            $spec_name = $mysqli1->query("SELECT specialization_name_ar FROM specializations WHERE specialization_id = " . (int)$filter_specialization_id)->fetch_assoc()['specialization_name_ar'] ?? '';
            $filter_parts[] = "تخصص: " . e($spec_name);
          }
          if (!empty($filter_batch_id)) {
            $batch_name = $mysqli1->query("SELECT value FROM batches WHERE id = " . (int)$filter_batch_id)->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['section_name'] ?: $r['section_id']) ?></td>
              <td><?= e($r['specialization_name'] ?: '—') ?></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="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
function loadSections(collegeId) {
    const sectionSelect = document.getElementById('filter_section');
    const programSelect = document.getElementById('filter_program');
    const specSelect = document.getElementById('filter_specialization');
    const sectionLoading = document.getElementById('sectionLoading');
    
    // Reset dependent selects
    sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
    programSelect.innerHTML = '<option value="">جميع البرامج</option>';
    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
    
    if (!collegeId || collegeId === '') {
        sectionSelect.disabled = true;
        programSelect.disabled = true;
        specSelect.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']) ? e($_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']) ? e($_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 specialization if exists
    const currentSpec = "<?= isset($_GET['filter_specialization']) ? e($_GET['filter_specialization']) : '' ?>";
    if (currentSpec) {
        const specInput = document.createElement('input');
        specInput.type = 'hidden';
        specInput.name = 'filter_specialization';
        specInput.value = currentSpec;
        form.appendChild(specInput);
    }
    
    // Add current batch if exists
    const currentBatch = "<?= isset($_GET['filter_batch']) ? e($_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']) ? e($_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();
}

// Load specializations based on program and section using AJAX
function loadSpecializations() {
    const programId = document.getElementById('filter_program').value;
    const sectionId = document.getElementById('filter_section').value;
    const collegeId = document.getElementById('filter_college').value;
    const specSelect = document.getElementById('filter_specialization');
    const specLoading = document.getElementById('specLoading');
    
    if (!programId || !sectionId || !collegeId) {
        specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
        return;
    }
    
    // Show loading indicator
    specLoading.style.display = 'block';
    specSelect.disabled = true;
    
    // AJAX request to get specializations
    fetch(`ajax/get_specializations.php?section_id=${sectionId}&program_id=${programId}&college_id=${collegeId}`)
        .then(response => response.json())
        .then(data => {
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            data.forEach(spec => {
                const option = document.createElement('option');
                option.value = spec.specialization_id;
                option.textContent = spec.specialization_name_ar;
                if ("<?= $filter_specialization_id ?>" == spec.specialization_id) {
                    option.selected = true;
                }
                specSelect.appendChild(option);
            });
            specSelect.disabled = false;
            specLoading.style.display = 'none';
        })
        .catch(error => {
            console.error('Error loading specializations:', error);
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            specSelect.disabled = false;
            specLoading.style.display = 'none';
        });
}

// Tab activation script
document.addEventListener('DOMContentLoaded', function() {
  // Initialize tooltips if needed
  var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
  var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
  });
  
  // Tab click animation
  const tabLinks = document.querySelectorAll('.nav-link');
  tabLinks.forEach(link => {
    link.addEventListener('click', function() {
      tabLinks.forEach(l => l.classList.remove('active'));
      this.classList.add('active');
    });
  });
  
  // Trigger specialization load if program and section are selected
  if ("<?= $filter_program_id ?>" && "<?= $filter_section_id ?>" && "<?= $filter_college_id ?>") {
    loadSpecializations();
  }
});
</script>

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