<?php
// admin_dashboard.php - نسخة محسنة بالكامل مع الحماية من SQL Injection
require 'db.php';
require 'helpers.php';
require_committee();

// إضافة هيدرات الأمان
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

// تعطيل عرض الأخطاء في بيئة الإنتاج
ini_set('display_errors', 0);
error_log("Admin dashboard accessed - " . date('Y-m-d H:i:s'));

$committeeId   = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll        = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege  = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

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

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

/* ---------- دوال المساعدة للأمان ---------- */
function validateInt($value, $default = null) {
    if ($value === null || $value === '') return $default;
    return filter_var($value, FILTER_VALIDATE_INT) !== false ? (int)$value : $default;
}

function validateString($value, $default = '', $maxLength = 255) {
    if ($value === null) return $default;
    $value = trim($value);
    // إزالة الأحرف الخطيرة والـ HTML
    $value = strip_tags($value);
    // إزالة الأحرف الخاصة
    $value = preg_replace('/[<>"\']/', '', $value);
    // تحديد طول أقصى
    $value = substr($value, 0, $maxLength);
    return $value === '' ? $default : $value;
}

function escapeLike($value) {
    return addcslashes($value, '%_');
}

function tableExists($table) {
    global $mysqli1;
    $result = $mysqli1->query("SHOW TABLES LIKE '" . $mysqli1->real_escape_string($table) . "'");
    return $result && $result->num_rows > 0;
}

function executeQuery($sql, $types = '', $params = []) {
    global $mysqli1;
    try {
        $stmt = $mysqli1->prepare($sql);
        if (!$stmt) {
            error_log("Prepare failed: " . $mysqli1->error);
            return null;
        }
        if (!empty($types) && !empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        if (!$stmt->execute()) {
            error_log("Execute failed: " . $stmt->error);
            $stmt->close();
            return null;
        }
        return $stmt;
    } catch (Exception $e) {
        error_log("Query execution error: " . $e->getMessage());
        return null;
    }
}

/* ---------- التحقق من وجود الجداول ---------- */
$hasSpecializations = tableExists('specializations');
$hasBatches = tableExists('batches');
$hasColleges = tableExists('colleges');
$hasSections = tableExists('sections');
$hasPrograms = tableExists('programs');

/* ---------- استلام وتنظيف المتغيرات ---------- */
$filter_college_id = validateInt($_GET['filter_college'] ?? null);
$filter_section_id = validateInt($_GET['filter_section'] ?? null);
$filter_program_id = validateInt($_GET['filter_program'] ?? null);
$filter_specialization_id = $hasSpecializations ? validateInt($_GET['filter_specialization'] ?? null) : null;
$filter_batch_id = $hasBatches ? validateInt($_GET['filter_batch'] ?? null) : null;

// تنظيف متغير البحث
$q = validateString($_GET['q'] ?? '', '', 100);
$onlyCompleted = ($_GET['completed'] ?? '1') === '1';
$medicalFilter = isset($_GET['medical']) && in_array($_GET['medical'], ['all', 'fit', 'unfit']) ? $_GET['medical'] : 'all';

/* ---------- بناء WHERE clause للاستعلامات الرئيسية ---------- */
$where = " WHERE 1=1 ";
$types = '';
$params = [];

// Apply college filter first (if user has permission to filter by college)
if ($canAll && $filter_college_id) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $filter_college_id;
} elseif (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
}

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

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

// Apply specialization filter (if table exists)
if ($hasSpecializations && $filter_specialization_id) {
    $where .= " AND s.specialization_id = ? ";
    $types .= 'i'; 
    $params[] = $filter_specialization_id;
}

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

/* ---------- Top KPIs ---------- */
$sqlKpi = "
  SELECT
    COUNT(*) AS total,
    
    -- حالة المقابلة
    SUM(CASE WHEN s.interview_status='accepted' THEN 1 ELSE 0 END) AS st_accepted,
    SUM(CASE WHEN s.interview_status='rejected' THEN 1 ELSE 0 END) AS st_rejected,
    SUM(CASE WHEN s.profile_completed=1 AND s.interview_status='pending' THEN 1 ELSE 0 END) AS st_pending,
    
    -- الحالة الطبية
    SUM(CASE WHEN s.medically_fit=1 THEN 1 ELSE 0 END) AS med_fit,
    SUM(CASE WHEN s.medically_fit=0 THEN 1 ELSE 0 END) AS med_unfit,
    SUM(CASE WHEN s.profile_completed=1 AND s.medical_status='completed' THEN 1 ELSE 0 END) AS med_wait,
    
    -- إكمال الملف
    SUM(CASE WHEN s.profile_completed=1 THEN 1 ELSE 0 END) AS prof_ok,
    SUM(CASE WHEN (s.profile_completed IS NULL OR s.profile_completed<>1) THEN 1 ELSE 0 END) AS prof_no,
    
    -- الطلاب الذين لم يرسلوا بياناتهم
    SUM(CASE WHEN (s.profile_completed IS NULL OR s.profile_completed<>1) AND s.created_at IS NOT NULL THEN 1 ELSE 0 END) AS not_submitted
  FROM students s
  $where
";

$stmt = executeQuery($sqlKpi, $types, $params);
$kpi = $stmt ? $stmt->get_result()->fetch_assoc() : [];
if ($stmt) $stmt->close();

// تهيئة القيم الافتراضية
$defaultKpi = ['total'=>0, 'st_pending'=>0, 'st_accepted'=>0, 'st_rejected'=>0, 
               'med_wait'=>0, 'med_fit'=>0, 'med_unfit'=>0, 'prof_ok'=>0, 'prof_no'=>0, 'not_submitted'=>0];
foreach ($defaultKpi as $key => $value) {
    $kpi[$key] = (int)($kpi[$key] ?? $value);
}

/* ---------- By College ---------- */
$sqlByCollege = "
  SELECT c.id, c.name,
    COUNT(*) AS total,
    SUM(CASE WHEN s.interview_status='accepted' THEN 1 ELSE 0 END) AS accepted,
    SUM(CASE WHEN s.interview_status='rejected' THEN 1 ELSE 0 END) AS rejected,
    SUM(CASE WHEN s.profile_completed=1 AND s.interview_status='pending' THEN 1 ELSE 0 END) AS pending,
    SUM(CASE WHEN s.medically_fit=1 THEN 1 ELSE 0 END) AS med_fit,
    SUM(CASE WHEN s.medically_fit=0 THEN 1 ELSE 0 END) AS med_unfit,
    SUM(CASE WHEN s.profile_completed=1 AND s.medical_status='completed' THEN 1 ELSE 0 END) AS med_wait,
    SUM(CASE WHEN s.profile_completed=1 THEN 1 ELSE 0 END) AS profile_ok,
    SUM(CASE WHEN (s.profile_completed IS NULL OR s.profile_completed<>1) AND s.created_at IS NOT NULL THEN 1 ELSE 0 END) AS not_submitted
  FROM students s
  LEFT JOIN colleges c ON c.id = s.college_id
  $where
  GROUP BY c.id, c.name
  ORDER BY total DESC, c.name ASC
  LIMIT 20
";

// إزالة WHERE المكرر إذا وجد
$sqlByCollege = str_replace('WHERE 1=1 AND WHERE', 'WHERE', $sqlByCollege);
$stmt = executeQuery($sqlByCollege, $types, $params);
$byCollege = $stmt ? $stmt->get_result()->fetch_all(MYSQLI_ASSOC) : [];
if ($stmt) $stmt->close();

