<?php
//student_affairs_dashboard.php
require 'db.php';
require 'helpers.php';
require_committee();

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

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

// إعدادات التصفية
$filter_college_id = $_GET['filter_college'] ?? null;
$filter_section_id = $_GET['filter_section'] ?? null;
$filter_program_id = $_GET['filter_program'] ?? null;
$filter_batch_id = $_GET['filter_batch'] ?? null;
$filter_semester_id = $_GET['filter_semester'] ?? null;

// جلب خيارات التصفية الأساسية
$colleges = $programs = $batches = $semesters = $sections = [];

try {
    // الكليات
    $colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
    $colleges_stmt->execute();
    $colleges = $colleges_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $colleges_stmt->close();
    
    // البرامج
    $programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
    
    // الدفعات
    $batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id");
    $batches_stmt->execute();
    $batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $batches_stmt->close();
    
    // الفصول الدراسية
    $semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
    $semesters_stmt->execute();
    $semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $semesters_stmt->close();
    
    // الأقسام (إذا كانت هناك كلية محددة)
    if ($filter_college_id && !empty($filter_college_id)) {
        $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", $filter_college_id);
        $sections_stmt->execute();
        $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $sections_stmt->close();
    }
    
} catch (Exception $e) {
    error_log("Error loading filter options: " . $e->getMessage());
}

// بناء WHERE بسيط
$where = " WHERE s.deleted_at IS NULL ";
$types = ''; 
$params = [];

// تحديد نطاق الكلية للجنة
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
    if (!$filter_college_id) {
        $filter_college_id = $scopeCollege;
    }
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 "; // لا يمكنه رؤية أي شيء
}

// تطبيق الفلاتر الأساسية
if ($filter_college_id && !empty($filter_college_id)) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $filter_college_id;
}

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

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

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

// ------ KPIs الأساسية ------
$sqlKpi = "
    SELECT
        COUNT(DISTINCT s.student_id) AS total,
        -- مسجلين كاملاً: جميع الدفعيات is_paid = 1
        COALESCE(SUM(CASE WHEN reg_status.status = 'paid' THEN 1 ELSE 0 END), 0) AS registered_paid,
        -- تسجيل غير مكتمل: بعض الدفعيات is_paid = 1 وبعضها is_paid = 0
        COALESCE(SUM(CASE WHEN reg_status.status = 'partial' THEN 1 ELSE 0 END), 0) AS registered_unpaid,
        -- غير مسجلين: جميع الدفعيات is_paid = 0 أو لا توجد دفعيات
        COALESCE(SUM(CASE WHEN reg_status.status IN ('not_paid', 'not_registered') THEN 1 ELSE 0 END), 0) AS not_registered,
        -- المبالغ المالية
        COALESCE(SUM(CASE WHEN reg_status.status = 'paid' THEN reg_status.total_paid_amount ELSE 0 END), 0) AS total_paid_amount,
        COALESCE(SUM(CASE WHEN reg_status.status = 'partial' THEN reg_status.total_unpaid_amount ELSE 0 END), 0) AS total_unpaid_amount,
        COALESCE(SUM(CASE WHEN reg_status.status IN ('not_paid', 'not_registered') THEN reg_status.total_unpaid_amount ELSE 0 END), 0) AS total_not_registered_amount,
        COALESCE(SUM(CASE WHEN reg_status.status = 'paid' THEN reg_status.total_fees ELSE 0 END), 0) AS total_paid_study_fees,
        COALESCE(SUM(CASE WHEN reg_status.status = 'partial' THEN reg_status.total_fees ELSE 0 END), 0) AS total_unpaid_study_fees,
        COALESCE(SUM(CASE WHEN reg_status.status IN ('not_paid', 'not_registered') THEN reg_status.total_fees ELSE 0 END), 0) AS total_not_registered_study_fees
    FROM students s
    LEFT JOIN (
        -- تحديد حالة التسجيل لكل طالب في الفصل المحدد
        SELECT 
            r.student_id,
            CASE 
                WHEN COUNT(r.id) = 0 THEN 'not_registered'        -- لا توجد دفعيات
                WHEN SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = COUNT(r.id) THEN 'not_paid'  -- جميع الدفعيات غير مدفوعة
                WHEN SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = 0 THEN 'paid'                -- جميع الدفعيات مدفوعة
                ELSE 'partial'  -- دفعيات جزئية
            END as status,
            SUM(CASE WHEN r.is_paid = 1 THEN r.payment_amount ELSE 0 END) as total_paid_amount,
            SUM(CASE WHEN r.is_paid = 0 THEN r.payment_amount ELSE 0 END) as total_unpaid_amount,
            SUM(r.study_fees) as total_fees
        FROM registrations r
        WHERE r.deleted_at IS NULL
";

// إضافة فلتر الفصل الدراسي للـ subquery
if ($filter_semester_id && !empty($filter_semester_id)) {
    $sqlKpi .= " AND r.semester_id = ? ";
}

$sqlKpi .= "        GROUP BY r.student_id
    ) reg_status ON reg_status.student_id = s.student_id
    $where
