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

// ✅ التحقق من تسجيل دخول الأدمن
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

if (function_exists('mysqli_set_charset')) {
    mysqli_set_charset($conn, "utf8mb4");
}

// ✅ جلب بيانات الأدمن من الجلسة
$admin_username = isset($_SESSION['admin_username']) ? $_SESSION['admin_username'] : '';
$admin_role     = isset($_SESSION['admin_role']) ? $_SESSION['admin_role'] : null;

// ✅ لو ماكو role (جلسة قديمة) نحدده من اسم المستخدم
if ($admin_role === null) {
    switch ($admin_username) {
        case 'alawael0':
            // فقط كارت أسئلة المدرسين
            $admin_role = 'questions_only';
            break;

        case 'alawael1':
            // واجبات + مواد داخلة + إحصائيات الامتحان
            $admin_role = 'homework_exam_stats';
            break;

        case 'alawael2':
            // تقييمات + إحصائيات + درجات + واجبات + مواد داخلة
            $admin_role = 'eval_stats_grades';
            break;

        case 'awael':   // اليوزر القديم
        case 'alawael': // اليوزر الكامل
        default:
            // كامل الصلاحيات
            $admin_role = 'super';
            break;
    }
    $_SESSION['admin_role'] = $admin_role;
}

// ✅ هذه الصفحة مسموحة فقط للأدوار:
// super + homework_exam_stats + eval_stats_grades
if (!in_array($admin_role, array('super','homework_exam_stats','eval_stats_grades'), true)) {
    header("Location: admin_dashboard.php");
    exit();
}

date_default_timezone_set('Asia/Baghdad');

/*
  ✅ التصفية حسب:
  t = exam_type
  m = exam_month
  s = exam_mode (شفهي/تحريري)
*/
$sel_type  = isset($_GET['t']) ? trim($_GET['t']) : '';
$sel_month = isset($_GET['m']) ? trim($_GET['m']) : '';
$sel_mode  = isset($_GET['s']) ? trim($_GET['s']) : ''; // ✅ جديد

/* نجلب القيم الموجودة أساسًا من الجدول عشان نظهرها في القوائم */
$types  = array();
$months = array();
$modes  = array(); // ✅ جديد

$rs = mysqli_query($conn, "SELECT DISTINCT exam_type FROM exam_topics WHERE exam_type <> '' ORDER BY exam_type");
if ($rs) {
    while ($r = mysqli_fetch_assoc($rs)) {
        $types[] = $r['exam_type'];
    }
}

$rs = mysqli_query($conn, "SELECT DISTINCT exam_month FROM exam_topics WHERE exam_month <> '' ORDER BY exam_month");
if ($rs) {
    while ($r = mysqli_fetch_assoc($rs)) {
        $months[] = $r['exam_month'];
    }
}

// ✅ جلب نوع الاختبار شفهي/تحريري
$rs = mysqli_query($conn, "SELECT DISTINCT exam_mode FROM exam_topics WHERE exam_mode <> '' ORDER BY exam_mode");
if ($rs) {
    while ($r = mysqli_fetch_assoc($rs)) {
        $modes[] = $r['exam_mode'];
    }
}

/* نبني where حسب الفصل والشهر ونوع الاختبار */
$where = "1";
if ($sel_type !== '') {
    $t = mysqli_real_escape_string($conn, $sel_type);
    $where .= " AND exam_type = '$t' ";
}
if ($sel_month !== '') {
    $m = mysqli_real_escape_string($conn, $sel_month);
    $where .= " AND exam_month = '$m' ";
}
if ($sel_mode !== '') {
    $s = mysqli_real_escape_string($conn, $sel_mode);
    $where .= " AND exam_mode = '$s' ";
}

// ======================= حذف مادة داخلة =======================
if (isset($_GET['del'])) {
    $del_id = (int)$_GET['del'];
    if ($del_id > 0) {
        mysqli_query($conn, "DELETE FROM exam_topics WHERE id = $del_id LIMIT 1");
    }

    // نرجّع لنفس التصفية (الفصل/الشهر/نوع الاختبار)
    $redir = "admin_exam_topics.php";
    $params = array();
    if ($sel_type  !== '') $params[] = "t=".urlencode($sel_type);
    if ($sel_month !== '') $params[] = "m=".urlencode($sel_month);
    if ($sel_mode  !== '') $params[] = "s=".urlencode($sel_mode);
    if (!empty($params)) {
        $redir .= "?".implode("&", $params);
    }
    header("Location: $redir");
    exit();
}