/* ---------- By Batch (الدفعات النشطة فقط - status=1) مع تطبيق الفلتر ---------- */
if ($hasBatches) {
    // بناء شروط WHERE للدفعات بناءً على الفلتر
    $batchWhere = " WHERE b.status = 1 AND b.deleted_at IS NULL";
    $batchTypes = '';
    $batchParams = [];
    
    // إضافة شروط الفلتر إذا كانت موجودة
    if ($canAll && $filter_college_id) {
        $batchWhere .= " AND s.college_id = ? ";
        $batchTypes .= 'i'; 
        $batchParams[] = $filter_college_id;
    } elseif (!$canAll && $scopeCollege !== null) {
        $batchWhere .= " AND s.college_id = ? ";
        $batchTypes .= 'i'; 
        $batchParams[] = $scopeCollege;
    }
    
    if ($filter_section_id) {
        $batchWhere .= " AND s.section_id = ? ";
        $batchTypes .= 'i'; 
        $batchParams[] = $filter_section_id;
    }
    
    if ($filter_program_id) {
        $batchWhere .= " AND s.program_id = ? ";
        $batchTypes .= 'i'; 
        $batchParams[] = $filter_program_id;
    }
    
    if ($hasSpecializations && $filter_specialization_id) {
        $batchWhere .= " AND s.specialization_id = ? ";
        $batchTypes .= 'i'; 
        $batchParams[] = $filter_specialization_id;
    }
    
    // استعلام لجلب جميع الدفعات النشطة مع عدد الطلاب في كل منها مع تطبيق الفلتر
    $sqlByBatch = "
        SELECT 
            b.id, 
            b.value AS name,
            COUNT(s.student_id) AS total,
            SUM(CASE WHEN s.interview_status = 'accepted' THEN 1 ELSE 0 END) AS accepted,
            SUM(CASE WHEN s.interview_status = 'rejected' THEN 1 ELSE 0 END) AS rejected,
            SUM(CASE WHEN s.profile_completed = 1 AND s.interview_status = 'pending' THEN 1 ELSE 0 END) AS pending,
            SUM(CASE WHEN s.medically_fit = 1 THEN 1 ELSE 0 END) AS med_fit,
            SUM(CASE WHEN s.medically_fit = 0 THEN 1 ELSE 0 END) AS med_unfit,
            SUM(CASE WHEN (s.profile_completed IS NULL OR s.profile_completed <> 1) AND s.created_at IS NOT NULL THEN 1 ELSE 0 END) AS not_submitted
        FROM batches b
        LEFT JOIN students s ON b.id = s.batch_id
        $batchWhere
        GROUP BY b.id, b.value
        ORDER BY b.value DESC
        LIMIT 20
    ";
    
    // تنفيذ الاستعلام مع معاملات الفلتر إذا وجدت
    if (!empty($batchTypes)) {
        $stmt = executeQuery($sqlByBatch, $batchTypes, $batchParams);
    } else {
        $stmt = executeQuery($sqlByBatch);
    }
    
    if ($stmt) {
        $byBatch = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        error_log("Batches data retrieved with filters: " . count($byBatch) . " batches");
    } else {
        $byBatch = [];
        error_log("Failed to execute batch query with filters");
    }
    
    // إذا لم تكن هناك نتائج، نعرض الدفعات بدون أعداد (على الأقل تظهر أسماء الدفعات)
    if (empty($byBatch)) {
        $simple_sql = "SELECT id, value AS name, 0 as total FROM batches WHERE status = 1 AND deleted_at IS NULL ORDER BY value DESC LIMIT 20";
        $simple_result = $mysqli1->query($simple_sql);
        if ($simple_result) {
            $byBatch = $simple_result->fetch_all(MYSQLI_ASSOC);
            error_log("Simple batch query returned " . count($byBatch) . " batches");
        }
    }
} else {
    $byBatch = [];
    error_log("Batches table does not exist");
}

/* ---------- 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,
    SUM(CASE WHEN (s.profile_completed IS NULL OR s.profile_completed<>1) AND s.created_at IS NOT NULL THEN 1 ELSE 0 END) AS not_submitted
  FROM students s
  $where
  GROUP BY s.gender
  ORDER BY total DESC
";

$stmt = executeQuery($sqlByGender, $types, $params);
$byGender = $stmt ? $stmt->get_result()->fetch_all(MYSQLI_ASSOC) : [];
if ($stmt) $stmt->close();

/* ---------- Recent Students ---------- */
// بناء استعلام recent حسب وجود جدول التخصصات
if ($hasSpecializations) {
    $sqlRecent = "
        SELECT 
            s.student_id, s.student_name, s.student_name_eng, 
            s.college_id, c.name AS college_name,
            s.section_id, sec.name AS section_name,
            s.program_id, p.name AS program_name,
            s.specialization_id, sp.specialization_name_ar AS specialization_name,
            s.batch_id, b.value AS batch_name,
            s.gender,
            s.interview_status as current_status,
            s.medically_fit,
            s.medical_status,
            COALESCE(s.profile_completed, 0) as profile_completed,
            s.created_at
        FROM students s
        LEFT JOIN colleges c ON c.id = s.college_id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON sec.id = s.section_id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON p.id = s.program_id AND p.deleted_at IS NULL
        LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_id AND sp.deleted_at IS NULL
        LEFT JOIN batches b ON b.id = s.batch_id AND b.deleted_at IS NULL
        $where
    ";
} else {
    $sqlRecent = "
        SELECT 
            s.student_id, s.student_name, s.student_name_eng, 
            s.college_id, c.name AS college_name,
            s.section_id, sec.name AS section_name,
            s.program_id, p.name AS program_name,
            NULL as specialization_id, NULL as specialization_name,
            s.batch_id, b.value AS batch_name,
            s.gender,
            s.interview_status as current_status,
            s.medically_fit,
            s.medical_status,
            COALESCE(s.profile_completed, 0) as profile_completed,
            s.created_at
        FROM students s
        LEFT JOIN colleges c ON c.id = s.college_id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON sec.id = s.section_id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON p.id = s.program_id AND p.deleted_at IS NULL
        LEFT JOIN batches b ON b.id = s.batch_id AND b.deleted_at IS NULL
        $where
    ";
}

// إضافة شروط البحث
if ($q !== '') {
    $sqlRecent .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?) ";
}

// إضافة شروط completed
if ($onlyCompleted) {
    $sqlRecent .= " AND COALESCE(s.profile_completed,0)=1 ";
}

// إضافة شروط medical
if ($medicalFilter !== 'all') {
    if ($medicalFilter === 'fit') {
        $sqlRecent .= " AND s.medically_fit=1 ";
    } elseif ($medicalFilter === 'unfit') {
        $sqlRecent .= " AND s.medically_fit=0 ";
    }
}

$sqlRecent .= " ORDER BY s.student_id DESC LIMIT 20 ";

// تنفيذ الاستعلام مع البحث إذا وجد
if ($q !== '') {
    $kw = '%' . escapeLike($q) . '%';
    if (!empty($types)) {
        $bindTypes = $types . 'sss';
        $bindArgs = array_merge($params, [$kw, $kw, $kw]);
    } else {
        $bindTypes = 'sss';
        $bindArgs = [$kw, $kw, $kw];
    }
    $stmt = executeQuery($sqlRecent, $bindTypes, $bindArgs);
} else {
    $stmt = executeQuery($sqlRecent, $types, $params);
}

$recentAccepted = $stmt ? $stmt->get_result()->fetch_all(MYSQLI_ASSOC) : [];
if ($stmt) $stmt->close();

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