";

try {
    $st = $mysqli1->prepare($sqlKpi);
    
    $bindParams = [];
    $bindTypes = '';
    
    // معالجة بارامتر الفصل الدراسي للـ subquery
    if ($filter_semester_id && !empty($filter_semester_id)) {
        $bindTypes .= 'i';
        $bindParams[] = $filter_semester_id;
    }
    
    // معالجة بارامترات WHERE الأساسية
    if ($types) {
        $bindTypes .= $types;
        $bindParams = array_merge($bindParams, $params);
    }
    
    if ($bindTypes) {
        $st->bind_param($bindTypes, ...$bindParams);
    }
    
    $st->execute(); 
    $kpi = $st->get_result()->fetch_assoc(); 
    $st->close();
} catch (Exception $e) {
    error_log("KPI query error: " . $e->getMessage());
    $kpi = [
        'total' => 0,
        'registered_paid' => 0,
        'registered_unpaid' => 0,
        'not_registered' => 0,
        'total_paid_amount' => 0,
        'total_unpaid_amount' => 0,
        'total_not_registered_amount' => 0,
        'total_paid_study_fees' => 0,
        'total_unpaid_study_fees' => 0,
        'total_not_registered_study_fees' => 0
    ];
}

$kpi['total'] = (int)($kpi['total'] ?? 0);
$kpi['registered_paid'] = (int)($kpi['registered_paid'] ?? 0);
$kpi['registered_unpaid'] = (int)($kpi['registered_unpaid'] ?? 0);
$kpi['not_registered'] = (int)($kpi['not_registered'] ?? 0);
$kpi['total_paid_amount'] = (float)($kpi['total_paid_amount'] ?? 0);
$kpi['total_unpaid_amount'] = (float)($kpi['total_unpaid_amount'] ?? 0);
$kpi['total_not_registered_amount'] = (float)($kpi['total_not_registered_amount'] ?? 0);
$kpi['total_paid_study_fees'] = (float)($kpi['total_paid_study_fees'] ?? 0);
$kpi['total_unpaid_study_fees'] = (float)($kpi['total_unpaid_study_fees'] ?? 0);
$kpi['total_not_registered_study_fees'] = (float)($kpi['total_not_registered_study_fees'] ?? 0);

// ------ الطلاب الجدد ------
$q = trim((string)($_GET['q'] ?? ''));

// تحضير SQL لآخر الطلاب
$sqlRecent = "
    SELECT 
        s.student_id, 
        s.student_name, 
        s.student_name_eng, 
        c.name AS college_name,
        b.value AS batch_name,
        sem.name AS semester_name,
        sem.code AS semester_code,
        s.gender,
        COALESCE(reg_stats.last_registration_date, s.created_at) as registration_date,
        
        -- إحصائيات الدفعيات
        COALESCE(reg_stats.total_paid_amount, 0) as total_paid_amount,
        COALESCE(reg_stats.total_unpaid_amount, 0) as total_unpaid_amount,
        COALESCE(reg_stats.total_fees, 0) as total_fees,
        COALESCE(reg_stats.registration_status, 'غير مسجل') as registration_status,
        COALESCE(reg_stats.status_detail, 'not_registered') as status_detail
        
    FROM students s
    LEFT JOIN colleges c ON c.id = s.college_id
    LEFT JOIN batches b ON b.id = s.batch_id
    LEFT JOIN (
        -- تجميع إحصائيات التسجيل لكل طالب
        SELECT 
            r.student_id,
            r.semester_id,
            SUM(CASE WHEN r.is_paid = 1 THEN r.payment_amount ELSE 0 END) as total_paid_amount,
            SUM(CASE WHEN r.is_paid = 0 THEN r.payment_amount ELSE 0 END) as total_unpaid_amount,
            SUM(r.study_fees) as total_fees,
            CASE 
                WHEN COUNT(r.id) = 0 THEN 'غير مسجل'
                WHEN SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = COUNT(r.id) THEN 'غير مسجل'  -- جميع الدفعيات غير مدفوعة
                WHEN SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = 0 THEN 'مسجل كاملاً'           -- جميع الدفعيات مدفوعة
                ELSE 'تسجيل غير مكتمل'  -- دفعيات جزئية
            END as registration_status,
            CASE 
                WHEN COUNT(r.id) = 0 THEN 'not_registered'
                WHEN SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = COUNT(r.id) THEN 'not_paid'
                WHEN SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) = 0 THEN 'paid'
                ELSE 'partial'
            END as status_detail,
            MAX(r.created_at) as last_registration_date
        FROM registrations r
        WHERE r.deleted_at IS NULL
";

// إضافة فلتر الفصل الدراسي للـ subquery
if ($filter_semester_id && !empty($filter_semester_id)) {
    $sqlRecent .= " AND r.semester_id = ? ";
}