// ======================= قراءة المواد لهذا الفلتر =======================
$topics = array();
$q = mysqli_query($conn, "
    SELECT *
    FROM exam_topics
    WHERE $where
    ORDER BY stage ASC, teacher_name ASC, created_at DESC
");
if ($q) {
    while ($row = mysqli_fetch_assoc($q)) {
        $topics[] = $row;
    }
}

// ======================= المدرسون الذين لم يرسلوا =======================
// لو ما اختار لا فصل ولا شهر ولا نوع اختبار، ما نعرض الكل كـ "متأخرين"
$missing = array();
if ($sel_type !== '' || $sel_month !== '' || $sel_mode !== '') {
    $qt = mysqli_query($conn, "SELECT id, name, subject, stages, classes FROM teachers ORDER BY name ASC");
    if ($qt) {
        while ($t = mysqli_fetch_assoc($qt)) {
            $tid = (int)$t['id'];

            // نبني شرط مطابق للفلتر
            $cond = "teacher_id = $tid";
            if ($sel_type !== '') {
                $t2 = mysqli_real_escape_string($conn, $sel_type);
                $cond .= " AND exam_type = '$t2'";
            }
            if ($sel_month !== '') {
                $m2 = mysqli_real_escape_string($conn, $sel_month);
                $cond .= " AND exam_month = '$m2'";
            }
            if ($sel_mode !== '') {
                $s2 = mysqli_real_escape_string($conn, $sel_mode);
                $cond .= " AND exam_mode = '$s2'";
            }

            $chk = mysqli_query($conn, "SELECT 1 FROM exam_topics WHERE $cond LIMIT 1");
            if (!$chk || mysqli_num_rows($chk) == 0) {
                $missing[] = $t;
            }
        }
    }
}
$missing_count = count($missing);

// ======================= لون المرحلة =======================
function stage_color($stage){
    $map = array(
        'أول'   => '#0ea5e9',
        'ثاني'  => '#22c55e',
        'ثالث'  => '#eab308',
        'رابع'  => '#8b5cf6',
        'خامس'  => '#f97316',
        'سادس'  => '#ef4444',
    );
    $stage = trim($stage);
    if ($stage === '') return '#6366f1';

    $parts = preg_split('/\s+/u', $stage);
    $first = isset($parts[0]) ? $parts[0] : $stage;

    return isset($map[$first]) ? $map[$first] : '#6366f1';
}

/* ✅ نبني رابط صفحة الطباعة ونمرّر له التصفية الحالية */
$print_link = "export_exam_topics_print.php";
$print_params = array();
if ($sel_type  !== '') $print_params[] = "t=".urlencode($sel_type);
if ($sel_month !== '') $print_params[] = "m=".urlencode($sel_month);
if ($sel_mode  !== '') $print_params[] = "s=".urlencode($sel_mode);
if (!empty($print_params)) {
    $print_link .= "?".implode("&", $print_params);
}
?>
<!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',sans-serif;
  min-height:100vh;
  background:radial-gradient(circle at 20% 20%,#1a1f3b,#0b0d18 80%);
  color:#fff;
}
header{
  display:flex;
  justify-content:space-between;
  align-items:center;
  padding:16px 20px;
  background:rgba(255,255,255,0.06);
  border-bottom:1px solid rgba(255,255,255,0.08);
  backdrop-filter:blur(10px);
}
header h1{font-size:18px}
header .btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;
  padding:7px 14px;
  border-radius:10px;
  text-decoration:none;
  font-weight:600;
}
.container{
  width:100%;
  max-width:1200px;
  margin:25px auto 50px;
  padding:0 15px;
}
.filter-box{
  background:rgba(255,255,255,0.03);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:14px;
  padding:12px 14px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:10px;
  margin-bottom:15px;
}
.filter-box form{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.filter-box select{
  background:rgba(0,0,0,0.25);
  border:1px solid rgba(255,255,255,0.04);
  border-radius:8px;
  padding:5px 10px;
  color:#fff;
}
.filter-box button{
  background:#00e6ff;
  border:none;
  padding:6px 12px;
  border-radius:8px;
  cursor:pointer;
  font-weight:600;
}
.btn-row{display:flex;gap:8px;flex-wrap:wrap}
.table-wrap{
  background:rgba(255,255,255,0.02);
  border:1px solid rgba(255,255,255,0.02);
  border-radius:14px;
  overflow:hidden;
}
table{width:100%;border-collapse:collapse}
thead{background:rgba(0,0,0,0.25);}
th,td{
  padding:10px 8px;
  font-size:13px;
  border-bottom:1px solid rgba(255,255,255,0.03);
  vertical-align:top;
}
th{white-space:nowrap;text-align:right}
.stage-badge{
  display:inline-block;
  padding:3px 10px;
  border-radius:9999px;
  font-size:12px;
  font-weight:600;
  color:#fff;
}
.actions button, .actions a{
  background:rgba(255,255,255,0.05);
  border:1px solid rgba(255,255,255,0.08);
  border-radius:8px;
  padding:5px 9px;
  color:#fff;
  cursor:pointer;
  font-size:11px;
  text-decoration:none;
  margin-bottom:3px;
  display:inline-block;
}
.actions button:hover, .actions a:hover{
  background:rgba(0,230,255,0.2);
}

/* ✅ الصف اللي تم نسخه */
.copied-row {
  background: rgba(34, 197, 94, 0.12);
}
.copied-row td {
  border-bottom-color: rgba(34, 197, 94, 0.35);
}

#missingBox{
  margin-top:20px;
  background:rgba(0,0,0,0.25);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:12px;
  display:none;
}
#missingBox table td, #missingBox table th{
  font-size:12px;
}
.toggle-missing{
  background:rgba(255,255,255,0.04);
  border:1px solid rgba(255,255,255,0.08);
  border-radius:10px;
  padding:7px 14px;
  color:#fff;
  cursor:pointer;
  font-size:13px;
  white-space:nowrap;
}
@media(max-width:700px){
  .filter-box{flex-direction:column;align-items:flex-start}
  .filter-box form{flex-wrap:wrap}
  .btn-row{flex-wrap:wrap}
  table{display:block;overflow-x:auto}
}
</style>
</head>
<body>

