<?php
session_start();
include 'db.php';

/* ✅ تقييد الصفحة على الأدمن فقط */
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

mysqli_set_charset($conn, "utf8mb4");

/*
  ✅ إذا تريد تشخيص أي خطأ بدل 500 (اختياري مؤقت)
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
*/

/* =========================
   أدوات مساعدة
   ========================= */
function esc($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

function top3_avg_admin($arr) {
    $clean = array();
    foreach ($arr as $v) { $clean[] = floatval($v); }
    rsort($clean);
    $top3 = array_slice($clean, 0, 3);
    $sum  = array_sum($top3);
    $count = count($top3) > 0 ? count($top3) : 1;
    return round($sum / $count, 2);
}
function round_half_up_int($v) {
    $v = (float)$v;
    $i = floor($v);
    return ($v - $i >= 0.5) ? $i + 1 : $i;
}
function clamp_grade($v){
    if ($v === null) return null;
    $v = trim((string)$v);
    if ($v === '') return null;
    $n = floatval($v);
    if ($n < 0) $n = 0;
    if ($n > 100) $n = 100;
    return $n;
}
function sql_num_or_null($v){
    if ($v === null || $v === '') return "NULL";
    if (!is_numeric($v)) return "NULL";
    return (string)floatval($v);
}
function csv_escape($v){
    $v = (string)$v;
    $v = str_replace('"', '""', $v);
    return '"' . $v . '"';
}

/* ✅ أهم تعديل: جلب مواد المرحلة بدون mysqli_stmt_get_result (متوافق مع الاستضافات القديمة) */
function fetch_subjects_by_stage($conn, $stage){
    $subjects = array();

    $stmt = mysqli_prepare($conn, "SELECT DISTINCT name FROM subjects WHERE stage = ? ORDER BY id ASC");
    if (!$stmt) return $subjects;

    mysqli_stmt_bind_param($stmt, "s", $stage);
    mysqli_stmt_execute($stmt);

    mysqli_stmt_bind_result($stmt, $name);
    while (mysqli_stmt_fetch($stmt)) {
        if ($name !== null && $name !== '') $subjects[] = $name;
    }
    mysqli_stmt_close($stmt);

    return $subjects;
}

/* =========================
   فلاتر GET
   ========================= */
$filter_stage = isset($_GET['stage']) ? trim($_GET['stage']) : '';
$filter_class = isset($_GET['class']) ? trim($_GET['class']) : '';
$search_name  = isset($_GET['q']) ? trim($_GET['q']) : '';

/* =========================
   Export: Excel / PDF(print)
   ========================= */
function build_export_url($export){
    $params = $_GET;
    $params['export'] = $export;
    return '?' . http_build_query($params);
}

function get_listeners_where_sql($conn, $filter_stage, $filter_class, $search_name){
    $where = " WHERE 1 ";
    if ($filter_stage !== '') {
        $stage_esc = mysqli_real_escape_string($conn, $filter_stage);
        $where .= " AND ls.stage = '".$stage_esc."' ";
    }
    if ($filter_class !== '') {
        $class_esc = mysqli_real_escape_string($conn, $filter_class);
        $where .= " AND ls.class = '".$class_esc."' ";
    }
    if ($search_name !== '') {
        $q_esc = mysqli_real_escape_string($conn, $search_name);
        $where .= " AND ls.name LIKE '%".$q_esc."%' ";
    }
    return $where;
}

function export_excel($conn, $filter_stage, $filter_class, $search_name){
    $where = get_listeners_where_sql($conn, $filter_stage, $filter_class, $search_name);

    header("Content-Type: text/csv; charset=UTF-8");
    header("Content-Disposition: attachment; filename=listener_grades_" . date('Y-m-d_H-i') . ".csv");

    // BOM for Excel Arabic
    echo "\xEF\xBB\xBF";

    $headers = array(
        'اسم الطالب','المرحلة','الشعبة','المادة',
        'ش1','ش2','ش3','يومي1','فصل أول','نصف السنة',
        'ش4','ش5','ش6','يومي2','فصل ثاني',
        'معدل سنوي','النهائي','آخر حفظ'
    );
    $line = array();
    foreach ($headers as $h) $line[] = csv_escape($h);
    echo implode(',', $line) . "\n";

    $sql = "SELECT ls.id AS listener_id, ls.name, ls.stage, ls.class,
                   lg.subject, lg.month1, lg.month2, lg.month3, lg.daily1, lg.semester1, lg.midterm,
                   lg.month4, lg.month5, lg.month6, lg.daily2, lg.semester2,
                   lg.annual_average, lg.final_result, lg.saved_at
            FROM listener_students ls
            LEFT JOIN listener_grades lg ON lg.listener_student_id = ls.id
            $where
            ORDER BY ls.stage, ls.class, ls.name, lg.subject";

    $q = mysqli_query($conn, $sql);
    if ($q) {
        while ($r = mysqli_fetch_assoc($q)) {
            $row = array(
                $r['name'], $r['stage'], $r['class'], $r['subject'],
                $r['month1'], $r['month2'], $r['month3'], $r['daily1'], $r['semester1'], $r['midterm'],
                $r['month4'], $r['month5'], $r['month6'], $r['daily2'], $r['semester2'],
                $r['annual_average'], $r['final_result'], $r['saved_at']
            );
            $out = array();
            foreach ($row as $v) $out[] = csv_escape($v);
            echo implode(',', $out) . "\n";
        }
    }
    exit();
}

function export_print($conn, $filter_stage, $filter_class, $search_name){
    $where = get_listeners_where_sql($conn, $filter_stage, $filter_class, $search_name);

    // ترتيب المواد
    $desired_order = array(
        'التربية الاسلامية',
        'اللغة العربية',
        'اللغة الانكليزية',
        'الرياضيات',
        'الكيمياء',
        'الاحياء',
        'الفيزياء',
        'الاجتماعيات',
        'الحاسوب',
        'اللغة الفرنسية',
        'اللغة الكردية'
    );

    $listeners_q = mysqli_query($conn, "SELECT * FROM listener_students ls $where ORDER BY ls.stage, ls.class, ls.name");

    ?>
    <!DOCTYPE html>
    <html lang="ar" dir="rtl">
    <head>
    <meta charset="UTF-8">
    <title>طباعة درجات المستمعين</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    body{font-family:Tahoma,Arial; padding:18px; color:#111}
    h2{margin:0 0 6px 0}
    .meta{margin:0 0 14px 0; color:#444}
    .card{border:1px solid #999; border-radius:10px; padding:12px; margin:0 0 14px 0}
    table{width:100%; border-collapse:collapse; font-size:12px}
    th,td{border:1px solid #999; padding:6px; text-align:center}
    th{background:#f3f3f3}
    td.subject{text-align:right; font-weight:bold}
    @media print { .no-print{display:none} }
    </style>
    </head>
    <body>
      <div class="no-print" style="margin-bottom:10px;">
        <button onclick="window.print()">🖨️ طباعة / حفظ PDF</button>
      </div>

      <h2>درجات الطلبة المستمعين</h2>
      <div class="meta">تاريخ الطباعة: <?php echo date('Y-m-d H:i'); ?></div>

      <?php
      if (!$listeners_q || mysqli_num_rows($listeners_q) == 0) {
          echo "<div>لا توجد بيانات ضمن الفلاتر الحالية.</div>";
      } else {
          while ($stu = mysqli_fetch_assoc($listeners_q)) {
              $lid = (int)$stu['id'];
              $stage = isset($stu['stage']) ? $stu['stage'] : '';

              // ✅ مواد المرحلة بدون get_result
              $subjects = fetch_subjects_by_stage($conn, $stage);

              $ordered = array();
              foreach ($desired_order as $dn) { if (in_array($dn, $subjects)) $ordered[] = $dn; }
              foreach ($subjects as $sname) { if (!in_array($sname, $ordered)) $ordered[] = $sname; }
              if (count($ordered) === 0) $ordered = array('التربية الاسلامية','اللغة العربية','اللغة الانكليزية','الرياضيات');

              // جلب درجاته
              $map = array();
              $gq = mysqli_query($conn, "SELECT * FROM listener_grades WHERE listener_student_id=".$lid);
              if ($gq) {
                  while ($g = mysqli_fetch_assoc($gq)) {
                      $subj = isset($g['subject']) ? $g['subject'] : '';
                      if ($subj !== '') $map[$subj] = $g;
                  }
              }

              echo '<div class="card">';
              echo '<div style="margin-bottom:10px;"><b>الطالب:</b> '.esc($stu['name']).' — <b>المرحلة:</b> '.esc($stu['stage']).' — <b>الشعبة:</b> '.esc($stu['class']).'</div>';

              echo '<table><thead><tr>
                    <th>المادة</th>
                    <th>ش1</th><th>ش2</th><th>ش3</th><th>يومي1</th><th>فصل أول</th>
                    <th>نصف السنة</th>
                    <th>ش4</th><th>ش5</th><th>ش6</th><th>يومي2</th><th>فصل ثاني</th>
                    <th>معدل سنوي</th><th>النهائي</th>
                    </tr></thead><tbody>';

              foreach ($ordered as $subj) {
                  $g = isset($map[$subj]) ? $map[$subj] : array();

                  $m1  = floatval(isset($g['month1']) ? $g['month1'] : 0);
                  $m2  = floatval(isset($g['month2']) ? $g['month2'] : 0);
                  $m3  = floatval(isset($g['month3']) ? $g['month3'] : 0);
                  $d1  = floatval(isset($g['daily1']) ? $g['daily1'] : 0);
                  $mid = floatval(isset($g['midterm']) ? $g['midterm'] : 0);

                  $m4  = floatval(isset($g['month4']) ? $g['month4'] : 0);
                  $m5  = floatval(isset($g['month5']) ? $g['month5'] : 0);
                  $m6  = floatval(isset($g['month6']) ? $g['month6'] : 0);
                  $d2  = floatval(isset($g['daily2']) ? $g['daily2'] : 0);

                  if ($d1 > 0) $sem1 = top3_avg_admin(array($m1,$m2,$m3,$d1));
                  else $sem1 = round(($m1+$m2+$m3)/3,2);
                  $sem1 = round_half_up_int($sem1);

                  if ($d2 > 0) $sem2 = top3_avg_admin(array($m4,$m5,$m6,$d2));
                  else $sem2 = round(($m4+$m5+$m6)/3,2);
                  $sem2 = round_half_up_int($sem2);

                  $annual = round(($sem1 + $sem2 + $mid)/3, 2);
                  $final  = isset($g['final_result']) ? $g['final_result'] : '';

                  echo '<tr>
                        <td class="subject">'.esc($subj).'</td>
                        <td>'.esc(isset($g['month1'])?$g['month1']:'').'</td>
                        <td>'.esc(isset($g['month2'])?$g['month2']:'').'</td>
                        <td>'.esc(isset($g['month3'])?$g['month3']:'').'</td>
                        <td>'.esc(isset($g['daily1'])?$g['daily1']:'0').'</td>
                        <td>'.esc($sem1).'</td>
                        <td>'.esc(isset($g['midterm'])?$g['midterm']:'').'</td>
                        <td>'.esc(isset($g['month4'])?$g['month4']:'0').'</td>
                        <td>'.esc(isset($g['month5'])?$g['month5']:'0').'</td>
                        <td>'.esc(isset($g['month6'])?$g['month6']:'0').'</td>
                        <td>'.esc(isset($g['daily2'])?$g['daily2']:'0').'</td>
                        <td>'.esc($sem2).'</td>
                        <td>'.esc($annual).'</td>
                        <td>'.esc($final).'</td>
                        </tr>';
              }
              echo '</tbody></table></div>';
          }
      }
      ?>
    </body>
    </html>
    <?php
    exit();
}

/* تشغيل التصدير حسب GET */
if (isset($_GET['export']) && $_GET['export'] !== '') {
    if ($_GET['export'] === 'excel') export_excel($conn, $filter_stage, $filter_class, $search_name);
    if ($_GET['export'] === 'print') export_print($conn, $filter_stage, $filter_class, $search_name);
}

/* =========================
   Actions POST
   ========================= */
$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    /* 1) إضافة طالب مستمع */
    if ($action === 'add_listener') {
        $name  = isset($_POST['name']) ? trim($_POST['name']) : '';
        $stage = isset($_POST['stage']) ? trim($_POST['stage']) : '';
        $class = isset($_POST['class']) ? trim($_POST['class']) : '';
        $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

        if ($name === '' || $stage === '' || $class === '') {
            $err = '⚠️ يرجى إدخال اسم الطالب والمرحلة والشعبة.';
        } else {
            $stmt = mysqli_prepare($conn, "INSERT INTO listener_students (name, stage, class, notes) VALUES (?,?,?,?)");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, "ssss", $name, $stage, $class, $notes);
                mysqli_stmt_execute($stmt);
                $new_id = mysqli_insert_id($conn);
                mysqli_stmt_close($stmt);

                /* ✅ تهيئة درجات المواد تلقائياً من جدول subjects حسب المرحلة (بدون get_result) */
                $subjects = fetch_subjects_by_stage($conn, $stage);

                foreach ($subjects as $subj) {
                    $ins = mysqli_prepare($conn, "INSERT IGNORE INTO listener_grades (listener_student_id, subject, saved_at) VALUES (?,?,NOW())");
                    if ($ins) {
                        mysqli_stmt_bind_param($ins, "is", $new_id, $subj);
                        mysqli_stmt_execute($ins);
                        mysqli_stmt_close($ins);
                    }
                }

                $msg = '✅ تم إضافة الطالب المستمع بنجاح (معزول عن طلاب المدرسة).';
            } else {
                $err = '❌ فشل إضافة الطالب.';
            }
        }
    }

    /* 2) حذف طالب مستمع */
    if ($action === 'delete_listener') {
        $listener_id = isset($_POST['listener_id']) ? (int)$_POST['listener_id'] : 0;
        if ($listener_id <= 0) {
            $err = '❌ معرف الطالب غير صحيح.';
        } else {
            $stmt = mysqli_prepare($conn, "DELETE FROM listener_students WHERE id = ? LIMIT 1");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, "i", $listener_id);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
                $msg = '🗑️ تم حذف الطالب المستمع (وتم حذف درجاته التابعة تلقائياً).';
            } else {
                $err = '❌ فشل حذف الطالب.';
            }
        }
    }

    /* 3) حفظ الدرجات */
    if ($action === 'save_grades') {
        $listener_id = isset($_POST['listener_id']) ? (int)$_POST['listener_id'] : 0;
        $grades = isset($_POST['g']) && is_array($_POST['g']) ? $_POST['g'] : array();

        if ($listener_id <= 0) {
            $err = '❌ معرف الطالب غير صحيح.';
        } else {
            foreach ($grades as $subject => $cols) {
                $subject = trim((string)$subject);
                if ($subject === '') continue;

                $m1  = clamp_grade(isset($cols['month1']) ? $cols['month1'] : null);
                $m2  = clamp_grade(isset($cols['month2']) ? $cols['month2'] : null);
                $m3  = clamp_grade(isset($cols['month3']) ? $cols['month3'] : null);
                $d1  = clamp_grade(isset($cols['daily1']) ? $cols['daily1'] : 0);
                $mid = clamp_grade(isset($cols['midterm']) ? $cols['midterm'] : null);

                $m4  = clamp_grade(isset($cols['month4']) ? $cols['month4'] : 0);
                $m5  = clamp_grade(isset($cols['month5']) ? $cols['month5'] : 0);
                $m6  = clamp_grade(isset($cols['month6']) ? $cols['month6'] : 0);
                $d2  = clamp_grade(isset($cols['daily2']) ? $cols['daily2'] : 0);

                $final = clamp_grade(isset($cols['final_result']) ? $cols['final_result'] : null);

                /* حساب فصل أول/ثاني/سنوي */
                if ($d1 !== null && floatval($d1) > 0) $sem1 = top3_avg_admin(array($m1, $m2, $m3, $d1));
                else $sem1 = round((floatval($m1) + floatval($m2) + floatval($m3)) / 3, 2);
                $sem1 = round_half_up_int($sem1);

                if ($d2 !== null && floatval($d2) > 0) $sem2 = top3_avg_admin(array($m4, $m5, $m6, $d2));
                else $sem2 = round((floatval($m4) + floatval($m5) + floatval($m6)) / 3, 2);
                $sem2 = round_half_up_int($sem2);

                $annual = round((floatval($sem1) + floatval($sem2) + floatval($mid)) / 3, 2);

                $subj_esc = mysqli_real_escape_string($conn, $subject);

                $sql = "INSERT INTO listener_grades
                        (listener_student_id, subject, month1, month2, month3, daily1, semester1, midterm,
                         month4, month5, month6, daily2, semester2, annual_average, final_result, saved_at)
                        VALUES
                        (".$listener_id.", '".$subj_esc."', ".sql_num_or_null($m1).", ".sql_num_or_null($m2).", ".sql_num_or_null($m3).",
                         ".sql_num_or_null($d1).", ".sql_num_or_null($sem1).", ".sql_num_or_null($mid).",
                         ".sql_num_or_null($m4).", ".sql_num_or_null($m5).", ".sql_num_or_null($m6).",
                         ".sql_num_or_null($d2).", ".sql_num_or_null($sem2).", ".sql_num_or_null($annual).", ".sql_num_or_null($final).", NOW())
                        ON DUPLICATE KEY UPDATE
                        month1=VALUES(month1),
                        month2=VALUES(month2),
                        month3=VALUES(month3),
                        daily1=VALUES(daily1),
                        semester1=VALUES(semester1),
                        midterm=VALUES(midterm),
                        month4=VALUES(month4),
                        month5=VALUES(month5),
                        month6=VALUES(month6),
                        daily2=VALUES(daily2),
                        semester2=VALUES(semester2),
                        annual_average=VALUES(annual_average),
                        final_result=VALUES(final_result),
                        saved_at=NOW()";

                mysqli_query($conn, $sql);
            }
            $msg = '✅ تم حفظ درجات الطالب المستمع.';
        }
    }
}

/* =========================
   جلب قائمة المراحل من subjects
   ========================= */
$stages = array();
$stg_q = mysqli_query($conn, "SELECT DISTINCT stage FROM subjects WHERE stage IS NOT NULL AND stage<>'' ORDER BY stage");
if ($stg_q) {
    while ($r = mysqli_fetch_assoc($stg_q)) $stages[] = $r['stage'];
}

/* =========================
   جلب المستمعين حسب الفلاتر
   ========================= */
$where = get_listeners_where_sql($conn, $filter_stage, $filter_class, $search_name);
$listeners_q = mysqli_query($conn, "SELECT * FROM listener_students ls $where ORDER BY ls.stage, ls.class, ls.name");

/* ترتيب المواد */
$desired_order = array(
    'التربية الاسلامية',
    'اللغة العربية',
    'اللغة الانكليزية',
    'الرياضيات',
    'الكيمياء',
    'الاحياء',
    'الفيزياء',
    'الاجتماعيات',
    'الحاسوب',
    'اللغة الفرنسية',
    'اللغة الكردية'
);

$excel_url = build_export_url('excel');
$pdf_url   = build_export_url('print');

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>درجات الطلبة المستمعين | ثانوية الأوائل الأهلية للبنين</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{
  font-family:'Tajawal','Calibri',sans-serif;
  background:radial-gradient(circle at 0% 0%,#1b2540,#050814 70%);
  color:#fff; min-height:100vh; padding:18px;
}
.container{max-width:1250px;margin:0 auto}
header{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;gap:10px;flex-wrap:wrap}
header h1{font-size:20px}
.header-actions{display:flex;gap:8px;flex-wrap:wrap}
a.btn{
  text-decoration:none;padding:7px 16px;border-radius:999px;
  background:linear-gradient(120deg,#00e6ff,#007bff);
  color:#fff;font-weight:700; display:inline-block
}
a.btn.green{background:linear-gradient(135deg,#22c55e,#3b82f6)}
a.btn.orange{background:linear-gradient(135deg,#f59e0b,#ef4444)}
.subtitle{color:#a7b3d9;margin-bottom:14px}
.box{
  background:rgba(15,23,42,0.9);
  border:1px solid rgba(148,163,184,0.25);
  border-radius:16px;
  padding:14px;
  box-shadow:0 10px 30px rgba(0,0,0,0.35);
  margin-bottom:14px;
}
.row{display:flex;flex-wrap:wrap;gap:10px 12px;align-items:flex-end}
.field{display:flex;flex-direction:column;font-size:13px}
label{margin-bottom:4px;color:#cbd5f5}
select,input{
  border-radius:10px;border:1px solid #323b5a;background:#020617;color:#e5e7eb;
  padding:7px 10px;min-width:160px
}
button{
  border:none;border-radius:999px;padding:8px 18px;
  background:linear-gradient(135deg,#3b82f6,#22c55e);
  color:#fff;font-weight:800;cursor:pointer;
  box-shadow:0 8px 20px rgba(34,197,94,0.35);
}
button.danger{
  background:linear-gradient(135deg,#ef4444,#f59e0b);
  box-shadow:0 8px 20px rgba(239,68,68,0.25);
}
.alert{padding:10px 12px;border-radius:12px;margin-bottom:12px;font-weight:700}
.alert.ok{background:rgba(34,197,94,0.14);border:1px solid rgba(34,197,94,0.35)}
.alert.err{background:rgba(239,68,68,0.14);border:1px solid rgba(239,68,68,0.35)}
.student-card{
  background:rgba(15,23,42,0.95);
  border-radius:18px;
  padding:14px;
  border:1px solid rgba(148,163,184,0.25);
  box-shadow:0 12px 35px rgba(0,0,0,0.45);
  margin-bottom:14px;
}
.meta{display:flex;flex-wrap:wrap;gap:8px 16px;margin-bottom:10px;align-items:center;justify-content:space-between}
.meta .info{display:flex;flex-wrap:wrap;gap:8px 16px}
.meta b{color:#e5e7eb}
.meta span{color:#9ca3af}
.table-wrap{overflow:auto;border-radius:14px;border:1px solid rgba(55,65,81,0.8)}
.grades-table{width:100%;border-collapse:collapse;font-size:12px;background:rgba(15,23,42,0.92);min-width:980px}
.grades-table th,.grades-table td{border:1px solid rgba(55,65,81,0.8);padding:6px;text-align:center;white-space:nowrap}
.grades-table th{background:rgba(15,23,42,0.98);font-weight:800}
.grades-table td.subject-col{text-align:right;font-weight:800}
.cell-input{
  width:72px;border-radius:10px;border:1px solid rgba(148,163,184,0.25);
  background:#020617;color:#fff;padding:6px 8px;text-align:center;
}
.cell-readonly{opacity:.85;background:rgba(2,6,23,0.55);border:1px dashed rgba(148,163,184,0.25)}
.actions{display:flex;justify-content:space-between;gap:10px;margin-top:10px;flex-wrap:wrap}
.smallnote{color:#9ca3af;font-size:12px;margin-top:8px}
</style>
</head>
<body>
<div class="container">
  <header>
    <h1>درجات الطلبة المستمعين (معزولة عن النظام)</h1>
    <div class="header-actions">
      <a class="btn green" href="<?php echo esc($excel_url); ?>">📥 تصدير Excel</a>
      <a class="btn orange" href="<?php echo esc($pdf_url); ?>" target="_blank">🖨️ تصدير PDF</a>
      <a class="btn" href="admin_dashboard.php">↩ العودة</a>
    </div>
  </header>

  <div class="subtitle">إضافة/عرض/تعديل درجات طلبة مستمعين بدون إدخالهم في جدول طلاب المدرسة.</div>

  <?php if ($msg !== ''): ?><div class="alert ok"><?php echo esc($msg); ?></div><?php endif; ?>
  <?php if ($err !== ''): ?><div class="alert err"><?php echo esc($err); ?></div><?php endif; ?>

  <!-- ✅ إضافة طالب مستمع -->
  <div class="box">
    <form method="post" class="row">
      <input type="hidden" name="action" value="add_listener">
      <div class="field">
        <label>اسم الطالب المستمع</label>
        <input type="text" name="name" placeholder="الاسم الكامل" required>
      </div>
      <div class="field">
        <label>المرحلة</label>
        <select name="stage" required>
          <option value="">اختر المرحلة</option>
          <?php foreach ($stages as $st): ?>
            <option value="<?php echo esc($st); ?>"><?php echo esc($st); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field">
        <label>الشعبة</label>
        <select name="class" required>
          <?php $classes = array('A','B','C','D','E','F'); foreach ($classes as $c) echo '<option value="'.esc($c).'">'.$c.'</option>'; ?>
        </select>
      </div>
      <div class="field" style="flex:1 1 220px;min-width:220px">
        <label>ملاحظة (اختياري)</label>
        <input type="text" name="notes" placeholder="مثال: مستمع من مدرسة كذا">
      </div>
      <button type="submit">➕ إضافة الطالب</button>
    </form>
    <div class="smallnote">لن يتم إضافة هذا الطالب إلى جدول <b>students</b> إطلاقًا — فقط إلى <b>listener_students</b>.</div>
  </div>

  <!-- ✅ فلاتر -->
  <div class="box">
    <form method="get" class="row">
      <div class="field">
        <label>المرحلة</label>
        <select name="stage">
          <option value="">جميع المراحل</option>
          <?php foreach ($stages as $st):
            $sel = ($st === $filter_stage) ? 'selected' : '';
            echo '<option value="'.esc($st).'" '.$sel.'>'.esc($st).'</option>';
          endforeach; ?>
        </select>
      </div>

      <div class="field">
        <label>الشعبة</label>
        <select name="class">
          <option value="">جميع الشعب</option>
          <?php $classes = array('A','B','C','D','E','F'); foreach ($classes as $c) {
              $sel = ($c === $filter_class) ? 'selected' : '';
              echo '<option value="'.esc($c).'" '.$sel.'>'.$c.'</option>';
          } ?>
        </select>
      </div>

      <div class="field" style="flex:1 1 220px;min-width:220px">
        <label>بحث بالاسم</label>
        <input type="text" name="q" value="<?php echo esc($search_name); ?>" placeholder="اكتب جزء من الاسم">
      </div>

      <button type="submit">🔎 عرض</button>
    </form>
  </div>

  <!-- ✅ عرض المستمعين -->
  <?php
  if (!$listeners_q || mysqli_num_rows($listeners_q) == 0) {
      echo '<div class="box">لا يوجد طلبة مستمعين ضمن الفلاتر الحالية.</div>';
  } else {
      while ($stu = mysqli_fetch_assoc($listeners_q)) {
          $lid   = (int)$stu['id'];
          $stage = isset($stu['stage']) ? $stu['stage'] : '';

          /* ✅ جلب مواد المرحلة بدون get_result */
          $subjects = fetch_subjects_by_stage($conn, $stage);

          /* ترتيب المواد */
          $ordered = array();
          foreach ($desired_order as $dn) { if (in_array($dn, $subjects)) $ordered[] = $dn; }
          foreach ($subjects as $sname) { if (!in_array($sname, $ordered)) $ordered[] = $sname; }
          if (count($ordered) === 0) $ordered = array('التربية الاسلامية','اللغة العربية','اللغة الانكليزية','الرياضيات');

          /* جلب درجات الطالب المستمع */
          $map = array();
          $gq = mysqli_query($conn, "SELECT * FROM listener_grades WHERE listener_student_id=".$lid);
          if ($gq) {
              while ($g = mysqli_fetch_assoc($gq)) {
                  $subj = isset($g['subject']) ? $g['subject'] : '';
                  if ($subj !== '') $map[$subj] = $g;
              }
          }

          /* تهيئة أي مادة ناقصة */
          foreach ($ordered as $subj) {
              if (!isset($map[$subj])) {
                  $subj_esc = mysqli_real_escape_string($conn, $subj);
                  mysqli_query($conn, "INSERT IGNORE INTO listener_grades (listener_student_id, subject, saved_at) VALUES (".$lid.", '".$subj_esc."', NOW())");
                  $map[$subj] = array('subject'=>$subj);
              }
          }
  ?>
    <div class="student-card">
      <div class="meta">
        <div class="info">
          <div><span>اسم الطالب:</span> <b><?php echo esc($stu['name']); ?></b></div>
          <div><span>المرحلة:</span> <b><?php echo esc($stu['stage']); ?></b></div>
          <div><span>الشعبة:</span> <b><?php echo esc($stu['class']); ?></b></div>
          <?php if (isset($stu['notes']) && trim($stu['notes']) !== ''): ?>
            <div><span>ملاحظة:</span> <b><?php echo esc($stu['notes']); ?></b></div>
          <?php endif; ?>
        </div>

        <!-- ✅ زر حذف الطالب -->
        <form method="post" onsubmit="return confirm('هل أنت متأكد من حذف هذا الطالب المستمع؟ سيتم حذف درجاته أيضاً.');">
          <input type="hidden" name="action" value="delete_listener">
          <input type="hidden" name="listener_id" value="<?php echo $lid; ?>">
          <button type="submit" class="danger">🗑️ حذف الطالب</button>
        </form>
      </div>

      <form method="post">
        <input type="hidden" name="action" value="save_grades">
        <input type="hidden" name="listener_id" value="<?php echo $lid; ?>">

        <div class="table-wrap">
          <table class="grades-table">
            <thead>
              <tr>
                <th>المادة</th>
                <th>ش1</th><th>ش2</th><th>ش3</th><th>يومي 1</th><th>فصل أول</th>
                <th>نصف السنة</th>
                <th>ش4</th><th>ش5</th><th>ش6</th><th>يومي 2</th><th>فصل ثاني</th>
                <th>معدل سنوي</th>
                <th>النهائي</th>
              </tr>
            </thead>
            <tbody>
            <?php foreach ($ordered as $subj):
                $g = $map[$subj];

                $m1  = floatval(isset($g['month1']) ? $g['month1'] : 0);
                $m2  = floatval(isset($g['month2']) ? $g['month2'] : 0);
                $m3  = floatval(isset($g['month3']) ? $g['month3'] : 0);
                $d1  = floatval(isset($g['daily1']) ? $g['daily1'] : 0);
                $mid = floatval(isset($g['midterm']) ? $g['midterm'] : 0);

                $m4  = floatval(isset($g['month4']) ? $g['month4'] : 0);
                $m5  = floatval(isset($g['month5']) ? $g['month5'] : 0);
                $m6  = floatval(isset($g['month6']) ? $g['month6'] : 0);
                $d2  = floatval(isset($g['daily2']) ? $g['daily2'] : 0);

                if ($d1 > 0) $sem1 = top3_avg_admin(array($m1,$m2,$m3,$d1));
                else $sem1 = round(($m1+$m2+$m3)/3,2);
                $sem1 = round_half_up_int($sem1);

                if ($d2 > 0) $sem2 = top3_avg_admin(array($m4,$m5,$m6,$d2));
                else $sem2 = round(($m4+$m5+$m6)/3,2);
                $sem2 = round_half_up_int($sem2);

                $annual = round(($sem1 + $sem2 + $mid)/3, 2);
            ?>
              <tr>
                <td class="subject-col"><?php echo esc($subj); ?></td>

                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][month1]" value="<?php echo esc(isset($g['month1']) ? $g['month1'] : ''); ?>" /></td>
                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][month2]" value="<?php echo esc(isset($g['month2']) ? $g['month2'] : ''); ?>" /></td>
                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][month3]" value="<?php echo esc(isset($g['month3']) ? $g['month3'] : ''); ?>" /></td>
                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][daily1]" value="<?php echo esc(isset($g['daily1']) ? $g['daily1'] : '0'); ?>" /></td>

                <td><input class="cell-input cell-readonly" value="<?php echo esc($sem1); ?>" disabled></td>

                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][midterm]" value="<?php echo esc(isset($g['midterm']) ? $g['midterm'] : ''); ?>" /></td>

                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][month4]" value="<?php echo esc(isset($g['month4']) ? $g['month4'] : '0'); ?>" /></td>
                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][month5]" value="<?php echo esc(isset($g['month5']) ? $g['month5'] : '0'); ?>" /></td>
                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][month6]" value="<?php echo esc(isset($g['month6']) ? $g['month6'] : '0'); ?>" /></td>
                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][daily2]" value="<?php echo esc(isset($g['daily2']) ? $g['daily2'] : '0'); ?>" /></td>

                <td><input class="cell-input cell-readonly" value="<?php echo esc($sem2); ?>" disabled></td>

                <td><input class="cell-input cell-readonly" value="<?php echo esc($annual); ?>" disabled></td>

                <td><input class="cell-input" name="g[<?php echo esc($subj); ?>][final_result]" value="<?php echo esc(isset($g['final_result']) ? $g['final_result'] : ''); ?>" /></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <div class="actions">
          <button type="submit">💾 حفظ درجات الطالب</button>
          <div class="smallnote">PDF: اضغط “تصدير PDF” ثم من نافذة الطباعة اختر Save as PDF.</div>
        </div>
      </form>
    </div>

  <?php
      } // while
  }
  ?>
</div>
</body>
</html>