$sqlRecent .= "        GROUP BY r.student_id, r.semester_id
    ) reg_stats ON reg_stats.student_id = s.student_id
    LEFT JOIN semesters sem ON sem.id = " . (($filter_semester_id && !empty($filter_semester_id)) ? "?" : "COALESCE(reg_stats.semester_id, (SELECT id FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC LIMIT 1))") . "
    $where
";

// إضافة البحث إذا كان موجوداً
if ($q !== '') {
    $sqlRecent .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?) ";
}

$sqlRecent .= " ORDER BY COALESCE(reg_stats.last_registration_date, s.created_at) DESC LIMIT 15 ";

$recentAccepted = [];
try {
    $st = $mysqli1->prepare($sqlRecent);
    
    $bindParams = [];
    $bindTypes = '';
    
    // معالجة بارامتر الفصل الدراسي للـ subquery
    if ($filter_semester_id && !empty($filter_semester_id)) {
        $bindTypes .= 'i';
        $bindParams[] = $filter_semester_id;
        
        // إضافة بارامتر للـ JOIN مع semesters
        $bindTypes .= 'i';
        $bindParams[] = $filter_semester_id;
    }
    
    // معالجة بارامترات WHERE الأساسية
    if ($types) {
        $bindTypes .= $types;
        $bindParams = array_merge($bindParams, $params);
    }
    
    // معالجة بارامترات البحث
    if ($q !== '') {
        $kw = '%'.$q.'%';
        $bindTypes .= 'sss';
        $bindParams = array_merge($bindParams, [$kw,$kw,$kw]);
    }
    
    if ($bindTypes) {
        $st->bind_param($bindTypes, ...$bindParams);
    }
    
    $st->execute();
    $recentAccepted = $st->get_result()->fetch_all(MYSQLI_ASSOC);
    $st->close();
} catch (Exception $e) {
    error_log("Recent students query error: " . $e->getMessage());
}

// الحصول على أسماء الفلاتر للتحديث الديناميكي
$college_name = "";
$section_name = "";
$program_name = "";
$batch_name = "";
$semester_name = "";

if ($filter_college_id) {
    foreach ($colleges as $college) {
        if ($college['id'] == $filter_college_id) {
            $college_name = $college['name'];
            break;
        }
    }
}

if ($filter_section_id && !empty($sections)) {
    foreach ($sections as $section) {
        if ($section['id'] == $filter_section_id) {
            $section_name = $section['name'];
            break;
        }
    }
}

if ($filter_program_id) {
    foreach ($programs as $program) {
        if ($program['id'] == $filter_program_id) {
            $program_name = $program['name'];
            break;
        }
    }
}

if ($filter_batch_id) {
    foreach ($batches as $batch) {
        if ($batch['id'] == $filter_batch_id) {
            $batch_name = $batch['value'];
            break;
        }
    }
}

if ($filter_semester_id) {
    foreach ($semesters as $semester) {
        if ($semester['id'] == $filter_semester_id) {
            $semester_name = $semester['name'] . ' (' . $semester['code'] . ')';
            break;
        }
    }
}