<style>
  :root {
    --primary-color: #1a5d1a;
    --secondary-color: #2e8b57;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --danger-color: #ef4444;
    --info-color: #3b82f6;
    --purple-color: #8b5cf6;
    --teal-color: #14b8a6;
    --orange-color: #f97316;
  }

  body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
    font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; 
  }

  .dash-card {
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
  }

  /* بطاقات التقارير المحسنة */
  .report-card {
    background: linear-gradient(135deg, #ffffff, #f8fafc);
    border-radius: 16px;
    padding: 25px;
    margin-bottom: 25px;
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }
  
  .report-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 6px;
    height: 100%;
    background: linear-gradient(to bottom, #4f46e5, #7c3aed);
  }
  
  .report-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 30px rgba(0,0,0,0.08);
  }
  
  .report-icon {
    font-size: 2.5rem;
    margin-bottom: 15px;
    color: #4f46e5;
  }
  
  .report-title {
    color: #1e293b;
    font-weight: 800;
    font-size: 1.2rem;
    margin-bottom: 10px;
  }
  
  .report-desc {
    color: #64748b;
    font-size: 0.9rem;
    line-height: 1.5;
    margin-bottom: 20px;
  }
  
  /* تحسين بطاقات الإحصائيات الرئيسية */
  .kpi-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }

  .kpi-card {
    background: white;
    border-radius: 16px;
    padding: 25px;
    position: relative;
    overflow: hidden;
    border: none;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
  }

  .kpi-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
  }

  .kpi-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 15px;
    background: var(--primary-color);
  }

  .kpi-card.total::before { background: linear-gradient(135deg, #1a5d1a, #2e8b57); }
  .kpi-card.accepted::before { background: linear-gradient(135deg, #065f46, #10b981); }
  .kpi-card.pending::before { background: linear-gradient(135deg, #78350f, #f59e0b); }
  .kpi-card.rejected::before { background: linear-gradient(135deg, #991b1b, #ef4444); }
  .kpi-card.not-submitted::before { background: linear-gradient(135deg, #92400e, #f97316); }

  .kpi-icon {
    position: absolute;
    top: 25px;
    right: 25px;
    width: 50px;
    height: 50px;
    border-radius: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: white;
  }

  .kpi-card.total .kpi-icon { background: linear-gradient(135deg, #1a5d1a, #2e8b57); }
  .kpi-card.accepted .kpi-icon { background: linear-gradient(135deg, #065f46, #10b981); }
  .kpi-card.pending .kpi-icon { background: linear-gradient(135deg, #78350f, #f59e0b); }
  .kpi-card.rejected .kpi-icon { background: linear-gradient(135deg, #991b1b, #ef4444); }
  .kpi-card.not-submitted .kpi-icon { background: linear-gradient(135deg, #92400e, #f97316); }

  .kpi-content {
    text-align: right;
    padding-right: 70px;
  }

  .kpi-number {
    font-size: 2.4rem;
    font-weight: 900;
    line-height: 1;
    margin-bottom: 8px;
    color: #1a1a1a;
  }

  .kpi-card.total .kpi-number { color: #1a5d1a; }
  .kpi-card.accepted .kpi-number { color: #065f46; }
  .kpi-card.pending .kpi-number { color: #78350f; }
  .kpi-card.rejected .kpi-number { color: #991b1b; }
  .kpi-card.not-submitted .kpi-number { color: #92400e; }

  .kpi-label {
    font-size: 1.1rem;
    color: #4b5563;
    font-weight: 700;
    margin-bottom: 5px;
  }

  .kpi-subtext {
    font-size: 0.85rem;
    color: #9ca3af;
    font-weight: 500;
  }

  .kpi-trend {
    position: absolute;
    bottom: 20px;
    left: 25px;
    font-size: 0.8rem;
    padding: 4px 10px;
    border-radius: 20px;
    font-weight: 600;
  }

  .kpi-card.total .kpi-trend { background: rgba(26, 93, 26, 0.1); color: #1a5d1a; }
  .kpi-card.accepted .kpi-trend { background: rgba(6, 95, 70, 0.1); color: #065f46; }
  .kpi-card.pending .kpi-trend { background: rgba(120, 53, 15, 0.1); color: #78350f; }
  .kpi-card.rejected .kpi-trend { background: rgba(153, 27, 27, 0.1); color: #991b1b; }
  .kpi-card.not-submitted .kpi-trend { background: rgba(146, 64, 14, 0.1); color: #92400e; }

  .chart-container {
    background: white;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.05);
    height: 100%;
    min-height: 350px;
  }

  .chart-title {
    font-size: 1.1rem;
    font-weight: 700;
    color: #1a5d1a;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 10px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f1f5f9;
  }

  .chart-title i {
    color: #1a5d1a;
    font-size: 1.2rem;
  }

  .settings-section {
    background: linear-gradient(135deg, #1a5d1a, #2e8b57);
    color: white;
    border-radius: 18px;
    padding: 25px;
    margin-bottom: 25px;
    box-shadow: 0 8px 32px rgba(26, 93, 26, 0.2);
  }

  .settings-card {
    background: white;
    border-radius: 14px;
    padding: 22px;
    text-align: center;
    box-shadow: 0 6px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
    height: 100%;
    border: 1px solid #f1f5f9;
  }

  .settings-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 30px rgba(0,0,0,0.12);
  }

  .settings-icon {
    font-size: 2.2rem;
    margin-bottom: 15px;
    background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
    width: 60px;
    height: 60px;
    line-height: 60px;
    border-radius: 50%;
    margin: 0 auto 15px;
    color: white;
  }

  .settings-card h6 {
    font-weight: 800;
    margin-bottom: 10px;
    font-size: 1rem;
  }

  .settings-card p {
    color: #64748b;
    font-size: 0.85rem;
    line-height: 1.5;
    margin-bottom: 20px;
    min-height: 40px;
  }

  .chip {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 0.3rem 0.8rem;
    border-radius: 50px;
    font-size: 0.85rem;
    font-weight: 600;
    border: none;
  }

  .chip.green {
    background: linear-gradient(135deg, #d1fae5, #a7f3d0);
    color: #065f46;
  }

  .chip.gray {
    background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
    color: #4b5563;
  }

  .chip.red {
    background: linear-gradient(135deg, #fee2e2, #fecaca);
    color: #991b1b;
  }

  .chip.blue {
    background: linear-gradient(135deg, #dbeafe, #bfdbfe);
    color: #1e3a8a;
  }

  .chip.orange {
    background: linear-gradient(135deg, #ffedd5, #fed7aa);
    color: #9a3412;
  }

  .chip.purple {
    background: linear-gradient(135deg, #f3e8ff, #e9d5ff);
    color: #7e22ce;
  }

  .chip.yellow {
    background: linear-gradient(135deg, #fef3c7, #fde68a);
    color: #92400e;
  }

  .btn {
    border-radius: 10px;
    font-weight: 700;
    padding: 8px 20px;
    font-size: 0.9rem;
    border: none;
    transition: all 0.3s ease;
  }

  .btn-sm {
    padding: 6px 15px;
    font-size: 0.85rem;
  }

  .btn-primary {
    background: linear-gradient(135deg, #1a5d1a, #2e8b57);
  }

  .btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(26, 93, 26, 0.3);
  }

  .btn-success {
    background: linear-gradient(135deg, #10b981, #059669);
  }

  .btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(16, 185, 129, 0.3);
  }

  .btn-warning {
    background: linear-gradient(135deg, #f59e0b, #d97706);
  }

  .btn-warning:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(245, 158, 11, 0.3);
  }

  .btn-danger {
    background: linear-gradient(135deg, #ef4444, #dc2626);
  }

  .btn-danger:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(239, 68, 68, 0.3);
  }

  .table-card {
    background: white;
    border-radius: 16px;
    padding: 0;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.05);
  }

  .table-header {
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;
    background: #f8fafc;
  }

  .table-title {
    font-size: 1.1rem;
    font-weight: 700;
    color: #1a5d1a;
    margin: 0;
  }

  .table th {
    background: #f8fafc;
    border-bottom: 2px solid #e2e8f0;
    font-weight: 700;
    color: #475569;
    font-size: 0.9rem;
    padding: 15px;
  }

  .table td {
    padding: 12px 15px;
    vertical-align: middle;
    border-color: #f1f5f9;
    font-size: 0.9rem;
  }

  .filter-card {
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
  }

  .filter-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f1f5f9;
  }

  .filter-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, #1a5d1a, #2e8b57);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.3rem;
  }

  .filter-title {
    font-size: 1.2rem;
    font-weight: 700;
    color: #1a5d1a;
    margin: 0;
  }

  .form-label {
    font-weight: 600;
    color: #4b5563;
    font-size: 0.9rem;
    margin-bottom: 8px;
  }

  .form-control, .form-select {
    border-radius: 10px;
    border: 1px solid #d1d5db;
    padding: 10px 15px;
    font-size: 0.9rem;
  }

  .form-control:focus, .form-select:focus {
    border-color: #1a5d1a;
    box-shadow: 0 0 0 3px rgba(26, 93, 26, 0.1);
  }

  .main-header {
    background: linear-gradient(135deg, #1a5d1a, #2e8b57);
    border-radius: 16px;
    padding: 25px;
    color: white;
    margin-bottom: 30px;
  }

  .main-header h3 {
    font-size: 1.8rem;
    font-weight: 800;
    margin-bottom: 8px;
  }

  .main-header p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1rem;
    margin-bottom: 0;
  }

  .chart-wrapper {
    height: 280px;
    position: relative;
  }

  .chart-legend {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 15px;
  }

  .legend-item {
    display: flex;
    align-items: center;
    font-size: 0.85rem;
    background: #f8fafc;
    padding: 5px 10px;
    border-radius: 6px;
    border: 1px solid #e2e8f0;
  }

  .legend-color {
    width: 12px;
    height: 12px;
    border-radius: 2px;
    margin-left: 8px;
  }

  .progress {
    border-radius: 10px;
    background-color: #f1f5f9;
    height: 10px;
  }

  .progress-bar {
    border-radius: 10px;
  }

  .college-progress {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 8px 0;
  }

  .college-name {
    min-width: 180px;
    font-weight: 700;
    color: #1e293b;
    font-size: 0.95rem;
  }

  .progress-container {
    flex: 1;
  }

  .college-count {
    min-width: 70px;
    text-align: left;
    font-weight: 700;
    color: #1e293b;
    font-size: 1rem;
  }

  /* تنسيق التبويبات في قسم الإعدادات */
  .nav-tabs .nav-link {
    border-radius: 30px;
    margin: 0 5px;
    padding: 10px 20px;
    font-weight: 600;
    transition: all 0.3s ease;
    border: none;
  }

  .nav-tabs .nav-link:hover {
    background-color: rgba(255, 255, 255, 0.2) !important;
    transform: translateY(-2px);
  }

  .nav-tabs .nav-link.active {
    background-color: white !important;
    color: #1a5d1a !important;
    font-weight: 700;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  }

  /* تحسين ظهور البطاقات داخل التبويبات */
  .tab-pane {
    transition: opacity 0.3s ease;
  }

  .tab-pane .settings-card {
    opacity: 0.95;
    transition: all 0.3s ease;
  }

  .tab-pane .settings-card:hover {
    opacity: 1;
    transform: translateY(-5px) scale(1.02);
    box-shadow: 0 15px 30px rgba(0,0,0,0.15);
  }

  /* تحسين ظهور التبويبات في الشاشات الصغيرة */
  @media (max-width: 768px) {
    .nav-tabs .nav-link {
      font-size: 0.8rem;
      padding: 8px 10px;
    }
    
    .nav-tabs .nav-link i {
      margin-left: 3px;
    }
    
    .kpi-container {
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
      gap: 15px;
    }
    
    .kpi-card {
      padding: 20px;
    }
    
    .kpi-icon {
      width: 40px;
      height: 40px;
      font-size: 1.2rem;
    }
    
    .kpi-content {
      padding-right: 60px;
    }
    
    .kpi-number {
      font-size: 2rem;
    }
    
    .chart-wrapper {
      height: 240px;
    }
  }
</style>

<div class="container py-4" dir="rtl">
  <!-- Header -->
  <div class="main-header">
    <div class="d-flex align-items-center justify-content-between">
      <div>
        <h3>لوحة التحكم الإدارية</h3>
        <p>مرحباً <?= htmlspecialchars($committeeName ?: 'عضو اللجنة') ?> - نظرة عامة على إحصائيات النظام</p>
      </div>
    </div>
  </div>

  <!-- بطاقات الإحصائيات الرئيسية المحسنة -->
  <div class="dash-card">
    <h5 class="chart-title mb-3">
      <i class="fas fa-chart-line"></i>
      الإحصائيات الرئيسية
    </h5>
    <div class="kpi-container">
      <div class="kpi-card total">
        <div class="kpi-icon">
          <i class="fas fa-users"></i>
        </div>
        <div class="kpi-content">
          <div class="kpi-number"><?= number_format($kpi['total']) ?></div>
          <div class="kpi-label">إجمالي الطلاب</div>
          <div class="kpi-subtext">جميع الطلاب المسجلين</div>
        </div>
        <div class="kpi-trend">إجمالي</div>
      </div>

      <div class="kpi-card accepted">
        <div class="kpi-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="kpi-content">
          <div class="kpi-number"><?= number_format($kpi['st_accepted']) ?></div>
          <div class="kpi-label">تم قبولهم</div>
          <div class="kpi-subtext">نسبة القبول: <?= $kpi['total'] > 0 ? number_format(($kpi['st_accepted'] / $kpi['total']) * 100, 1) : 0 ?>%</div>
        </div>
        <div class="kpi-trend">مقبول</div>
      </div>

      <div class="kpi-card pending">
        <div class="kpi-icon">
          <i class="fas fa-clock"></i>
        </div>
        <div class="kpi-content">
          <div class="kpi-number"><?= number_format($kpi['st_pending']) ?></div>
          <div class="kpi-label">قيد الانتظار</div>
          <div class="kpi-subtext">بانتظار المقابلة</div>
        </div>
        <div class="kpi-trend">قيد الانتظار</div>
      </div>

      <div class="kpi-card rejected">
        <div class="kpi-icon">
          <i class="fas fa-times-circle"></i>
        </div>
        <div class="kpi-content">
          <div class="kpi-number"><?= number_format($kpi['st_rejected']) ?></div>
          <div class="kpi-label">مرفوضون</div>
          <div class="kpi-subtext">لم يجتازوا المقابلة</div>
        </div>
        <div class="kpi-trend">مرفوض</div>
      </div>

      <div class="kpi-card not-submitted">
        <div class="kpi-icon">
          <i class="fas fa-exclamation-circle"></i>
        </div>
        <div class="kpi-content">
          <div class="kpi-number"><?= number_format($kpi['not_submitted']) ?></div>
          <div class="kpi-label">ملفات غير مكتملة</div>
          <div class="kpi-subtext">لم يرسلوا بياناتهم</div>
        </div>
        <div class="kpi-trend">غير مكتمل</div>
      </div>
    </div>
  </div>

  <!-- المخططات البيانية -->
  <div class="row g-4 mb-4">
    <!-- مخطط توزيع الطلاب حسب الدفعات -->
    <div class="col-md-6">
      <div class="chart-container">
        <div class="chart-title">
          <i class="fas fa-calendar-alt"></i>
          توزيع الطلاب حسب الدفعات
          <?php if (!empty($filter_college_id) || !empty($filter_section_id) || !empty($filter_program_id)): ?>
            <span class="badge bg-info text-white ms-2">مع تطبيق الفلتر</span>
          <?php endif; ?>
        </div>
        <div class="chart-wrapper">
          <canvas id="batchChart"></canvas>
        </div>
        <?php if (empty($byBatch)): ?>
          <div class="text-center text-muted py-4">
            <i class="fas fa-info-circle fa-2x mb-2"></i>
            <p>لا توجد بيانات للعرض</p>
            <small>تأكد من وجود دفعات نشطة وطلاب مسجلين</small>
          </div>
        <?php else: ?>
          <div class="chart-legend">
            <?php 
            $batchColors = ['#4f46e5', '#7c3aed', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#84cc16'];
            $i = 0;
            foreach (array_slice($byBatch, 0, 8) as $batch): 
            ?>
              <div class="legend-item">
                <div class="legend-color" style="background-color: <?= $batchColors[$i] ?>"></div>
                <span><?= htmlspecialchars($batch['name'] ?? '') ?>: <?= number_format($batch['total'] ?? 0) ?></span>
              </div>
            <?php 
              $i++;
            endforeach; 
            ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- مخطط توزيع الطلاب حسب الكليات -->
    <div class="col-md-6">
      <div class="chart-container">
        <div class="chart-title">
          <i class="fas fa-university"></i>
          توزيع الطلاب حسب الكليات
        </div>
        <div class="chart-wrapper">
          <canvas id="collegeChart"></canvas>
        </div>
        <?php if (empty($byCollege)): ?>
          <div class="text-center text-muted py-4">
            <i class="fas fa-info-circle fa-2x mb-2"></i>
            <p>لا توجد بيانات للعرض</p>
          </div>
        <?php else: ?>
          <div class="chart-legend">
            <?php 
            $collegeColors = ['#4f46e5', '#7c3aed', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#84cc16'];
            $i = 0;
            foreach (array_slice($byCollege, 0, 8) as $college): 
            ?>
              <div class="legend-item">
                <div class="legend-color" style="background-color: <?= $collegeColors[$i] ?>"></div>
                <span><?= htmlspecialchars(mb_substr($college['name'] ?? '', 0, 20)) ?>: <?= number_format($college['total'] ?? 0) ?></span>
              </div>
            <?php 
              $i++;
            endforeach; 
            ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

<!-- قسم الإعدادات الرئيسي -->
<div class="settings-section">
    <h5 class="text-white mb-4 fw-bold">
        <i class="fas fa-cogs me-2"></i>
        مركز الإعدادات والتحكم
    </h5>
    
    <!-- تبويبات التنقل بين أقسام الإعدادات -->
    <ul class="nav nav-tabs nav-fill mb-4" id="settingsTabs" role="tablist" style="border-bottom-color: rgba(255,255,255,0.2);">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab" aria-controls="system" aria-selected="true" style="background: linear-gradient(135deg, #6369d6f0, #dc829a); color: white; border: none; margin: 0 2px; border-radius: 30px;">
                <i class="fas fa-cogs me-2"></i>إعدادات النظام
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="fees-tab" data-bs-toggle="tab" data-bs-target="#fees" type="button" role="tab" aria-controls="fees" aria-selected="false" style="background: linear-gradient(135deg, #f6b023, #f28b20); color: white; border: none; margin: 0 2px; border-radius: 30px;">
                <i class="fas fa-money-bill-wave me-2"></i>إعدادات الرسوم
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="registration-tab" data-bs-toggle="tab" data-bs-target="#registration" type="button" role="tab" aria-controls="registration" aria-selected="false" style="background: linear-gradient(135deg, #3ca55c, #2a8c4a); color: white; border: none; margin: 0 2px; border-radius: 30px;">
                <i class="fas fa-calendar-alt me-2"></i>إدارة التسجيلات
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="students-tab" data-bs-toggle="tab" data-bs-target="#students" type="button" role="tab" aria-controls="students" aria-selected="false" style="background: linear-gradient(135deg, #4facfe, #00bcd4); color: white; border: none; margin: 0 2px; border-radius: 30px;">
                <i class="fas fa-user-graduate me-2"></i>إدارة الطلاب
            </button>
        </li>
    </ul>

    <!-- محتوى التبويبات -->
    <div class="tab-content" id="settingsTabsContent">
        
        <!-- ========== تبويب إعدادات النظام ========== -->
        <div class="tab-pane fade show active" id="system" role="tabpanel" aria-labelledby="system-tab">
            <div class="row">
                <!-- بطاقة إعدادات المستخدمين -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #3b82f6;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #3b82f6, #1e40af); color: white; box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);">
                            <i class="fas fa-users-cog"></i>
                        </div>
                        <h6 style="color: #1e3a8a;">إعدادات المستخدمين</h6>
                        <p style="color: #4b5563;">إدارة صلاحيات وحسابات المستخدمين </p>
                        <a href="user_control.php" class="btn w-100" style="background: linear-gradient(135deg, #3b82f6, #1e40af); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إدارة المستخدمين
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إعدادات الأقسام -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #c40da6;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #c40da6, #c40da6); color: white; box-shadow: 0 10px 20px rgba(233, 60, 186, 0.3);">
                            <i class="fas fa-university"></i>
                        </div>
                        <h6 style="color: #c40da6;">الأقسام</h6>
                        <p style="color: #4b5563;">  إضافة وتعديل وحذف الأقسام  </p>
                        <a href="sections.php" class="btn w-100" style="background: linear-gradient(135deg, #c40da6, #c40da6); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إدارة الأقسام
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إدارة التخصصات -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #7e22ce;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #9333ea, #6b21a5); color: white; box-shadow: 0 10px 20px rgba(147, 51, 234, 0.3);">
                            <i class="fas fa-tags"></i>
                        </div>
                        <h6 style="color: #581c87;">إدارة التخصصات</h6>
                        <p style="color: #4b5563;">إضافة وتعديل وحذف التخصصات الأكاديمية</p>
                        <a href="manage-specializations.php" class="btn w-100" style="background: linear-gradient(135deg, #9333ea, #6b21a5); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إدارة التخصصات
                        </a>
                    </div>
                </div>
            </div>
            
            <div class="row mt-2">
                <!-- بطاقة إعدادات الدفعات -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #06b6d4;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #06b6d4, #0891b2); color: white; box-shadow: 0 10px 20px rgba(6, 182, 212, 0.3);">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <h6 style="color: #155e75;">إدارة الدفعات</h6>
                        <p style="color: #4b5563;">إضافة وتعديل الدفعات الدراسية</p>
                        <a href="batches.php" class="btn w-100" style="background: linear-gradient(135deg, #06b6d4, #0891b2); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إدارة الدفعات
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إعدادات المقررات الدراسية -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #059669;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #10b981, #047857); color: white; box-shadow: 0 10px 20px rgba(16, 185, 129, 0.3);">
                            <i class="fas fa-door-open"></i>
                        </div>
                        <h6 style="color: #065f46;">المقررات الدراسية</h6>
                        <p style="color: #4b5563;">إدارة المقررات الدراسية</p>
                        <a href="courses_management.php" class="btn w-100" style="background: linear-gradient(135deg, #10b981, #047857); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إدارة القبول
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إعدادات النظام العامة -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #4b5563;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #6b7280, #374151); color: white; box-shadow: 0 10px 20px rgba(75, 85, 99, 0.3);">
                            <i class="fas fa-sliders-h"></i>
                        </div>
                        <h6 style="color: #1f2937;">إعدادات عامة</h6>
                        <p style="color: #4b5563;">إعدادات النظام الأساسية والتكوين</p>
                        <a href="#" class="btn w-100" style="background: linear-gradient(135deg, #6b7280, #374151); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> الإعدادات العامة
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- ========== تبويب إعدادات الرسوم ========== -->
        <div class="tab-pane fade" id="fees" role="tabpanel" aria-labelledby="fees-tab">
            <div class="row">
                <!-- بطاقة إعدادات الرسوم الأساسية -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #059669;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #10b981, #047857); color: white; box-shadow: 0 10px 20px rgba(16, 185, 129, 0.3);">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <h6 style="color: #065f46;">إعدادات الرسوم الأساسية</h6>
                        <p style="color: #4b5563;">تعديل وتعيين رسوم التسجيل حسب التصنيفات</p>
                        <a href="generalsetting.php" class="btn w-100" style="background: linear-gradient(135deg, #10b981, #047857); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إعدادات الرسوم
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة تعديل رسوم مؤقت -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #ea580c;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #f97316, #c2410c); color: white; box-shadow: 0 10px 20px rgba(249, 115, 22, 0.3);">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h6 style="color: #9a3412;">تعديل رسوم مؤقت</h6>
                        <p style="color: #4b5563;">تعديل رسوم طالب بشكل مؤقت (خصومات مؤقتة)</p>
                        <a href="fee_discounts.php" class="btn w-100" style="background: linear-gradient(135deg, #f97316, #c2410c); color: white; border: none;">
                            <i class="fas fa-clock me-1"></i> تعديل مؤقت
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة تعديل رسوم دائم -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #b91c1c;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #b91c1c, #7f1d1d); color: white; box-shadow: 0 10px 20px rgba(185, 28, 28, 0.3);">
                            <i class="fas fa-lock"></i>
                        </div>
                        <h6 style="color: #7f1d1d;">تعديل رسوم دائم</h6>
                        <p style="color: #4b5563;">تعديل رسوم طالب بشكل دائم</p>
                        <a href="fees_management.php" class="btn w-100" style="background: linear-gradient(135deg, #b91c1c, #7f1d1d); color: white; border: none;">
                            <i class="fas fa-lock me-1"></i> تعديل دائم
                        </a>
                    </div>
                </div>
            </div>
            
            <div class="row mt-2">
         
                
            
            </div>
        </div>
        
        <!-- ========== تبويب إدارة التسجيلات ========== -->
        <div class="tab-pane fade" id="registration" role="tabpanel" aria-labelledby="registration-tab">
            <div class="row">
                <!-- بطاقة إدارة تسجيلات الطلاب -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #8b5cf6;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #a78bfa, #7c3aed); color: white; box-shadow: 0 10px 20px rgba(139, 92, 246, 0.3);">
                            <i class="fas fa-user-graduate"></i>
                        </div>
                        <h6 style="color: #5b21b6;">إدارة تسجيلات الطلاب</h6>
                        <p style="color: #4b5563;">إدارة تسجيلات الطلاب والإجراءات</p>
                        <a href="registration_management.php" class="btn w-100" style="background: linear-gradient(135deg, #a78bfa, #7c3aed); color: white; border: none;">
                            <i class="fas fa-cog me-1"></i> إدارة التسجيلات
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة تمديد فترات التسجيل -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #14b8a6;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #2dd4bf, #0d9488); color: white; box-shadow: 0 10px 20px rgba(20, 184, 166, 0.3);">
                            <i class="fas fa-calendar-plus"></i>
                        </div>
                        <h6 style="color: #115e59;">تمديد فترات التسجيل</h6>
                        <p style="color: #4b5563;">تمديد فترة التسجيل للطلاب غير المدفوعة</p>
                        <a href="extend_registration.php" class="btn w-100" style="background: linear-gradient(135deg, #2dd4bf, #0d9488); color: white; border: none;">
                            <i class="fas fa-calendar-alt me-1"></i> تمديد التسجيل
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إلغاء تسجيلات الطلاب -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #ec4899;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #f472b6, #db2777); color: white; box-shadow: 0 10px 20px rgba(236, 72, 153, 0.3);">
                            <i class="fas fa-user-minus"></i>
                        </div>
                        <h6 style="color: #9d174d;">إلغاء تسجيلات الطلاب</h6>
                        <p style="color: #4b5563;">إلغاء تسجيل الطلاب بعد التسجيل</p>
                        <a href="deregistration.php" class="btn w-100" style="background: linear-gradient(135deg, #f472b6, #db2777); color: white; border: none;">
                            <i class="fas fa-ban me-1"></i> إلغاء التسجيل
                        </a>
                    </div>
                </div>
            </div>
            
            <div class="row mt-2">
                <!-- بطاقة إيقاف التسجيل -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #b91c1c;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #ef4444, #b91c1c); color: white; box-shadow: 0 10px 20px rgba(185, 28, 28, 0.3);">
                            <i class="fas fa-stop-circle"></i>
                        </div>
                        <h6 style="color: #7f1d1d;">إيقاف التسجيل</h6>
                        <p style="color: #4b5563;">تحديد تاريخ نهاية للتسجيلات النشطة</p>
                        <a href="stop_registration.php" class="btn w-100" style="background: linear-gradient(135deg, #ef4444, #b91c1c); color: white; border: none;">
                            <i class="fas fa-calendar-times me-1"></i> إيقاف التسجيل
                        </a>
                    </div>
                </div>
                
             
            </div>
        </div>
        
        <!-- ========== تبويب إدارة الطلاب ========== -->
        <div class="tab-pane fade" id="students" role="tabpanel" aria-labelledby="students-tab">
            <div class="row">
                <!-- بطاقة إضافة طالب -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #0ea5e9;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #38bdf8, #0284c7); color: white; box-shadow: 0 10px 20px rgba(14, 165, 233, 0.3);">
                            <i class="fas fa-user-plus"></i>
                        </div>
                        <h6 style="color: #0369a1;">إضافة طالب</h6>
                        <p style="color: #4b5563;">إضافة طالب جديد يدويًا إلى النظام</p>
                        <a href="add-student.php" class="btn w-100" style="background: linear-gradient(135deg, #38bdf8, #0284c7); color: white; border: none;">
                            <i class="fas fa-plus me-1"></i> إضافة طالب
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة استيراد طلاب -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #10b981;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #34d399, #059669); color: white; box-shadow: 0 10px 20px rgba(16, 185, 129, 0.3);">
                            <i class="fas fa-file-import"></i>
                        </div>
                        <h6 style="color: #065f46;">استيراد طلاب</h6>
                        <p style="color: #4b5563;">استيراد بيانات الطلاب من ملف Excel</p>
                        <a href="#" class="btn w-100" style="background: linear-gradient(135deg, #34d399, #059669); color: white; border: none;">
                            <i class="fas fa-upload me-1"></i> استيراد
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة تصدير بيانات -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #f97316;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #fb923c, #ea580c); color: white; box-shadow: 0 10px 20px rgba(249, 115, 22, 0.3);">
                            <i class="fas fa-file-export"></i>
                        </div>
                        <h6 style="color: #9a3412;">تصدير البيانات</h6>
                        <p style="color: #4b5563;">تصدير بيانات الطلاب والتقارير</p>
                        <a href="#" class="btn w-100" style="background: linear-gradient(135deg, #fb923c, #ea580c); color: white; border: none;">
                            <i class="fas fa-download me-1"></i> تصدير
                        </a>
                    </div>
                </div>
            </div>
            
            <div class="row mt-2">
                <!-- بطاقة بحث متقدم -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #6366f1;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #818cf8, #4f46e5); color: white; box-shadow: 0 10px 20px rgba(99, 102, 241, 0.3);">
                            <i class="fas fa-search"></i>
                        </div>
                        <h6 style="color: #3730a3;">بحث متقدم</h6>
                        <p style="color: #4b5563;">بحث متقدم في بيانات الطلاب</p>
                        <a href="#" class="btn w-100" style="background: linear-gradient(135deg, #818cf8, #4f46e5); color: white; border: none;">
                            <i class="fas fa-search me-1"></i> بحث متقدم
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إدارة الحالات الطبية -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #ef4444;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #f87171, #dc2626); color: white; box-shadow: 0 10px 20px rgba(239, 68, 68, 0.3);">
                            <i class="fas fa-heartbeat"></i>
                        </div>
                        <h6 style="color: #b91c1c;">إدارة الحالات الطبية</h6>
                        <p style="color: #4b5563;">تحديث الحالات الطبية للطلاب</p>
                        <a href="#" class="btn w-100" style="background: linear-gradient(135deg, #f87171, #dc2626); color: white; border: none;">
                            <i class="fas fa-heart me-1"></i> إدارة الحالات
                        </a>
                    </div>
                </div>
                
                <!-- بطاقة إدارة نتائج المقابلات -->
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="settings-card" style="border-top: 4px solid #d946ef;">
                        <div class="settings-icon" style="background: linear-gradient(135deg, #e879f9, #c026d3); color: white; box-shadow: 0 10px 20px rgba(217, 70, 239, 0.3);">
                            <i class="fas fa-comments"></i>
                        </div>
                        <h6 style="color: #a21caf;">إدارة المقابلات</h6>
                        <p style="color: #4b5563;">إدارة نتائج المقابلات الشخصية</p>
                        <a href="#" class="btn w-100" style="background: linear-gradient(135deg, #e879f9, #c026d3); color: white; border: none;">
                            <i class="fas fa-comment me-1"></i> إدارة المقابلات
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- تحسينات CSS إضافية -->
<style>
/* تحسينات إضافية للبطاقات */
.settings-card {
    background: white;
    border-radius: 16px;
    padding: 22px;
    text-align: center;
    box-shadow: 0 10px 25px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
    height: 100%;
    position: relative;
    overflow: hidden;
    border: none;
}

.settings-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 20px 35px rgba(0,0,0,0.12);
}

.settings-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(to right, transparent, rgba(255,255,255,0.5), transparent);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.settings-card:hover::before {
    opacity: 1;
}

.settings-icon {
    font-size: 2.2rem;
    width: 70px;
    height: 70px;
    line-height: 70px;
    border-radius: 50%;
    margin: 0 auto 20px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.settings-card:hover .settings-icon {
    transform: scale(1.1) rotate(5deg);
}

.settings-card h6 {
    font-weight: 800;
    margin-bottom: 12px;
    font-size: 1.1rem;
    transition: color 0.3s ease;
}

.settings-card p {
    color: #64748b;
    font-size: 0.9rem;
    line-height: 1.6;
    margin-bottom: 25px;
    min-height: 48px;
}

.settings-card .btn {
    border-radius: 50px;
    padding: 10px 20px;
    font-weight: 600;
    font-size: 0.95rem;
    transition: all 0.3s ease;
    border: none;
    position: relative;
    overflow: hidden;
}

.settings-card .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.15);
}

.settings-card .btn::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    border-radius: 50%;
    background: rgba(255,255,255,0.2);
    transform: translate(-50%, -50%);
    transition: width 0.6s, height 0.6s;
}

.settings-card .btn:hover::after {
    width: 300px;
    height: 300px;
}

/* تحسين التبويبات */
.nav-tabs .nav-link {
    border-radius: 50px !important;
    padding: 12px 25px !important;
    font-weight: 700 !important;
    font-size: 1rem !important;
    transition: all 0.3s ease !important;
    opacity: 0.9;
}

.nav-tabs .nav-link:hover {
    opacity: 1;
    transform: translateY(-2px);
    box-shadow: 0 8px 15px rgba(0,0,0,0.1);
}

.nav-tabs .nav-link.active {
    opacity: 1;
    transform: translateY(-3px);
    box-shadow: 0 12px 20px rgba(0,0,0,0.15);
}

/* عنوان القسم */
.settings-section h5 {
    font-size: 1.8rem;
    font-weight: 800;
    margin-bottom: 30px;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}

/* تحسين التجاوب مع الشاشات الصغيرة */
@media (max-width: 768px) {
    .settings-section h5 {
        font-size: 1.4rem;
    }
    
    .nav-tabs .nav-link {
        padding: 8px 15px !important;
        font-size: 0.85rem !important;
    }
    
    .settings-card {
        padding: 18px;
    }
    
    .settings-icon {
        width: 60px;
        height: 60px;
        font-size: 1.8rem;
    }
    
    .settings-card h6 {
        font-size: 1rem;
    }
    
    .settings-card p {
        font-size: 0.85rem;
        min-height: auto;
        margin-bottom: 20px;
    }
}
</style>

  <!-- بطاقات التقارير المحسنة -->
  <div class="dash-card mb-4">
    <h5 class="section-title">
      <i class="fas fa-file-alt me-2"></i>
      التقارير والإحصائيات المتقدمة
    </h5>
    
    <div class="row">
      <!-- تقارير التسجيل -->
      <div class="col-md-4 mb-3">
        <div class="report-card">
          <div class="report-icon">
            <i class="fas fa-user-check text-success"></i>
          </div>
          <div class="report-title">الطلاب المسجلين كاملاً</div>
          <div class="report-desc">جميع الرسوم مسددة  </div>
          <a href="reports/registeredstudents.php" class="btn btn-success w-100">
            <i class="fas fa-eye me-1"></i> عرض التقرير
          </a>
        </div>
      </div>
      
      <div class="col-md-4 mb-3">
        <div class="report-card">
          <div class="report-icon">
            <i class="fas fa-user-times text-danger"></i>
          </div>
          <div class="report-title">الطلاب غير المسجلين</div>
          <div class="report-desc">لم يسددوا أي رسوم حتى الآن</div>
          <a href="reports/unregisteredstudents.php" class="btn btn-danger w-100">
            <i class="fas fa-eye me-1"></i> عرض التقرير
          </a>
        </div>
      </div>
      
      <div class="col-md-4 mb-3">
        <div class="report-card">
          <div class="report-icon">
            <i class="fas fa-user-clock text-warning"></i>
          </div>
          <div class="report-title">مسجلين جزئياً</div>
          <div class="report-desc">سددوا بعض الرسوم فقط</div>
          <a href="reports/partiallyregistered.php" class="btn btn-warning w-100">
            <i class="fas fa-eye me-1"></i> عرض التقرير
          </a>
        </div>
      </div>
    </div>
    
    <div class="row">
      <!-- تقارير الحضور -->
      <div class="col-md-6 mb-3">
        <div class="report-card">
          <div class="report-icon">
            <i class="fas fa-chalkboard-teacher text-primary"></i>
          </div>
          <div class="report-title">حضور المحاضرات</div>
          <div class="report-desc">سجل الحضور اليومي والإحصاءات</div>
          <a href="reports/lectureattendance.php" class="btn btn-primary w-100">
            <i class="fas fa-chart-bar me-1"></i> عرض الإحصائيات
          </a>
        </div>
      </div>
      
      <div class="col-md-6 mb-3">
        <div class="report-card">
          <div class="report-icon">
            <i class="fas fa-file-signature text-info"></i>
          </div>
          <div class="report-title">حضور الامتحان</div>
          <div class="report-desc">نتائج وتوقيعات الطلاب في الامتحانات</div>
          <a href="reports/examattendance.php" class="btn btn-info w-100">
            <i class="fas fa-chart-pie me-1"></i> عرض النتائج
          </a>
        </div>
      </div>
    </div>
  </div>

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

    <div class="college-distribution">
      <?php 
      $topColleges = array_slice($byCollege, 0, 8);
      foreach ($topColleges as $college): 
        $percentage = $kpi['total'] > 0 ? ($college['total'] / $kpi['total']) * 100 : 0;
        $barColor = $percentage > 20 ? 'bg-success' : ($percentage > 10 ? 'bg-primary' : 'bg-info');
      ?>
        <div class="college-progress">
          <div class="college-name"><?= htmlspecialchars($college['name'] ?: 'كلية #' . $college['id']) ?></div>
          <div class="progress-container">
            <div class="progress">
              <div class="progress-bar <?= $barColor ?>" role="progressbar" 
                   style="width: <?= $percentage ?>%" 
                   aria-valuenow="<?= $percentage ?>" 
                   aria-valuemin="0" 
                   aria-valuemax="100">
                <span class="progress-text"><?= number_format($percentage, 1) ?>%</span>
              </div>
            </div>
          </div>
          <div class="college-count"><?= number_format($college['total']) ?></div>
        </div>
      <?php endforeach; ?>
    </div>
    
    <?php if (count($byCollege) > 8): ?>
      <div class="mt-3 text-center">
        <small class="text-muted">عرض <?= count($topColleges) ?> من <?= count($byCollege) ?> كلية</small>
      </div>
    <?php endif; ?>
  </div>

  <!-- التصفية -->
  <div class="filter-card">
    <div class="filter-header">
      <div class="filter-icon">
        <i class="fas fa-filter"></i>
      </div>
      <div>
        <h5 class="filter-title">تصفية التقارير</h5>
        <p class="text-muted mb-0 small">حدد معايير التصفية لعرض البيانات المطلوبة</p>
      </div>
    </div>

    <form method="get" class="row g-3" id="filterForm">
      <?php if ($canAll): ?>
      <div class="col-lg-2 col-md-4">
        <label class="form-label">الكلية</label>
        <select class="form-select" name="filter_college" id="filter_college" onchange="loadSections(this.value);">
          <option value="">-- الكل --</option>
          <?php
          $filter_colleges_sql = "SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name";
          $filter_colleges_result = $mysqli1->query($filter_colleges_sql);
          while ($college = $filter_colleges_result->fetch_assoc()) {
            $selected = (isset($_GET['filter_college']) && $_GET['filter_college'] == $college['id']) ? 'selected' : '';
            echo "<option value=\"" . (int)$college['id'] . "\" $selected>" . htmlspecialchars($college['name']) . "</option>";
          }
          ?>
        </select>
      </div>
      <?php else: ?>
        <input type="hidden" name="filter_college" value="<?= (int)$scopeCollege ?>">
      <?php endif; ?>
      
      <div class="col-lg-2 col-md-4">
        <label class="form-label">القسم</label>
        <select class="form-select" name="filter_section" id="filter_section" onchange="loadSpecializations()" <?= (!isset($_GET['filter_college']) || empty($_GET['filter_college'])) ? 'disabled' : '' ?>>
          <option value="">-- الكل --</option>
          <?php
          // فقط إذا كان هناك كلية محددة مسبقاً، نقوم بتحميل الأقسام
          if (isset($_GET['filter_college']) && !empty($_GET['filter_college'])) {
            $selected_college_id = (int)$_GET['filter_college'];
            $sections_sql = "SELECT id, name FROM sections WHERE parent = ? AND deleted_at IS NULL ORDER BY name";
            $sections_stmt = $mysqli1->prepare($sections_sql);
            $sections_stmt->bind_param("i", $selected_college_id);
            $sections_stmt->execute();
            $sections_result = $sections_stmt->get_result();
            while ($section = $sections_result->fetch_assoc()) {
              $selected = (isset($_GET['filter_section']) && $_GET['filter_section'] == $section['id']) ? 'selected' : '';
              echo "<option value=\"" . (int)$section['id'] . "\" $selected>" . htmlspecialchars($section['name']) . "</option>";
            }
            $sections_stmt->close();
          }
          ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-4">
        <label class="form-label">البرنامج</label>
        <select class="form-select" name="filter_program" id="filter_program" onchange="loadSpecializations()">
          <option value="">-- الكل --</option>
          <?php
          $filter_programs_sql = "SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name";
          $filter_programs_result = $mysqli1->query($filter_programs_sql);
          while ($program = $filter_programs_result->fetch_assoc()) {
            $selected = (isset($_GET['filter_program']) && $_GET['filter_program'] == $program['id']) ? 'selected' : '';
            echo "<option value=\"" . (int)$program['id'] . "\" $selected>" . htmlspecialchars($program['name']) . "</option>";
          }
          ?>
        </select>
      </div>

      <!-- حقل التخصص -->
      <?php if ($hasSpecializations): ?>
      <div class="col-lg-2 col-md-4">
        <label class="form-label">التخصص</label>
        <select class="form-select" name="filter_specialization" id="filter_specialization">
          <option value="">-- الكل --</option>
          <?php
          // إذا كان هناك قسم وبرنامج محددين مسبقاً، نحمل التخصصات المناسبة
          if (isset($_GET['filter_section']) && !empty($_GET['filter_section']) && 
              isset($_GET['filter_program']) && !empty($_GET['filter_program'])) {
            $spec_sql = "SELECT specialization_id, specialization_name_ar 
                         FROM specializations 
                         WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
                         ORDER BY specialization_name_ar";
            $spec_stmt = $mysqli1->prepare($spec_sql);
            $spec_stmt->bind_param("ii", $_GET['filter_section'], $_GET['filter_program']);
            $spec_stmt->execute();
            $spec_result = $spec_stmt->get_result();
            while ($spec = $spec_result->fetch_assoc()) {
              $selected = (isset($_GET['filter_specialization']) && $_GET['filter_specialization'] == $spec['specialization_id']) ? 'selected' : '';
              echo "<option value=\"" . (int)$spec['specialization_id'] . "\" $selected>" . htmlspecialchars($spec['specialization_name_ar']) . "</option>";
            }
            $spec_stmt->close();
          }
          ?>
        </select>
      </div>
      <?php endif; ?>
      
      <div class="col-lg-2 col-md-4">
        <label class="form-label">الدفعة</label>
        <select class="form-select" name="filter_batch">
          <option value="">-- الكل --</option>
          <?php
          // فقط الدفعات النشطة (status=1)
          $filter_batches_sql = "SELECT id, value FROM batches WHERE status = 1 AND deleted_at IS NULL ORDER BY value DESC";
          $filter_batches_result = $mysqli1->query($filter_batches_sql);
          while ($batch = $filter_batches_result->fetch_assoc()) {
            $selected = (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $batch['id']) ? 'selected' : '';
            echo "<option value=\"" . (int)$batch['id'] . "\" $selected>" . htmlspecialchars($batch['value']) . "</option>";
          }
          ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-4 d-flex align-items-end">
        <div class="d-flex gap-2 w-100">
          <button type="submit" class="btn btn-primary w-100">
            <i class="fas fa-filter me-1"></i>
            تصفية
          </button>
          <a href="admin_dashboard.php" class="btn btn-outline-secondary w-100">
            <i class="fas fa-sync-alt me-1"></i>
            إعادة
          </a>
        </div>
      </div>
    </form>
  </div>

  <!-- آخر الطلبات -->
  <div class="table-card">
    <div class="table-header">
      <div class="d-flex align-items-center justify-content-between">
        <h6 class="table-title">
          <i class="fas fa-history me-2"></i>
          آخر الطلبات المسجلة (آخر 20 طالب)
        </h6>
        
        <div class="d-flex align-items-center gap-2">
          <!-- البحث -->
          <form class="d-flex gap-2" method="get" style="max-width: 250px;">
            <?php foreach (['filter_college', 'filter_section', 'filter_program', 'filter_specialization', 'filter_batch', 'completed', 'medical'] as $param): ?>
              <?php if (isset($_GET[$param]) && $_GET[$param] !== ''): ?>
                <input type="hidden" name="<?= htmlspecialchars($param) ?>" value="<?= htmlspecialchars($_GET[$param]) ?>">
              <?php endif; ?>
            <?php endforeach; ?>
            
            <div class="input-group input-group-sm">
              <input type="text" class="form-control" name="q" 
                     placeholder="بحث..." 
                     value="<?= htmlspecialchars($q ?? '') ?>"
                     maxlength="100">
              <button class="btn btn-primary" type="submit">
                <i class="fas fa-search"></i>
              </button>
            </div>
          </form>
          
          <!-- فلتر إكمال الملف -->
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" 
                   id="completedSwitch" 
                   <?= $onlyCompleted ? 'checked' : '' ?>
                   onchange="window.location.href='?<?= http_build_query(array_merge($_GET, ['completed' => $onlyCompleted ? '0' : '1'])) ?>'">
            <label class="form-check-label" for="completedSwitch">
              الملفات المكتملة فقط
            </label>
          </div>
        </div>
      </div>
    </div>
    
    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th width="50">#</th>
            <th>الطالب</th>
            <th>الرقم الجامعي</th>
            <th>الكلية</th>
            <th>القسم</th>
            <th>البرنامج</th>
            <?php if ($hasSpecializations): ?>
            <th>التخصص</th>
            <?php endif; ?>
            <th>الدفعة</th>
            <th>حالة المقابلة</th>
            <th>الحالة الطبية</th>
            <th>الإجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($recentAccepted)): ?>
            <tr>
              <td colspan="<?= $hasSpecializations ? 11 : 10 ?>" class="text-center text-muted py-3">
                <i class="fas fa-users fa-lg mb-2 d-block"></i>
                لا توجد طلبات حديثة
              </td>
            </tr>
          <?php else: 
            $serial = 1;
            foreach ($recentAccepted as $r): 
          ?>
            <tr>
              <td class="text-center fw-bold text-primary">
                <?= $serial++ ?>
              </td>
              <td>
                <div class="fw-semibold"><?= htmlspecialchars($r['student_name'] ?: $r['student_name_eng'] ?: '—') ?></div>
              </td>
              <td>
                <code class="text-primary fw-bold"><?= htmlspecialchars($r['student_id']) ?></code>
              </td>
              <td><?= htmlspecialchars($r['college_name'] ?: $r['college_id']) ?></td>
              <td><?= htmlspecialchars($r['section_name'] ?: $r['section_id']) ?></td>
              <td><?= htmlspecialchars($r['program_name'] ?: $r['program_id']) ?></td>
              <?php if ($hasSpecializations): ?>
              <td><?= htmlspecialchars($r['specialization_name'] ?? '—') ?></td>
              <?php endif; ?>
              <td>
                <span class="badge bg-light text-dark"><?= htmlspecialchars($r['batch_name'] ?: $r['batch_id']) ?></span>
              </td>
              <td>
                <?php 
                $status = $r['current_status'] ?? 'pending';
                if ($status === 'accepted'): ?>
                  <span class="chip green">
                    <i class="fas fa-check-circle me-1"></i>مقبول
                  </span>
                <?php elseif ($status === 'rejected'): ?>
                  <span class="chip red">
                    <i class="fas fa-times-circle me-1"></i>مرفوض
                  </span>
                <?php else: ?>
                  <span class="chip gray">
                    <i class="fas fa-clock me-1"></i>قيد الانتظار
                  </span>
                <?php endif; ?>
              </td>
              <td>
                <?php 
                $medically_fit = $r['medically_fit'];
                if ($medically_fit == 1): ?>
                  <span class="chip green">
                    <i class="fas fa-heart me-1"></i>لائق
                  </span>
                <?php elseif ($medically_fit == 0): ?>
                  <span class="chip red">
                    <i class="fas fa-heart-broken me-1"></i>غير لائق
                  </span>
                <?php else: ?>
                  <span class="chip orange">
                    <i class="fas fa-clock me-1"></i>انتظار فحص
                  </span>
                <?php endif; ?>
              </td>
              <td>
                <div class="btn-group btn-group-sm" role="group">

                  <a class="btn btn-outline-info" 
                     href="student_profile_admin.php?student_id=<?= urlencode($r['student_id']) ?>"
                     title="الملف">
                    <i class="fas fa-file-alt"></i>
                  </a>
                </div>
              </td>
            </tr>
          <?php 
            endforeach; 
          endif; 
          ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
// دالة تحميل الأقسام بناءً على الكلية المحددة
function loadSections(collegeId) {
    const sectionSelect = document.getElementById('filter_section');
    
    if (!collegeId || collegeId === '') {
        sectionSelect.innerHTML = '<option value="">-- الكل --</option>';
        sectionSelect.disabled = true;
        return;
    }
    
    // إظهار رسالة التحميل
    sectionSelect.innerHTML = '<option value="">جاري التحميل...</option>';
    sectionSelect.disabled = false;
    
    // تحميل أقسام كلية محددة من مجلد ajax
    fetch(`ajax/get_sections.php?college_id=${encodeURIComponent(collegeId)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(sections => {
            sectionSelect.innerHTML = '<option value="">-- الكل --</option>';
            if (sections && sections.length > 0) {
                sections.forEach(section => {
                    sectionSelect.innerHTML += `<option value="${section.id}">${escapeHtml(section.name)}</option>`;
                });
            } else {
                sectionSelect.innerHTML = '<option value="">لا توجد أقسام</option>';
            }
            
            // بعد تحميل الأقسام، نحاول تحميل التخصصات إذا كان البرنامج محدداً
            const programId = document.getElementById('filter_program').value;
            if (programId && programId !== '') {
                loadSpecializations();
            }
        })
        .catch(error => {
            console.error('Error loading sections:', error);
            sectionSelect.innerHTML = '<option value="">-- الكل --</option>';
        });
}

// دالة تحميل التخصصات بناءً على القسم والبرنامج المحددين
function loadSpecializations() {
    <?php if (!$hasSpecializations): ?>
    return;
    <?php endif; ?>
    
    const sectionId = document.getElementById('filter_section').value;
    const programId = document.getElementById('filter_program').value;
    const specSelect = document.getElementById('filter_specialization');
    
    if (!sectionId || sectionId === '' || !programId || programId === '') {
        specSelect.innerHTML = '<option value="">-- الكل --</option>';
        return;
    }
    
    // إظهار رسالة التحميل
    specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
    
    // تحميل التخصصات حسب القسم والبرنامج
    fetch(`ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(specializations => {
            specSelect.innerHTML = '<option value="">-- الكل --</option>';
            if (specializations && specializations.length > 0) {
                specializations.forEach(spec => {
                    specSelect.innerHTML += `<option value="${spec.specialization_id}">${escapeHtml(spec.specialization_name_ar)}</option>`;
                });
            } else {
                specSelect.innerHTML = '<option value="">لا توجد تخصصات</option>';
            }
        })
        .catch(error => {
            console.error('Error loading specializations:', error);
            specSelect.innerHTML = '<option value="">-- الكل --</option>';
        });
}

// دالة مساعدة لـ HTML escaping في JavaScript
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// التهيئة عند تحميل الصفحة
document.addEventListener('DOMContentLoaded', function() {
    const collegeSelect = document.getElementById('filter_college');
    
    // إذا كان هناك كلية محددة مسبقاً، نقوم بتحميل الأقسام
    if (collegeSelect && collegeSelect.value) {
        loadSections(collegeSelect.value);
    }
    
    // تحميل التخصصات إذا كان القسم والبرنامج محددين مسبقاً
    const sectionId = document.getElementById('filter_section').value;
    const programId = document.getElementById('filter_program').value;
    if (sectionId && sectionId !== '' && programId && programId !== '') {
        setTimeout(() => {
            loadSpecializations();
        }, 500);
    }
});
</script>

<script>
// مخطط توزيع الطلاب حسب الدفعات
const batchCtx = document.getElementById('batchChart');
if (batchCtx) {
  <?php if (!empty($byBatch)): ?>
  const batchLabels = <?= json_encode(array_map(function($batch) { 
      return htmlspecialchars($batch['name'] ?? ''); 
  }, array_slice($byBatch, 0, 8))) ?>;
  
  const batchData = <?= json_encode(array_map(function($batch) { 
      return (int)($batch['total'] ?? 0); 
  }, array_slice($byBatch, 0, 8))) ?>;
  
  if (batchLabels.length > 0 && batchData.some(value => value > 0)) {
    new Chart(batchCtx, {
      type: 'bar',
      data: {
        labels: batchLabels,
        datasets: [{
          label: 'عدد الطلاب',
          data: batchData,
          backgroundColor: [
            'rgba(79, 70, 229, 0.8)',
            'rgba(124, 58, 237, 0.8)',
            'rgba(16, 185, 129, 0.8)',
            'rgba(245, 158, 11, 0.8)',
            'rgba(239, 68, 68, 0.8)',
            'rgba(139, 92, 246, 0.8)',
            'rgba(6, 182, 212, 0.8)',
            'rgba(132, 204, 22, 0.8)'
          ],
          borderColor: [
            'rgb(79, 70, 229)',
            'rgb(124, 58, 237)',
            'rgb(16, 185, 129)',
            'rgb(245, 158, 11)',
            'rgb(239, 68, 68)',
            'rgb(139, 92, 246)',
            'rgb(6, 182, 212)',
            'rgb(132, 204, 22)'
          ],
          borderWidth: 1,
          borderRadius: 6,
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              color: 'rgba(0,0,0,0.05)'
            }
          },
          x: {
            grid: {
              display: false
            }
          }
        }
      }
    });
  } else {
    batchCtx.style.display = 'none';
    batchCtx.parentElement.innerHTML += '<div class="text-center text-muted py-4"><i class="fas fa-info-circle fa-2x mb-2"></i><p>لا توجد بيانات كافية للرسم البياني</p></div>';
  }
  <?php else: ?>
  batchCtx.style.display = 'none';
  batchCtx.parentElement.innerHTML += '<div class="text-center text-muted py-4"><i class="fas fa-info-circle fa-2x mb-2"></i><p>لا توجد بيانات للعرض</p><small>تأكد من وجود دفعات نشطة وطلاب مسجلين</small></div>';
  <?php endif; ?>
}

// مخطط توزيع الطلاب حسب الكليات
const collegeCtx = document.getElementById('collegeChart');
if (collegeCtx) {
  <?php if (!empty($byCollege)): ?>
  const collegeLabels = <?= json_encode(array_map(function($college) { 
      return htmlspecialchars(mb_substr($college['name'] ?? '', 0, 20)); 
  }, array_slice($byCollege, 0, 8))) ?>;
  
  const collegeData = <?= json_encode(array_map(function($college) { 
      return (int)($college['total'] ?? 0); 
  }, array_slice($byCollege, 0, 8))) ?>;
  
  if (collegeLabels.length > 0 && collegeData.some(value => value > 0)) {
    new Chart(collegeCtx, {
      type: 'doughnut',
      data: {
        labels: collegeLabels,
        datasets: [{
          data: collegeData,
          backgroundColor: [
            'rgba(79, 70, 229, 0.8)',
            'rgba(124, 58, 237, 0.8)',
            'rgba(16, 185, 129, 0.8)',
            'rgba(245, 158, 11, 0.8)',
            'rgba(239, 68, 68, 0.8)',
            'rgba(139, 92, 246, 0.8)',
            'rgba(6, 182, 212, 0.8)',
            'rgba(132, 204, 22, 0.8)'
          ],
          borderColor: '#fff',
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '60%',
        plugins: {
          legend: {
            display: false
          }
        }
      }
    });
  } else {
    collegeCtx.style.display = 'none';
    collegeCtx.parentElement.innerHTML += '<div class="text-center text-muted py-4"><i class="fas fa-info-circle fa-2x mb-2"></i><p>لا توجد بيانات للعرض</p></div>';
  }
  <?php else: ?>
  collegeCtx.style.display = 'none';
  collegeCtx.parentElement.innerHTML += '<div class="text-center text-muted py-4"><i class="fas fa-info-circle fa-2x mb-2"></i><p>لا توجد بيانات للعرض</p></div>';
  <?php endif; ?>
}
</script>

<script>
// تفعيل التبويبات في قسم الإعدادات
document.addEventListener('DOMContentLoaded', function() {
    // تفعيل تبويبات Bootstrap
    var triggerTabList = [].slice.call(document.querySelectorAll('#settingsTabs button'));
    triggerTabList.forEach(function (triggerEl) {
        var tabTrigger = new bootstrap.Tab(triggerEl);
        triggerEl.addEventListener('click', function (event) {
            event.preventDefault();
            tabTrigger.show();
        });
    });
});
</script>

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