<header>
  <h1>📋 المواد الداخلة بالامتحان</h1>
  <a href="admin_dashboard.php" class="btn">↩ العودة للوحة</a>
</header>

<div class="container">

  <!-- ✅ التصفية: نوع الامتحان + الشهر + نوع الاختبار -->
  <div class="filter-box">
    <form method="get">
      <label>الفصل / نوع الامتحان:</label>
      <select name="t">
        <option value="">الكل</option>
        <?php foreach ($types as $tp): ?>
          <option value="<?php echo htmlspecialchars($tp, ENT_QUOTES, 'UTF-8'); ?>"
            <?php echo ($sel_type === $tp ? 'selected' : ''); ?>>
            <?php echo htmlspecialchars($tp, ENT_QUOTES, 'UTF-8'); ?>
          </option>
        <?php endforeach; ?>
      </select>

      <label>الشهر:</label>
      <select name="m">
        <option value="">الكل</option>
        <?php foreach ($months as $mo): ?>
          <option value="<?php echo htmlspecialchars($mo, ENT_QUOTES, 'UTF-8'); ?>"
            <?php echo ($sel_month === $mo ? 'selected' : ''); ?>>
            <?php echo htmlspecialchars($mo, ENT_QUOTES, 'UTF-8'); ?>
          </option>
        <?php endforeach; ?>
      </select>

      <label>نوع الاختبار:</label>
      <select name="s">
        <option value="">الكل</option>
        <?php foreach ($modes as $md): ?>
          <option value="<?php echo htmlspecialchars($md, ENT_QUOTES, 'UTF-8'); ?>"
            <?php echo ($sel_mode === $md ? 'selected' : ''); ?>>
            <?php echo htmlspecialchars($md, ENT_QUOTES, 'UTF-8'); ?>
          </option>
        <?php endforeach; ?>
      </select>

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

    <div class="btn-row">
      <button type="button" class="toggle-missing" onclick="toggleMissing()">
        📋 المدرسون الذين لم يرسلوا المادة الداخلة
        (<?php echo $missing_count; ?>)
      </button>

      <!-- ✅ زر تصدير / طباعة -->
      <a href="<?php echo $print_link; ?>" target="_blank"
         style="background:#ff8a00;border:1px solid rgba(255,255,255,0.1);border-radius:10px;padding:7px 14px;color:#fff;text-decoration:none;font-size:13px;">
        📄 تصدير / طباعة
      </a>
    </div>
  </div>

  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>التاريخ</th>
          <th>المرحلة</th>
          <th>المدرّس</th>
          <th>المادة</th>
          <th>نوع الامتحان</th>
          <th>الشهر</th>
          <th>نوع الاختبار</th>
          <th>المادة الداخلة</th>
          <th>عمليات</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($topics) == 0): ?>
        <tr>
          <td colspan="10" style="text-align:center;color:#bbb;padding:20px 0;">لا توجد مواد داخلة لهذا الفلتر.</td>
        </tr>
      <?php else: ?>
        <?php $i=1; foreach ($topics as $row): ?>
          <tr data-id="<?php echo (int)$row['id']; ?>">
            <td><?php echo $i++; ?></td>
            <td><?php echo htmlspecialchars($row['created_at'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
              <?php if (trim($row['stage']) != ''): ?>
                <span class="stage-badge" style="background:<?php echo stage_color($row['stage']); ?>;">
                  <?php echo htmlspecialchars($row['stage'], ENT_QUOTES, 'UTF-8'); ?>
                </span>
              <?php else: ?>
                — 
              <?php endif; ?>
            </td>
            <td><?php echo $row['teacher_name'] != '' ? htmlspecialchars($row['teacher_name'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php echo $row['teacher_subject'] != '' ? htmlspecialchars($row['teacher_subject'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php echo $row['exam_type'] != '' ? htmlspecialchars($row['exam_type'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php echo $row['exam_month'] != '' ? htmlspecialchars($row['exam_month'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php
                $mode_val = isset($row['exam_mode']) ? trim($row['exam_mode']) : '';
                echo ($mode_val != '') ? htmlspecialchars($mode_val, ENT_QUOTES, 'UTF-8') : '—';
            ?></td>
            <td style="max-width:280px;white-space:pre-wrap;"><?php echo $row['topics'] != '' ? nl2br(htmlspecialchars($row['topics'], ENT_QUOTES, 'UTF-8')) : '—'; ?></td>
            <td class="actions">
              <button type="button" onclick="copyText(`<?php echo str_replace('`','\`', htmlspecialchars($row['topics'], ENT_QUOTES, 'UTF-8')); ?>`, <?php echo (int)$row['id']; ?>)">📋 نسخ</button>
              <a href="admin_exam_topics.php?<?php
                // نحافظ على الفلاتر في رابط الحذف
                $qq = array();
                if ($sel_type  !== '') $qq[] = "t=".urlencode($sel_type);
                if ($sel_month !== '') $qq[] = "m=".urlencode($sel_month);
                if ($sel_mode  !== '') $qq[] = "s=".urlencode($sel_mode);
                $qq[] = "del=".(int)$row['id'];
                echo implode("&", $qq);
              ?>" onclick="return confirm('حذف هذه المادة الداخلة؟');">🗑 حذف</a>
            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <div id="missingBox">
    <table style="width:100%;border-collapse:collapse;">
      <thead>
        <tr>
          <th>#</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>المراحل</th>
          <th>الشعب</th>
        </tr>
      </thead>
      <tbody>
      <?php if (($sel_type === '' && $sel_month === '' && $sel_mode === '') || $missing_count == 0): ?>
        <tr>
          <td colspan="5" style="text-align:center;color:#ddd;padding:10px 0;">
            <?php if ($sel_type === '' && $sel_month === '' && $sel_mode === ''): ?>
              اختر فصلًا و/أو شهرًا و/أو نوع اختبار لعرض المتأخرين.
            <?php else: ?>
              كل المدرسين أرسلوا في هذا الفلتر ✅
            <?php endif; ?>
          </td>
        </tr>
      <?php else: ?>
        <?php $j=1; foreach ($missing as $m): ?>
          <tr>
            <td><?php echo $j++; ?></td>
            <td><?php echo htmlspecialchars($m['name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($m['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo $m['stages'] ? htmlspecialchars($m['stages'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php echo $m['classes'] ? htmlspecialchars($m['classes'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

</div>

<footer style="text-align:center;padding:15px;color:#aaa;font-size:12px;">
  © <?php echo date("Y"); ?> ثانوية الأوائل الأهلية للبنين
</footer>

<script>
function copyText(text, rowId){
  const markRow = () => {
    const row = document.querySelector('tr[data-id="'+rowId+'"]');
    if (row) {
      row.classList.add('copied-row');
    }
  };

  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(function(){
      alert('✅ تم نسخ المادة الداخلة.');
      markRow();
    }, function(){
      alert('⚠️ لم يتم النسخ، انسخه يدويًا.');
      markRow();
    });
  } else {
    var ta = document.createElement('textarea');
    ta.value = text;
    document.body.appendChild(ta);
    ta.select();
    document.execCommand('copy');
    document.body.removeChild(ta);
    alert('✅ تم نسخ المادة الداخلة.');
    markRow();
  }
}

function toggleMissing(){
  var box = document.getElementById('missingBox');
  box.style.display = (box.style.display === 'none' || box.style.display === '') ? 'block' : 'none';
}
</script>

</body>
</html>