/* ---------- UI ---------- */
include 'header.php';
?>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  body, h1,h2,h3,h4,h5,h6, p, a, button, label { font-family: 'Cairo', sans-serif !important; }
  .dash-card{border:1px solid #e5e7eb;border-radius:12px;padding:16px;background:#fff;box-shadow:0 4px 12px rgba(0,0,0,.08);margin-bottom:16px;}
  .kpi-stats{display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:12px;margin-bottom:20px;}
  .kpi-item{border-radius:10px;padding:15px;color:#fff;position:relative;overflow:hidden;}
  .kpi-item::before{content:'';position:absolute;top:0;right:0;width:60px;height:100%;background:rgba(255,255,255,.1);}
  .kpi-item .n{font-size:1.8rem;font-weight:800;margin-bottom:5px;}
  .kpi-item .label{font-size:.85rem;opacity:.9;}
  .filter-icon{width:36px;height:36px;background:#3b82f6;border-radius:8px;display:flex;align-items:center;justify-content:center;color:white;}
  .chip{display:inline-block;padding:3px 10px;border-radius:20px;font-size:.85rem;font-weight:500;}
  .chip.green{background:#d1fae5;color:#065f46;}
  .chip.gray{background:#e5e7eb;color:#1f2937;}
  .chip.blue{background:#dbeafe;color:#1e3a8a;}
  .chip.orange{background:#fed7aa;color:#9a3412;}
  .chip.purple{background:#e9d5ff;color:#7e22ce;}
  .chip.red{background:#fecaca;color:#991b1b;}
  .report-card{border-radius:10px;padding:12px;margin-bottom:12px;border:1px solid #e5e7eb;transition:all .2s;}
  .report-card:hover{transform:translateY(-2px);box-shadow:0 6px 16px rgba(0,0,0,.1);}
  .form-control-sm{font-size:.875rem;}
  .btn-sm{padding:.25rem .75rem;font-size:.875rem;}
  .table-sm{font-size:.875rem;}
  .badge{padding:.35em .65em;font-size:.75em;}
  .semester-badge {
    background-color: #e9d5ff;
    color: #7e22ce;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 500;
  }
  .filter-summary {
    background: #f8fafc;
    border-radius: 8px;
    padding: 10px;
    margin-top: 10px;
    border: 1px solid #e2e8f0;
  }
  .filter-summary-item {
    display: inline-block;
    margin-left: 8px;
    margin-bottom: 5px;
  }
  .filter-summary-badge {
    background: #dbeafe;
    color: #1e40af;
    padding: 3px 8px;
    border-radius: 6px;
    font-size: 0.8rem;
  }
  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #6b7280;
  }
  .empty-state i {
    font-size: 3rem;
    margin-bottom: 15px;
    color: #d1d5db;
  }
  .search-container {
    position: relative;
  }
  .search-clear {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: #6b7280;
    cursor: pointer;
    padding: 5px;
  }
  .status-info {
    font-size: 0.75rem;
    margin-top: 3px;
  }
  .section-loader {
    display: none;
    width: 16px;
    height: 16px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #2596be;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-left: 5px;
  }
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  .payment-details {
    font-size: 0.8rem;
    margin-top: 3px;
  }
  .payment-paid {
    color: #059669;
  }
  .payment-unpaid {
    color: #dc2626;
  }
  .payment-total {
    color: #1e40af;
    font-weight: 500;
  }
  .status-detail {
    font-size: 0.7rem;
    margin-top: 2px;
    opacity: 0.8;
  }
  .payment-zero {
    color: #6b7280;
    font-style: italic;
  }
</style>

<div class="container py-3" dir="rtl">
  <!-- بطاقات KPIs السريعة -->
  <div class="kpi-stats">
    <div class="kpi-item" style="background:linear-gradient(135deg,#3b82f6,#1d4ed8);">
      <div class="n"><?= number_format($kpi['total']) ?></div>
      <div class="label">إجمالي الطلاب</div>
      <?php if ($filter_semester_id && $semester_name): ?>
        <div class="label small">في الفصل: <?= e($semester_name) ?></div>
      <?php endif; ?>
      <?php if ($filter_batch_id && $batch_name): ?>
        <div class="label small">الدفعة: <?= e($batch_name) ?></div>
      <?php endif; ?>
    </div>
    <div class="kpi-item" style="background:linear-gradient(135deg,#10b981,#059669);">
      <div class="n"><?= number_format($kpi['registered_paid']) ?></div>
      <div class="label">مسجلين كاملاً</div>
      <div class="label small">(جميع الدفعيات مكتملة)</div>
      <?php if ($kpi['total'] > 0): ?>
        <div class="label small"><?= round(($kpi['registered_paid'] / $kpi['total']) * 100, 1) ?>%</div>
      <?php endif; ?>
      <?php if ($kpi['total_paid_amount'] > 0): ?>
        <div class="label small">مدفوعات: <?= number_format($kpi['total_paid_amount'], 0) ?></div>
      <?php endif; ?>
    </div>
    <div class="kpi-item" style="background:linear-gradient(135deg,#f59e0b,#d97706);">
      <div class="n"><?= number_format($kpi['registered_unpaid']) ?></div>
      <div class="label">تسجيل غير مكتمل</div>
      <div class="label small">(دفعيات جزئية)</div>
      <?php if ($kpi['total'] > 0): ?>
        <div class="label small"><?= round(($kpi['registered_unpaid'] / $kpi['total']) * 100, 1) ?>%</div>
      <?php endif; ?>
      <?php if ($kpi['total_unpaid_amount'] > 0): ?>
        <div class="label small">مستحقة: <?= number_format($kpi['total_unpaid_amount'], 0) ?></div>
      <?php endif; ?>
    </div>
    <div class="kpi-item" style="background:linear-gradient(135deg,#ef4444,#dc2626);">
      <div class="n"><?= number_format($kpi['not_registered']) ?></div>
      <div class="label">غير مسجلين</div>
      <div class="label small">(لا توجد دفعيات مدفوعة)</div>
      <?php if ($kpi['total'] > 0): ?>
        <div class="label small"><?= round(($kpi['not_registered'] / $kpi['total']) * 100, 1) ?>%</div>
      <?php endif; ?>
      <?php if ($kpi['total_not_registered_amount'] > 0): ?>
        <div class="label small">مستحقة: <?= number_format($kpi['total_not_registered_amount'], 0) ?></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- بطاقة التصفية المبسطة -->
  <div class="dash-card">
    <div class="d-flex align-items-center mb-3">
      <div class="filter-icon me-2">
        <i class="fas fa-filter"></i>
      </div>
      <h6 class="fw-bold mb-0">تصفية الطلاب</h6>
      <span class="badge bg-primary ms-2">
        <i class="fas fa-sliders-h me-1"></i>
        <?= ($filter_college_id || $filter_section_id || $filter_program_id || $filter_batch_id || $filter_semester_id) ? 'مفعل' : 'غير مفعل' ?>
      </span>
    </div>
    
    <form method="get" class="row g-2 align-items-end" id="filterForm">
      <div class="col-lg-2 col-md-6">
        <label class="form-label fw-semibold text-muted mb-1">
          <i class="fas fa-university me-1"></i> الكلية
        </label>
        <select class="form-control form-control-sm" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
          <option value="">جميع الكليات</option>
          <?php foreach ($colleges as $college): ?>
            <?php if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) continue; ?>
            <option value="<?= $college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
              <?= e($college['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-6">
        <label class="form-label fw-semibold text-muted mb-1">
          <i class="fas fa-layer-group me-1"></i> القسم
          <span class="section-loader" id="sectionLoader"></span>
        </label>
        <select class="form-control form-control-sm" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?>>
          <option value="">جميع الأقسام</option>
          <?php if ($filter_college_id && !empty($sections)): ?>
            <?php foreach ($sections as $section): ?>
              <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                <?= e($section['name']) ?>
              </option>
            <?php endforeach; ?>
          <?php endif; ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-6">
        <label class="form-label fw-semibold text-muted mb-1">
          <i class="fas fa-graduation-cap me-1"></i> البرنامج
        </label>
        <select class="form-control form-control-sm" name="filter_program" id="filter_program">
          <option value="">جميع البرامج</option>
          <?php foreach ($programs as $program): ?>
            <option value="<?= $program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
              <?= e($program['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-6">
        <label class="form-label fw-semibold text-muted mb-1">
          <i class="fas fa-users me-1"></i> الدفعة
        </label>
        <select class="form-control form-control-sm" name="filter_batch" id="filter_batch">
          <option value="">جميع الدفعات</option>
          <?php foreach ($batches as $batch): ?>
            <option value="<?= $batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
              <?= e($batch['value']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-6">
        <label class="form-label fw-semibold text-muted mb-1">
          <i class="fas fa-calendar-alt me-1"></i> الفصل الدراسي
        </label>
        <select class="form-control form-control-sm" name="filter_semester" id="filter_semester">
          <option value="">جميع الفصول</option>
          <?php foreach ($semesters as $semester): ?>
            <option value="<?= $semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
              <?= e($semester['name'] . ' (' . $semester['code'] . ')') ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      
      <div class="col-lg-2 col-md-6">
        <div class="d-flex gap-2">
          <button type="submit" class="btn btn-primary btn-sm flex-grow-1">
            <i class="fas fa-filter me-1"></i> تطبيق التصفية
          </button>
          <a href="student_affairs_dashboard.php" class="btn btn-outline-secondary btn-sm">
            <i class="fas fa-sync-alt"></i>
          </a>
        </div>
      </div>
    </form>
    
    <!-- ملخص الفلاتر المطبقة -->
    <?php if ($filter_college_id || $filter_section_id || $filter_program_id || $filter_batch_id || $filter_semester_id): ?>
    <div class="filter-summary mt-3">
      <div class="d-flex align-items-center mb-2">
        <i class="fas fa-info-circle text-primary me-2"></i>
        <small class="fw-semibold">الفلاتر المطبقة:</small>
      </div>
      <div>
        <?php if ($filter_college_id && $college_name): ?>
          <span class="filter-summary-item">
            <span class="filter-summary-badge">
              <i class="fas fa-university me-1"></i>كلية: <?= e($college_name) ?>
            </span>
          </span>
        <?php endif; ?>
        
        <?php if ($filter_section_id && $section_name): ?>
          <span class="filter-summary-item">
            <span class="filter-summary-badge">
              <i class="fas fa-layer-group me-1"></i>قسم: <?= e($section_name) ?>
            </span>
          </span>
        <?php endif; ?>
        
        <?php if ($filter_program_id && $program_name): ?>
          <span class="filter-summary-item">
            <span class="filter-summary-badge">
              <i class="fas fa-graduation-cap me-1"></i>برنامج: <?= e($program_name) ?>
            </span>
          </span>
        <?php endif; ?>
        
        <?php if ($filter_batch_id && $batch_name): ?>
          <span class="filter-summary-item">
            <span class="filter-summary-badge">
              <i class="fas fa-users me-1"></i>دفعة: <?= e($batch_name) ?>
            </span>
          </span>
        <?php endif; ?>
        
        <?php if ($filter_semester_id && $semester_name): ?>
          <span class="filter-summary-item">
            <span class="filter-summary-badge">
              <i class="fas fa-calendar-alt me-1"></i>فصل: <?= e($semester_name) ?>
            </span>
          </span>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>

  <!-- بطاقة التقارير السريعة -->
  <div class="dash-card">
    <h6 class="fw-bold mb-3">التقارير السريعة</h6>
    <div class="row g-2">
      <div class="col-md-3">
        <a href="reports/registered_students.php?<?= http_build_query([
          'filter_applied' => 1,
          'filter_college' => $filter_college_id,
          'filter_section' => $filter_section_id,
          'filter_program' => $filter_program_id,
          'filter_batch' => $filter_batch_id,
          'filter_semester' => $filter_semester_id
        ]) ?>" class="report-card text-decoration-none d-block">
          <div class="d-flex align-items-center">
            <div class="rounded-circle p-2 bg-success bg-opacity-10 text-success me-2">
              <i class="fas fa-check-circle"></i>
            </div>
            <div>
              <div class="fw-bold text-dark">المسجلين كاملاً</div>
              <small class="text-muted">جميع الدفعيات مكتملة</small>
              <?php if ($filter_semester_id): ?>
                <div class="text-muted small mt-1">(في الفصل الحالي)</div>
              <?php endif; ?>
            </div>
            <div class="ms-auto">
              <span class="badge bg-success"><?= number_format($kpi['registered_paid']) ?></span>
            </div>
          </div>
        </a>
      </div>
      <div class="col-md-3">
        <a href="reports/partially_registered.php?<?= http_build_query([
          'filter_applied' => 1,
          'filter_college' => $filter_college_id,
          'filter_section' => $filter_section_id,
          'filter_program' => $filter_program_id,
          'filter_batch' => $filter_batch_id,
          'filter_semester' => $filter_semester_id
        ]) ?>" class="report-card text-decoration-none d-block">
          <div class="d-flex align-items-center">
            <div class="rounded-circle p-2 bg-warning bg-opacity-10 text-warning me-2">
              <i class="fas fa-exclamation-circle"></i>
            </div>
            <div>
              <div class="fw-bold text-dark">تسجيل غير مكتمل</div>
              <small class="text-muted">دفعيات جزئية</small>
              <?php if ($filter_semester_id): ?>
                <div class="text-muted small mt-1">(في الفصل الحالي)</div>
              <?php endif; ?>
            </div>
            <div class="ms-auto">
              <span class="badge bg-warning"><?= number_format($kpi['registered_unpaid']) ?></span>
            </div>
          </div>
        </a>
      </div>
      <div class="col-md-3">
        <a href="reports/unregistered_students.php?<?= http_build_query([
          'filter_applied' => 1,
          'filter_college' => $filter_college_id,
          'filter_section' => $filter_section_id,
          'filter_program' => $filter_program_id,
          'filter_batch' => $filter_batch_id,
          'filter_semester' => $filter_semester_id
        ]) ?>" class="report-card text-decoration-none d-block">
          <div class="d-flex align-items-center">
            <div class="rounded-circle p-2 bg-danger bg-opacity-10 text-danger me-2">
              <i class="fas fa-times-circle"></i>
            </div>
            <div>
              <div class="fw-bold text-dark">غير المسجلين</div>
              <small class="text-muted">لا توجد دفعيات مدفوعة</small>
              <?php if ($filter_semester_id): ?>
                <div class="text-muted small mt-1">(في الفصل الحالي)</div>
              <?php endif; ?>
            </div>
            <div class="ms-auto">
              <span class="badge bg-danger"><?= number_format($kpi['not_registered']) ?></span>
            </div>
          </div>
        </a>
      </div>
      <div class="col-md-3">
        <a href="reports/payment_details.php?<?= http_build_query([
          'filter_applied' => 1,
          'filter_college' => $filter_college_id,
          'filter_section' => $filter_section_id,
          'filter_program' => $filter_program_id,
          'filter_batch' => $filter_batch_id,
          'filter_semester' => $filter_semester_id
        ]) ?>" class="report-card text-decoration-none d-block">
          <div class="d-flex align-items-center">
            <div class="rounded-circle p-2 bg-info bg-opacity-10 text-info me-2">
              <i class="fas fa-money-bill-wave"></i>
            </div>
            <div>
              <div class="fw-bold text-dark">تفاصيل المدفوعات</div>
              <small class="text-muted">ملخص المدفوعات</small>
              <?php if ($filter_semester_id): ?>
                <div class="text-muted small mt-1">(في الفصل الحالي)</div>
              <?php endif; ?>
            </div>
            <div class="ms-auto">
              <span class="badge bg-info"><?= number_format($kpi['total_paid_amount'] + $kpi['total_unpaid_amount'] + $kpi['total_not_registered_amount'], 0) ?></span>
            </div>
          </div>
        </a>
      </div>
    </div>
  </div>

  <!-- آخر الطلاب -->
  <div class="dash-card">
    <div class="d-flex align-items-center justify-content-between mb-3">
      <div>
        <h6 class="fw-bold mb-0">آخر الطلاب</h6>
        <?php if ($q || $filter_college_id || $filter_section_id || $filter_program_id || $filter_batch_id || $filter_semester_id): ?>
          <small class="text-muted">
            <i class="fas fa-info-circle me-1"></i>
            عرض <?= count($recentAccepted) ?> طالب
            <?php if ($q): ?> (نتائج بحث) <?php endif; ?>
            <?php if ($filter_batch_id && $batch_name): ?> | الدفعة: <?= e($batch_name) ?> <?php endif; ?>
            <?php if ($filter_semester_id && $semester_name): ?> | الفصل: <?= e($semester_name) ?> <?php endif; ?>
          </small>
        <?php endif; ?>
      </div>
      <form method="get" class="d-flex gap-2 align-items-center">
        <input type="hidden" name="filter_college" value="<?= e($filter_college_id ?? '') ?>">
        <input type="hidden" name="filter_section" value="<?= e($filter_section_id ?? '') ?>">
        <input type="hidden" name="filter_program" value="<?= e($filter_program_id ?? '') ?>">
        <input type="hidden" name="filter_batch" value="<?= e($filter_batch_id ?? '') ?>">
        <input type="hidden" name="filter_semester" value="<?= e($filter_semester_id ?? '') ?>">
        
        <div class="search-container position-relative">
          <input type="text" class="form-control form-control-sm ps-4" name="q" placeholder="بحث بالاسم أو الرقم الجامعي..." value="<?= e($q) ?>" id="searchInput">
          <?php if ($q): ?>
            <button type="button" class="search-clear" onclick="clearSearch()" title="مسح البحث">
              <i class="fas fa-times"></i>
            </button>
          <?php endif; ?>
        </div>
        
        <button class="btn btn-primary btn-sm" type="submit">
          <i class="fas fa-search"></i>
        </button>
      </form>
    </div>

    <div class="table-responsive">
      <table class="table table-sm table-hover">
        <thead class="table-light">
          <tr>
            <th>#</th>
            <th>الطالب</th>
            <th>الرقم الجامعي</th>
            <th>الكلية</th>
            <th>الدفعة</th>
            <th>الفصل الدراسي</th>
            <th>تاريخ التسجيل</th>
            <th>المبالغ المالية</th>
            <th>الحالة</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($recentAccepted)): ?>
            <tr>
              <td colspan="9" class="text-center py-4">
                <div class="empty-state">
                  <i class="fas fa-user-graduate"></i>
                  <h6 class="mt-2 mb-1">لا توجد نتائج</h6>
                  <p class="text-muted small mb-0">
                    <?php if ($q): ?>
                      لم يتم العثور على طلاب مطابقين للبحث "<?= e($q) ?>"
                    <?php else: ?>
                      لا توجد بيانات متاحة بناءً على عوامل التصفية المحددة
                      <?php if ($filter_batch_id && $batch_name): ?>
                        <br>الدفعة المحددة: <?= e($batch_name) ?>
                      <?php endif; ?>
                    <?php endif; ?>
                  </p>
                </div>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($recentAccepted as $index => $r): ?>
              <tr>
                <td class="text-muted"><?= $index + 1 ?></td>
                <td>
                  <div class="fw-semibold">
                    <?= e($r['student_name'] ?: $r['student_name_eng'] ?: '—') ?>
                  </div>
                  <?php if ($r['student_name'] && $r['student_name_eng']): ?>
                    <small class="text-muted d-block"><?= e($r['student_name_eng']) ?></small>
                  <?php endif; ?>
                </td>
                <td><code class="fw-bold"><?= e($r['student_id']) ?></code></td>
                <td>
                  <span class="badge bg-light text-dark">
                    <?= e($r['college_name'] ?: '—') ?>
                  </span>
                </td>
                <td>
                  <span class="badge bg-secondary">
                    <?= e($r['batch_name'] ?: '—') ?>
                  </span>
                </td>
                <td>
                  <?php if ($r['semester_name']): ?>
                    <span class="semester-badge">
                      <i class="fas fa-calendar me-1"></i>
                      <?= e($r['semester_name'] . ($r['semester_code'] ? ' (' . $r['semester_code'] . ')' : '')) ?>
                    </span>
                  <?php else: ?>
                    <span class="text-muted">—</span>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if ($r['registration_date']): ?>
                    <span class="text-nowrap">
                      <?= date('Y-m-d', strtotime($r['registration_date'])) ?>
                    </span>
                    <br>
                    <small class="text-muted">
                      <?= date('H:i', strtotime($r['registration_date'])) ?>
                    </small>
                  <?php else: ?>
                    <span class="text-muted">—</span>
                  <?php endif; ?>
                </td>
                <td>
                  <?php 
                  $total_paid = (float)($r['total_paid_amount'] ?? 0);
                  $total_unpaid = (float)($r['total_unpaid_amount'] ?? 0);
                  $total_fees = (float)($r['total_fees'] ?? 0);
                  $status_detail = $r['status_detail'] ?? 'not_registered';
                  ?>
                  
                  <?php if ($total_paid > 0): ?>
                    <div class="fw-bold payment-paid">
                      <?= number_format($total_paid, 0) ?>
                      <small class="d-block">مدفوعة</small>
                    </div>
                  <?php endif; ?>
                  
                  <?php if ($total_unpaid > 0): ?>
                    <div class="fw-bold payment-unpaid">
                      <?= number_format($total_unpaid, 0) ?>
                      <small class="d-block">غير مدفوعة</small>
                    </div>
                  <?php endif; ?>
                  
                  <?php if ($total_fees > 0): ?>
                    <div class="payment-details payment-total">
                      <small>إجمالي الرسوم: <?= number_format($total_fees, 0) ?></small>
                    </div>
                  <?php elseif ($status_detail === 'not_registered'): ?>
                    <div class="payment-zero small">
                      لا توجد رسوم
                    </div>
                  <?php endif; ?>
                </td>
                <td>
                  <?php 
                  $status = $r['registration_status'] ?? 'غير مسجل';
                  $status_detail = $r['status_detail'] ?? 'not_registered';
                  
                  // تحديد لون الحالة
                  if ($status_detail === 'paid') {
                      $class = 'chip green';
                  } elseif ($status_detail === 'partial') {
                      $class = 'chip orange';
                  } else {
                      $class = 'chip gray'; // not_registered أو not_paid
                  }
                  ?>
                  
                  <span class="<?= $class ?>">
                    <i class="fas fa-circle me-1" style="font-size: 0.5rem;"></i>
                    <?= e($status) ?>
                  </span>
                  
                  <?php if ($status_detail === 'partial'): ?>
                    <div class="status-info text-warning">
                      <i class="fas fa-exclamation-triangle me-1"></i>
                      دفعيات جزئية
                    </div>
                  <?php elseif ($status_detail === 'not_paid'): ?>
                    <div class="status-info text-danger">
                      <i class="fas fa-times me-1"></i>
                      جميع الدفعيات غير مدفوعة
                    </div>
                  <?php endif; ?>
                  
                  <?php if ($total_paid > 0 && $total_fees > 0): ?>
                    <div class="status-detail">
                      <?= round(($total_paid / $total_fees) * 100, 1) ?>% مكتمل
                    </div>
                  <?php elseif ($status_detail === 'not_paid' && $total_fees > 0): ?>
                    <div class="status-detail">
                      0% مكتمل
                    </div>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    
    <?php if (!empty($recentAccepted)): ?>
      <div class="mt-3 text-center">
        <small class="text-muted">
          <i class="fas fa-info-circle me-1"></i>
          عرض <?= count($recentAccepted) ?> من أصل <?= number_format($kpi['total']) ?> طالب
          <?php if ($filter_semester_id && $semester_name): ?>
            | الفصل الدراسي: <?= e($semester_name) ?>
          <?php endif; ?>
          <?php if ($filter_batch_id && $batch_name): ?>
            | الدفعة: <?= e($batch_name) ?>
          <?php endif; ?>
        </small>
      </div>
    <?php endif; ?>
  </div>
</div>

<script>
// cache للأقسام
let sectionsCache = {};

function loadSections(collegeId) {
    const sectionSelect = document.getElementById('filter_section');
    const sectionLoader = document.getElementById('sectionLoader');
    
    if (!collegeId || collegeId === '') {
        sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
        sectionSelect.disabled = true;
        return;
    }
    
    // التحقق من الـ cache
    if (sectionsCache[collegeId]) {
        populateSections(sectionsCache[collegeId], sectionSelect);
        sectionSelect.disabled = false;
        return;
    }
    
    // إظهار مؤشر التحميل
    sectionLoader.style.display = 'inline-block';
    sectionSelect.disabled = true;
    sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
    
    // طلب AJAX لجلب الأقسام من المجلد ajax
    fetch(`ajax/get_sections.php?college_id=${collegeId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            sectionsCache[collegeId] = data || [];
            populateSections(sectionsCache[collegeId], sectionSelect);
            sectionSelect.disabled = false;
            sectionLoader.style.display = 'none';
        })
        .catch(error => {
            console.error('Error loading sections:', error);
            sectionSelect.innerHTML = '<option value="">خطأ في التحميل</option>';
            sectionSelect.disabled = false;
            sectionLoader.style.display = 'none';
        });
}

function populateSections(sections, selectElement) {
    selectElement.innerHTML = '<option value="">جميع الأقسام</option>';
    
    if (sections && sections.length > 0) {
        sections.forEach(section => {
            const option = document.createElement('option');
            option.value = section.id;
            option.textContent = section.name;
            selectElement.appendChild(option);
        });
    } else {
        selectElement.innerHTML = '<option value="">لا توجد أقسام</option>';
    }
}

// تحسين البحث
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.form.submit();
            }, 500);
        });
        
        searchInput.focus();
    }
    
    // تحميل الأقسام عند تحميل الصفحة إذا كانت الكلية محددة
    const collegeId = "<?= $filter_college_id ?>";
    if (collegeId && collegeId !== '') {
        // استخدام setTimeout لإعطاء الوقت لتحميل DOM أولاً
        setTimeout(() => {
            loadSections(collegeId);
        }, 100);
    }
});

// دالة لمسح البحث
function clearSearch() {
    const searchInput = document.getElementById('searchInput');
    searchInput.value = '';
    searchInput.form.submit();
}
</script>

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