<?php
// medical_list.php — Doctor dashboard with filters/search/sort + flash
// نسخة محسنة مع إضافة المتسلسل والبرنامج وحذف آخر فحص

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 60);
ini_set('memory_limit', '256M');

// بدء قياس وقت التنفيذ
$start_time = microtime(true);

error_log("=== Starting medical_list.php (Fixed Version) ===");

try {
    require 'db.php';
    require 'helpers.php';
    require_doctor();

    $doctor = current_doctor();
    error_log("Doctor loaded: " . ($doctor['name'] ?? 'Unknown'));

} catch (Exception $e) {
    error_log("Error in medical_list.php: " . $e->getMessage());
    die("حدث خطأ في النظام. الرجاء المحاولة لاحقاً.");
}

/* ------- Flash ------- */
$flashOk  = flash_get('ok');
$flashErr = flash_get('err');

/* ------- Inputs with proper sanitization ------- */
$status = $_GET['status'] ?? 'all';
$allowedStatus = ['all','waiting','approved','rejected'];
$status = in_array($status, $allowedStatus, true) ? $status : 'all';

$college_id = isset($_GET['college_id']) && ctype_digit($_GET['college_id']) ? (int)$_GET['college_id'] : null;
$program_id = isset($_GET['program_id']) && ctype_digit($_GET['program_id']) ? (int)$_GET['program_id'] : null;
$q = trim($_GET['q'] ?? '');
$q = htmlspecialchars($q, ENT_QUOTES, 'UTF-8');

$sort = $_GET['sort'] ?? 'id_desc';
$allowedSort = ['id_desc','id_asc','medical_date_desc','medical_date_asc'];
$sort = in_array($sort, $allowedSort, true) ? $sort : 'id_desc';

$semester_filter = $_GET['semester_filter'] ?? 'first'; // افتراضي: الفصل الأول
$limit = 50;
$offset = 0;
$page = isset($_GET['page']) && ctype_digit($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

error_log("Inputs - Status: $status, College ID: $college_id, Program ID: $program_id, Query: $q, Sort: $sort, Semester: $semester_filter, Page: $page");

try {
    /* ------- جلب قائمة الكليات ------- */
    $colleges = [];
    $colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges ORDER BY name");
    if ($colleges_stmt) {
        $colleges_stmt->execute();
        $colleges_result = $colleges_stmt->get_result();
        while ($college = $colleges_result->fetch_assoc()) {
            $colleges[$college['id']] = $college['name'];
        }
        $colleges_stmt->close();
        error_log("Colleges loaded: " . count($colleges));
    }

    /* ------- جلب قائمة البرامج ------- */
    $programs = [];
    $programs_sql = "SELECT id, name FROM programs ORDER BY name";
    $programs_stmt = $mysqli1->prepare($programs_sql);
    if ($programs_stmt) {
        $programs_stmt->execute();
        $programs_result = $programs_stmt->get_result();
        while ($program = $programs_result->fetch_assoc()) {
            $programs[$program['id']] = $program['name'];
        }
        $programs_stmt->close();
        error_log("Programs loaded: " . count($programs));
    }

    /* ------- جلب قائمة الفصول الدراسية ------- */
    $semesters = [];
    $semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters ORDER BY id DESC");
    if ($semesters_stmt) {
        $semesters_stmt->execute();
        $semesters_result = $semesters_stmt->get_result();
        while ($semester = $semesters_result->fetch_assoc()) {
            $semesters[] = $semester;
        }
        $semesters_stmt->close();
        error_log("Semesters loaded: " . count($semesters));
    }

} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
}

/* ============== تحديد معرف الفصل الأول ============== */
$first_semester_id = null;
$selected_semester_id = null;

