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

// لو تريد تقيّدها بالأدمن فقط خلّي هذي مفعّلة
if (!isset($_SESSION['admin_id'])) { header("Location: admin_login.php"); exit(); }

date_default_timezone_set('Asia/Baghdad');

/*
  ✅ التصفية صارت حسب "الفصل" (نوع الامتحان) و "الشهر".
  نستقبل t = exam_type  و m = exam_month
*/
$sel_type  = isset($_GET['t']) ? trim($_GET['t']) : '';
$sel_month = isset($_GET['m']) ? trim($_GET['m']) : '';

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

$rs = mysqli_query($conn, "SELECT DISTINCT exam_type FROM exam_topics WHERE exam_type <> '' ORDER BY exam_type");
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");
while ($r = mysqli_fetch_assoc($rs)) {
    $months[] = $r['exam_month'];
}

/* نبني 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 (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 = [];
    if ($sel_type  !== '') $params[] = "t=".urlencode($sel_type);
    if ($sel_month !== '') $params[] = "m=".urlencode($sel_month);
    if (!empty($params)) {
        $redir .= "?".implode("&", $params);
    }
    header("Location: $redir");
    exit();
}

// ======================= قراءة المواد لهذا الفلتر =======================
$topics = [];
$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 = [];
if ($sel_type !== '' || $sel_month !== '') {
    $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'";
            }

            $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 = [
        'أول'   => '#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';
}

/* ✅ نبني رابط صفحة الطباعة (بدل الـ PDF) ونمرّر له التصفية الحالية */
$print_link = "export_exam_topics_print.php";
$print_params = [];
if ($sel_type !== '')  $print_params[] = "t=".urlencode($sel_type);
if ($sel_month !== '') $print_params[] = "m=".urlencode($sel_month);
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>

      <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>
        </tr>
      </thead>
      <tbody>
      <?php if (count($topics) == 0): ?>
        <tr>
          <td colspan="9" 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 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 = [];
                if ($sel_type  !== '') $qq[] = "t=".urlencode($sel_type);
                if ($sel_month !== '') $qq[] = "m=".urlencode($sel_month);
                $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 === '') || $missing_count == 0): ?>
        <tr>
          <td colspan="5" style="text-align:center;color:#ddd;padding:10px 0;">
            <?php if ($sel_type === '' && $sel_month === ''): ?>
              اختر فصلًا و/أو شهرًا لعرض المتأخرين.
            <?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>