try {
    // محاولة العثور على الفصل الأول
    $columns_check = $mysqli1->query("SHOW COLUMNS FROM semesters LIKE 'semester_number'");
    if ($columns_check && $columns_check->num_rows > 0) {
        $semester_stmt = $mysqli1->prepare("SELECT id FROM semesters WHERE semester_number = 1 ORDER BY id DESC LIMIT 1");
    } else {
        $semester_stmt = $mysqli1->prepare("SELECT id FROM semesters WHERE name LIKE '%الأول%' OR name LIKE '%first%' ORDER BY id DESC LIMIT 1");
    }
    
    if ($semester_stmt) {
        $semester_stmt->execute();
        $semester_result = $semester_stmt->get_result();
        if ($semester_row = $semester_result->fetch_assoc()) {
            $first_semester_id = (int)$semester_row['id'];
            error_log("First semester ID found: " . $first_semester_id);
        }
        $semester_stmt->close();
    }
    
    if (!$first_semester_id && !empty($semesters)) {
        $first_semester_id = (int)$semesters[0]['id'];
        error_log("Using latest semester as first semester: " . $first_semester_id);
    }
    
    if ($semester_filter === 'first' && $first_semester_id) {
        $selected_semester_id = $first_semester_id;
    } elseif ($semester_filter === 'current' && !empty($semesters)) {
        $selected_semester_id = (int)$semesters[0]['id'];
    }
    
    error_log("Selected semester ID: " . ($selected_semester_id ?? 'none'));
    
} catch (Exception $e) {
    error_log("Error getting semester: " . $e->getMessage());
}

/* ============== استعلام العد ============== */
$counts = [
    'all' => 0,
    'waiting' => 0,
    'approved' => 0,
    'rejected' => 0
];
$total_pages = 1;

try {
    // بناء استعلام العد
    $count_sql = "SELECT COUNT(DISTINCT s.student_id) as total FROM students s";
    $count_params = [];
    $count_types = "";
    
    if ($selected_semester_id) {
        $count_sql = "SELECT COUNT(DISTINCT s.student_id) as total FROM students s INNER JOIN registrations r ON s.student_id = r.student_id WHERE r.semester_id = ?";
        $count_params[] = $selected_semester_id;
        $count_types .= "i";
    }
    
    if ($college_id && $college_id > 0) {
        $count_sql .= (strpos($count_sql, 'WHERE') !== false) ? " AND s.college_id = ?" : " WHERE s.college_id = ?";
        $count_types .= "i";
        $count_params[] = $college_id;
    }
    
    if ($program_id && $program_id > 0) {
        $count_sql .= (strpos($count_sql, 'WHERE') !== false) ? " AND s.program_id = ?" : " WHERE s.program_id = ?";
        $count_types .= "i";
        $count_params[] = $program_id;
    }
    
    // تنفيذ استعلام العد
    if (!empty($count_params)) {
        $count_stmt = $mysqli1->prepare($count_sql);
        if ($count_stmt) {
            $count_stmt->bind_param($count_types, ...$count_params);
            $count_stmt->execute();
            $count_result = $count_stmt->get_result()->fetch_assoc();
            $counts['all'] = (int)($count_result['total'] ?? 0);
            $count_stmt->close();
        }
    } else {
        $count_result = $mysqli1->query("SELECT COUNT(*) as total FROM students");
        $count_row = $count_result->fetch_assoc();
        $counts['all'] = (int)$count_row['total'];
    }
    
    // حساب عدد الصفحات
    $total_pages = ceil($counts['all'] / $limit);
    
    // استعلامات الحالات
    $status_sql = "
        SELECT 
            SUM(CASE WHEN s.medical_status = 'completed' AND s.profile_completed = 1 AND s.medically_fit IS NULL THEN 1 ELSE 0 END) as waiting,
            SUM(CASE WHEN s.medically_fit = 1 AND s.medical_status = 'completed' AND s.profile_completed = 1 THEN 1 ELSE 0 END) as approved,
            SUM(CASE WHEN s.medically_fit = 0 AND s.medical_status = 'completed' AND s.profile_completed = 1 THEN 1 ELSE 0 END) as rejected
        FROM students s
    ";
    
    $status_where = [];
    $status_params = [];
    $status_types = "";
    
    if ($selected_semester_id) {
        $status_sql = "
            SELECT 
                SUM(CASE WHEN s.medical_status = 'completed' AND s.profile_completed = 1 AND s.medically_fit IS NULL THEN 1 ELSE 0 END) as waiting,
                SUM(CASE WHEN s.medically_fit = 1 AND s.medical_status = 'completed' AND s.profile_completed = 1 THEN 1 ELSE 0 END) as approved,
                SUM(CASE WHEN s.medically_fit = 0 AND s.medical_status = 'completed' AND s.profile_completed = 1 THEN 1 ELSE 0 END) as rejected
            FROM students s
            INNER JOIN registrations r ON s.student_id = r.student_id
            WHERE r.semester_id = ?
        ";
        $status_params[] = $selected_semester_id;
        $status_types .= "i";
        
        if ($college_id && $college_id > 0) {
            $status_sql .= " AND s.college_id = ?";
            $status_types .= "i";
            $status_params[] = $college_id;
        }
        
        if ($program_id && $program_id > 0) {
            $status_sql .= " AND s.program_id = ?";
            $status_types .= "i";
            $status_params[] = $program_id;
        }
        
        $status_stmt = $mysqli1->prepare($status_sql);
        if ($status_stmt) {
            $status_stmt->bind_param($status_types, ...$status_params);
            $status_stmt->execute();
            $status_result = $status_stmt->get_result()->fetch_assoc();
            $counts['waiting'] = (int)($status_result['waiting'] ?? 0);
            $counts['approved'] = (int)($status_result['approved'] ?? 0);
            $counts['rejected'] = (int)($status_result['rejected'] ?? 0);
            $status_stmt->close();
        }
    } else {
        $status_result = $mysqli1->query($status_sql);
        if ($status_result) {
            $row = $status_result->fetch_assoc();
            $counts['waiting'] = (int)($row['waiting'] ?? 0);
            $counts['approved'] = (int)($row['approved'] ?? 0);
            $counts['rejected'] = (int)($row['rejected'] ?? 0);
        }
    }
    
    error_log("Counts calculated: " . print_r($counts, true));
    
} catch (Exception $e) {
    error_log("Error calculating counts: " . $e->getMessage());
}

/* ------- بناء الاستعلام الرئيسي ------- */
$from = "FROM students s";
$where = ["1=1"];
$params = [];
$types  = "";

if ($selected_semester_id) {
    $from = "FROM students s INNER JOIN registrations r ON s.student_id = r.student_id";
    $where[] = "r.semester_id = ?";
    $params[] = $selected_semester_id;
    $types .= "i";
}

switch ($status) {
    case 'waiting': 
        $where[] = "s.medical_status = 'completed'";
        $where[] = "s.profile_completed = 1";
        $where[] = "s.medically_fit IS NULL";
        break;
    case 'approved':     
        $where[] = "s.medically_fit = 1";     
        $where[] = "s.medical_status = 'completed'";
        $where[] = "s.profile_completed = 1";
        break;
    case 'rejected':     
        $where[] = "s.medically_fit = 0";     
        $where[] = "s.medical_status = 'completed'";
        $where[] = "s.profile_completed = 1";
        break;
    case 'all':
    default: 
        break;
}

if ($college_id && $college_id > 0) {
    $where[] = "s.college_id = ?";
    $types  .= "i";
    $params[] = $college_id;
}

if ($program_id && $program_id > 0) {
    $where[] = "s.program_id = ?";
    $types  .= "i";
    $params[] = $program_id;
}

if ($q !== '') {
    if (ctype_digit($q)) {
        $where[] = "s.student_id = ?";
        $types  .= "s";
        $params[] = $q;
    } else {
        $where[] = "(s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?)";
        $types  .= "sss";
        $like = "%" . $q . "%";
        $params[] = $like; 
        $params[] = $like; 
        $params[] = $like;
    }
}

$whereSql = "WHERE " . implode(" AND ", $where);

/* ------- ORDER ------- */
switch ($sort) {
    case 'id_asc':              $orderBy = "ORDER BY s.student_id ASC"; break;
    case 'medical_date_desc':   $orderBy = "ORDER BY m.medical_date DESC, s.student_id DESC"; break;
    case 'medical_date_asc':    $orderBy = "ORDER BY m.medical_date ASC, s.student_id ASC"; break;
    case 'id_desc':
    default:                    $orderBy = "ORDER BY s.student_id DESC"; break;
}

/* ============== الاستعلام الرئيسي مع المتسلسل والبرنامج ============== */
$sql = "
    SELECT 
        s.student_id, 
        s.student_name, 
        s.student_name_eng, 
        s.nationality,
        s.phone_number, 
        s.interview_status, 
        s.medically_fit,
        s.medical_checked_at,
        s.medical_status,
        s.profile_completed,
        s.college_id,
        s.program_id,
        c.name as college_name,
        p.name as program_name,
        m.medical_date,
        m.has_disability,
        m.has_chronic_diseases,
        m.has_psychological_diseases,
        m.has_vision_problems,
        m.has_hearing_problems,
        m.covid_vaccinated,
        m.has_diabetes,
        m.has_blood_pressure,
        m.has_family_diseases,
        @rownum := @rownum + 1 as serial_number
    $from
    CROSS JOIN (SELECT @rownum := " . (($page - 1) * $limit) . ") rn
    LEFT JOIN student_medical_records m ON s.student_id = m.student_id
    LEFT JOIN colleges c ON s.college_id = c.id
    LEFT JOIN programs p ON s.program_id = p.id
    $whereSql
    $orderBy
    LIMIT ? OFFSET ?
";

$students = [];
$row_count = 0;

try {
    error_log("SQL: " . $sql);
    error_log("Params count: " . count($params));
    
    $stmt = $mysqli1->prepare($sql);
    if (!$stmt) { 
        error_log("Failed to prepare SQL statement: " . $mysqli1->error);
        throw new Exception("DB error in preparing statement.");
    }
    
    // Add pagination parameters
    $all_types = $types . "ii";
    $all_params = array_merge($params, [$limit, $offset]);
    
    if (!empty($all_params)) { 
        $stmt->bind_param($all_types, ...$all_params); 
    }
    
    $stmt->execute();
    
    $res = $stmt->get_result();
    $row_count = $res->num_rows;
    error_log("Number of rows fetched: $row_count");
    
    while($row = $res->fetch_assoc()) {
        $students[] = $row;
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    error_log("Error executing query: " . $e->getMessage());
    $students = [];
    $row_count = 0;
}

// حساب وقت التنفيذ
$end_time = microtime(true);
$execution_time = $end_time - $start_time;
error_log("Execution time: " . round($execution_time, 2) . " seconds");

// بدء إخراج HTML
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>كشف الفحص الطبي - الفصل الأول</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
  --primary: #4361ee;
  --success: #06d6a0;
  --warning: #ffd166;
  --danger: #ef476f;
  --dark: #2b2d42;
  --light: #f8f9fa;
  --border: #e9ecef;
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background: #f5f7fa;
  min-height: 100vh;
  font-family: 'Cairo', sans-serif;
  padding: 20px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.main-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.dashboard-header {
  background: linear-gradient(135deg, #2b2d42, #4a4e69);
  color: white;
  padding: 20px;
  text-align: center;
}

.welcome-text {
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1rem;
  opacity: 0.9;
  margin-bottom: 20px;
}

.semester-badge {
  display: inline-block;
  background: #f59e0b;
  color: white;
  padding: 8px 20px;
  border-radius: 50px;
  font-weight: 700;
  margin-top: 10px;
  font-size: 1.1rem;
}

.action-buttons-top {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 15px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer !important;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
  font-size: 0.9rem;
  min-width: 120px;
  justify-content: center;
}

.btn-refresh {
  background: #f59e0b;
  color: white;
}

.btn-home {
  background: #10b981;
  color: white;
}

.btn-logout {
  background: #ef4444;
  color: white;
}

.btn:hover {
  transform: translateY(-2px);
  opacity: 0.9;
}

.btn:disabled {
  cursor: not-allowed !important;
  opacity: 0.6;
}

.pagination-btn {
  min-width: 40px;
  padding: 8px 12px;
}

.flash-message {
  padding: 15px 20px;
  margin: 20px;
  border-radius: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.flash-success {
  background: #d1fae5;
  color: #065f46;
  border: 1px solid #a7f3d0;
}

.flash-error {
  background: #fee2e2;
  color: #991b1b;
  border: 1px solid #fecaca;
}

.filters-section {
  padding: 20px;
  background: var(--light);
  border-bottom: 1px solid var(--border);
}

.filters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.form-control, .form-select {
  width: 100%;
  padding: 10px 15px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 0.9rem;
  font-family: 'Cairo', sans-serif;
}

.form-control:focus, .form-select:focus {
  border-color: var(--primary);
  outline: none;
  box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
}

.filter-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 15px;
}

.btn-primary {
  background: var(--primary);
  color: white;
}

.btn-light {
  background: #64748b;
  color: white;
}

.tabs-section {
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid var(--border);
}

.tabs-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.tab {
  padding: 10px 20px;
  border-radius: 10px;
  text-decoration: none;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  color: #64748b;
  border: 1px solid var(--border);
  transition: all 0.3s ease;
}

.tab:hover {
  background: #f1f5f9;
  transform: translateY(-2px);
}

.tab.active {
  background: #f1f5f9;
  color: var(--primary);
  border-color: var(--primary);
}

.count-badge {
  background: #e2e8f0;
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 700;
  min-width: 30px;
  text-align: center;
}

.table-section {
  padding: 0;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 900px;
}

.data-table th {
  background: #f8fafc;
  padding: 12px 10px;
  text-align: right;
  font-weight: 700;
  color: var(--dark);
  border-bottom: 2px solid var(--border);
  white-space: nowrap;
}

.data-table td {
  padding: 12px 10px;
  border-bottom: 1px solid var(--border);
  white-space: nowrap;
}

.serial-column {
  width: 60px;
  text-align: center;
  font-weight: 600;
  color: var(--primary);
}

.table-footer {
  padding: 15px 20px;
  background: #f8fafc;
  border-top: 1px solid var(--border);
  text-align: center;
  color: #64748b;
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 700;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.badge-waiting { background: #fef3c7; color: #92400e; }
.badge-approved { background: #d1fae5; color: #065f46; }
.badge-rejected { background: #fee2e2; color: #991b1b; }

.action-btn {
  padding: 6px 12px;
  background: var(--primary);
  color: white;
  text-decoration: none;
  border-radius: 6px;
  font-size: 0.8rem;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: #3046c0;
  transform: translateY(-2px);
}

.loading {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255,255,255,.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.info-box {
  background: #e0f2fe;
  border-right: 4px solid #2596be;
  padding: 15px 20px;
  margin: 15px 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-box i {
  color: #2596be;
  font-size: 1.2rem;
}

.info-box p {
  color: #0c4a6e;
  font-weight: 500;
}

.program-badge {
  background: #8b5cf6;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
}

.college-badge {
  background: #64748b;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
}

@media (max-width: 768px) {
  body { padding: 10px; }
  .welcome-text { font-size: 1.5rem; }
  .action-buttons-top { flex-direction: column; align-items: center; }
  .btn { width: 100%; max-width: 300px; }
  .filters-grid { grid-template-columns: 1fr; }
  .tabs-container { flex-direction: column; }
  .tab { width: 100%; justify-content: center; }
  .data-table { font-size: 0.8rem; }
  .serial-column { width: 40px; }
}
</style>
</head>
<body>
<div class="container">
  <div class="main-card">
    <!-- الهيدر -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="welcome-text">
          <i class="fas fa-user-md"></i>
          مرحباً د. <?php echo htmlspecialchars($doctor['name'] ?? 'الطبيب'); ?>
        </div>
        <div class="subtitle">لوحة التحكم - إدارة الخدمات الصحية</div>
        
        <?php if ($selected_semester_id): ?>
          <div class="semester-badge">
            <i class="fas fa-graduation-cap"></i>
            عرض طلاب الفصل الأول - <?php echo date('Y'); ?>
          </div>
        <?php endif; ?>
        
        <!-- أزرار الإجراءات في الأعلى -->
        <div class="action-buttons-top">
          <button class="btn btn-refresh" id="refreshBtn">
            <i class="fas fa-sync-alt"></i>
            تحديث الصفحة
          </button>
          
          <a href="../index.php" class="btn btn-home" id="homeBtn">
            <i class="fas fa-home"></i>
            الصفحة الرئيسية
          </a>
          
          <a href="signout.php?role=doctor" class="btn btn-logout" id="logoutBtn" onclick="return confirm('هل أنت متأكد من تسجيل الخروج؟')">
            <i class="fas fa-sign-out-alt"></i>
            تسجيل الخروج
          </a>
        </div>
      </div>
    </div>

    <!-- الرسائل -->
    <?php if ($flashOk): ?>
      <div class="flash-message flash-success">
        <i class="fas fa-check-circle"></i>
        <?php echo htmlspecialchars($flashOk); ?>
      </div>
    <?php endif; ?>
    
    <?php if ($flashErr): ?>
      <div class="flash-message flash-error">
        <i class="fas fa-exclamation-triangle"></i>
        <?php echo htmlspecialchars($flashErr); ?>
      </div>
    <?php endif; ?>

    <!-- معلومات DEBUG (يمكن إخفاؤها في الإنتاج) -->
    <div class="info-box">
      <i class="fas fa-info-circle"></i>
      <div>
        <strong>معلومات النظام:</strong><br>
        - عدد الطلاب الكلي: <?php echo $counts['all']; ?><br>
        - الفصل المحدد: <?php echo $selected_semester_id ? 'معرف الفصل: ' . $selected_semester_id : 'جميع الفصول'; ?><br>
        - عدد النتائج المعروضة: <?php echo count($students); ?><br>
        - الصفحة: <?php echo $page; ?> من <?php echo $total_pages; ?>
      </div>
    </div>

    <!-- الفلاتر -->
    <div class="filters-section">
      <form method="get" id="filtersForm">
        <input type="hidden" name="status" value="<?php echo htmlspecialchars($status); ?>">
        <input type="hidden" name="page" value="1" id="pageInput">
        
        <div class="filters-grid">
          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-university"></i> الكليّة
            </label>
            <select name="college_id" class="form-control" id="collegeSelect">
              <option value="">جميع الكليات</option>
              <?php foreach ($colleges as $id => $name): ?>
                <option value="<?php echo (int)$id; ?>" <?php echo $college_id == $id ? 'selected' : ''; ?>>
                  <?php echo htmlspecialchars($name); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-graduation-cap"></i> البرنامج
            </label>
            <select name="program_id" class="form-control" id="programSelect">
              <option value="">جميع البرامج</option>
              <?php foreach ($programs as $id => $name): ?>
                <option value="<?php echo (int)$id; ?>" <?php echo $program_id == $id ? 'selected' : ''; ?>>
                  <?php echo htmlspecialchars($name); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-graduation-cap"></i> الفصل الدراسي
            </label>
            <select name="semester_filter" class="form-control">
          
              <option value="first" <?php echo $semester_filter === 'first' ? 'selected' : ''; ?>>الفصل الأول</option>
                         </select>
          </div>

          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-search"></i> البحث
            </label>
            <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" 
                   placeholder="ابحث برقم أو اسم الطالب..." class="form-control">
          </div>

          <div class="filter-group">
            <label style="font-weight: 600; margin-bottom: 5px; display: block;">
              <i class="fas fa-sort"></i> الترتيب
            </label>
            <select name="sort" class="form-control">
              <option value="id_desc" <?php echo $sort==='id_desc'?'selected':''; ?>>الأحدث أولاً</option>
              <option value="id_asc" <?php echo $sort==='id_asc'?'selected':''; ?>>الأقدم أولاً</option>
              <option value="medical_date_desc" <?php echo $sort==='medical_date_desc'?'selected':''; ?>>آخر فحص (حديث)</option>
              <option value="medical_date_asc" <?php echo $sort==='medical_date_asc'?'selected':''; ?>>آخر فحص (قديم)</option>
            </select>
          </div>
        </div>

        <div class="filter-actions">
          <button type="submit" class="btn btn-primary" id="applyFilters">
            <i class="fas fa-filter"></i>
            تطبيق الفلاتر
          </button>
          <a href="medical_list.php?status=all&semester_filter=first" class="btn btn-light">
            <i class="fas fa-times"></i>
            إعادة تعيين
          </a>
        </div>
      </form>
    </div>

    <!-- التبويبات -->
    <div class="tabs-section">
      <div class="tabs-container">
        <a class="tab all <?php echo $status==='all'?'active':''; ?>" 
           href="?status=all&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=1">
          <i class="fas fa-users"></i>
          الكل
          <span class="count-badge"><?php echo (int)$counts['all']; ?></span>
        </a>
        
        <a class="tab waiting <?php echo $status==='waiting'?'active':''; ?>" 
           href="?status=waiting&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=1">
          <i class="fas fa-clock"></i>
          في الانتظار
          <span class="count-badge"><?php echo (int)$counts['waiting']; ?></span>
        </a>
        
        <a class="tab approved <?php echo $status==='approved'?'active':''; ?>" 
           href="?status=approved&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=1">
          <i class="fas fa-check-circle"></i>
          مقبول
          <span class="count-badge"><?php echo (int)$counts['approved']; ?></span>
        </a>
        
        <a class="tab rejected <?php echo $status==='rejected'?'active':''; ?>" 
           href="?status=rejected&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=1">
          <i class="fas fa-times-circle"></i>
          مرفوض
          <span class="count-badge"><?php echo (int)$counts['rejected']; ?></span>
        </a>
      </div>
    </div>

    <!-- الجدول -->
    <div class="table-section">
      <?php if (empty($students)): ?>
        <div style="text-align: center; padding: 60px 20px; color: #64748b;">
          <i class="fas fa-info-circle" style="font-size: 4rem; margin-bottom: 20px; opacity: 0.5;"></i>
          <h3 style="margin-bottom: 15px; font-size: 1.5rem;">لا توجد بيانات للعرض</h3>
          <p style="font-size: 1.1rem; opacity: 0.8;">
            <?php if ($selected_semester_id): ?>
              لا يوجد طلاب مسجلين في الفصل المحدد.
            <?php elseif ($q): ?>
              لم يتم العثور على نتائج للبحث "<?php echo htmlspecialchars($q); ?>"
            <?php elseif ($college_id): ?>
              لا يوجد طلاب في هذه الكلية.
            <?php elseif ($program_id): ?>
              لا يوجد طلاب في هذا البرنامج.
            <?php else: ?>
              لا يوجد طلاب في قاعدة البيانات.
            <?php endif; ?>
          </p>
          <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
            <a href="medical_list.php?status=all&semester_filter=all" class="btn btn-primary">عرض جميع الطلاب</a>
            <a href="medical_list.php?status=all&semester_filter=first" class="btn btn-warning">عرض الفصل الأول</a>
          </div>
        </div>
      <?php else: ?>
        <table class="data-table">
          <thead>
            <tr>
              <th class="serial-column">#</th>
              <th>رقم الطالب</th>
              <th>اسم الطالب</th>
              <th>الكليّة</th>
              <th>البرنامج</th>
              <th>الهاتف</th>
              <th>الحالة الطبية</th>
              <th>تاريخ الفحص</th>
              <th>الإجراء</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($students as $index => $row): ?>
            <?php
              $name  = $row['student_name'] ?: $row['student_name_eng'];
              $medically_fit = $row['medically_fit'];
              
              if ($medically_fit === null) { 
                $medTxt = 'في الانتظار'; 
                $medClass = 'badge-waiting';
                $medIcon = 'fas fa-clock';
              } elseif ((int)$medically_fit === 1) { 
                $medTxt = 'مقبول طبيًا';         
                $medClass = 'badge-approved';
                $medIcon = 'fas fa-check-circle';
              } else { 
                $medTxt = 'مرفوض طبيًا';     
                $medClass = 'badge-rejected';
                $medIcon = 'fas fa-times-circle';
              }
              
              $serial = ($page - 1) * $limit + $index + 1;
            ?>
            <tr>
              <td class="serial-column"><?php echo $serial; ?></td>
              <td><code><?php echo htmlspecialchars($row['student_id']); ?></code></td>
              <td><?php echo htmlspecialchars($name); ?></td>
              <td>
                <span class="college-badge">
                  <?php echo htmlspecialchars($row['college_name'] ?? '—'); ?>
                </span>
              </td>
              <td>
                <span class="program-badge">
                  <?php echo htmlspecialchars($row['program_name'] ?? '—'); ?>
                </span>
              </td>
              <td><?php echo htmlspecialchars($row['phone_number'] ?? '—'); ?></td>
              <td>
                <span class="status-badge <?php echo $medClass; ?>">
                  <i class="<?php echo $medIcon; ?>"></i>
                  <?php echo $medTxt; ?>
                </span>
              </td>
              <td><?php echo $row['medical_checked_at'] ? date('Y-m-d', strtotime($row['medical_checked_at'])) : '—'; ?></td>
              <td>
                <a class="action-btn" href="medical_review.php?id=<?php echo urlencode($row['student_id']); ?>">
                  <i class="fas fa-eye"></i>
                  عرض
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
          <div class="pagination">
            <?php if ($page > 1): ?>
              <a class="btn btn-light pagination-btn" 
                 href="?status=<?php echo urlencode($status); ?>&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=<?php echo $page-1; ?>">
                <i class="fas fa-chevron-right"></i>
              </a>
            <?php endif; ?>
            
            <?php
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            for ($i = $start_page; $i <= $end_page; $i++):
            ?>
              <a class="btn <?php echo $i == $page ? 'btn-primary' : 'btn-light'; ?> pagination-btn" 
                 href="?status=<?php echo urlencode($status); ?>&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=<?php echo $i; ?>">
                <?php echo $i; ?>
              </a>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
              <a class="btn btn-light pagination-btn" 
                 href="?status=<?php echo urlencode($status); ?>&sort=<?php echo urlencode($sort); ?>&q=<?php echo urlencode($q); ?>&college_id=<?php echo (int)$college_id; ?>&program_id=<?php echo (int)$program_id; ?>&semester_filter=<?php echo urlencode($semester_filter); ?>&page=<?php echo $page+1; ?>">
                <i class="fas fa-chevron-left"></i>
              </a>
            <?php endif; ?>
          </div>
        <?php endif; ?>
      <?php endif; ?>
    </div>

    <!-- الفوتر -->
    <div class="table-footer">
      <i class="fas fa-info-circle"></i>
      <?php if (!empty($students)): ?>
        عرض <?php echo count($students); ?> طالب من أصل <?php echo (int)$counts['all']; ?>
        <?php if ($selected_semester_id): ?>
          في الفصل الأول
        <?php endif; ?>
        - الصفحة <?php echo $page; ?> من <?php echo $total_pages; ?>
      <?php else: ?>
        لا توجد نتائج مطابقة للبحث
      <?php endif; ?>
      <br>
      <small>وقت التنفيذ: <?php echo round($execution_time, 2); ?> ثانية</small>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // زر التحديث
    const refreshBtn = document.getElementById('refreshBtn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function(e) {
            e.preventDefault();
            this.innerHTML = '<span class="loading"></span> جاري التحديث...';
            this.disabled = true;
            setTimeout(() => window.location.reload(), 300);
        });
    }
    
    // منع الإرسال المزدوج
    const filtersForm = document.getElementById('filtersForm');
    const applyBtn = document.getElementById('applyFilters');
    
    if (filtersForm && applyBtn) {
        filtersForm.addEventListener('submit', function(e) {
            if (applyBtn.disabled) {
                e.preventDefault();
                return false;
            }
            applyBtn.disabled = true;
            applyBtn.innerHTML = '<span class="loading"></span> جاري التطبيق...';
        });
    }
    
    // تحديث البرامج عند تغيير الكلية (اختياري - يمكن إضافة AJAX هنا)
    const collegeSelect = document.getElementById('collegeSelect');
    if (collegeSelect) {
        collegeSelect.addEventListener('change', function() {
            // يمكن إضافة AJAX لتحميل البرامج حسب الكلية
            console.log('College changed to: ' + this.value);
        });
    }
});
</script>
</body>
</html>
