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

// ✅ التحقق من تسجيل الدخول
if (!isset($_SESSION['teacher_id'])) {
    header("Location: login.php");
    exit();
}
mysqli_set_charset($conn, "utf8mb4");

$teacher_id = (int)$_SESSION['teacher_id'];

/*
    ✅ نجيب بيانات المدرّس من جدول teachers
*/
$teacher_q = mysqli_query($conn, "SELECT name, subject, stages, classes FROM teachers WHERE id='{$teacher_id}' LIMIT 1");
if (!$teacher_q || mysqli_num_rows($teacher_q) == 0) {
    die("<div style='margin:50px auto;text-align:center;font-family:Cairo;color:red;'>❌ لا يمكن جلب بياناتك من جدول المدرسين.</div>");
}
$teacher_row     = mysqli_fetch_assoc($teacher_q);
$teacher_name    = isset($teacher_row['name']) ? $teacher_row['name'] : 'مدرّس';
$teacher_subject = isset($teacher_row['subject']) ? $teacher_row['subject'] : 'غير محدد';
$stages_raw      = isset($teacher_row['stages'])  ? $teacher_row['stages']  : '';
// مخلّين classes_raw بس ما راح نستخدمه لأنك قلت "الغِ الشعبة"
$classes_raw     = isset($teacher_row['classes']) ? $teacher_row['classes'] : '';

/*
    ✅ نحول المراحل إلى مصفوفة من جدول المدرسين نفسه
*/
$teacher_stages_arr = explode(',', $stages_raw);
$teacher_stages = array();
foreach ($teacher_stages_arr as $stg) {
    $stg = trim($stg);
    if ($stg !== '') {
        $teacher_stages[] = $stg;
    }
}

/*
    ✅ الفلاتر (بدون الشعبة)
*/
$filter_stage = isset($_GET['stage']) ? trim($_GET['stage']) : '';
$filter_sem   = isset($_GET['semester']) ? trim($_GET['semester']) : '';
$filter_exam  = isset($_GET['exam_type']) ? trim($_GET['exam_type']) : '';

/*
    ✅ نبني شرط الاستعلام
*/
$where = " WHERE teacher_id = '{$teacher_id}' AND subject = '" . mysqli_real_escape_string($conn, $teacher_subject) . "' ";
if ($filter_stage != '') {
    $where .= " AND stage = '" . mysqli_real_escape_string($conn, $filter_stage) . "' ";
}
if ($filter_sem != '') {
    $where .= " AND semester = '" . mysqli_real_escape_string($conn, $filter_sem) . "' ";
}
if ($filter_exam != '') {
    // "بدون" معناها نصف/آخر السنة (exam_type فارغ)
    if ($filter_exam === 'بدون') {
        $where .= " AND (exam_type = '' OR exam_type IS NULL) ";
    } else {
        $where .= " AND exam_type = '" . mysqli_real_escape_string($conn, $filter_exam) . "' ";
    }
}

$q = mysqli_query($conn, "SELECT * FROM question_files $where ORDER BY uploaded_at DESC");
?>
<!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;
  display:flex;
  flex-direction:column;
}
body::before{
  content:"";
  position:fixed;
  top:-50%;
  left:-50%;
  width:200%;
  height:200%;
  background:
    radial-gradient(circle at 30% 30%,rgba(0,255,255,0.2),transparent 70%),
    radial-gradient(circle at 70% 70%,rgba(255,215,0,0.2),transparent 80%),
    radial-gradient(circle at 50% 100%,rgba(138,43,226,0.15),transparent 60%);
  animation:nebula 25s linear infinite alternate;
  filter:blur(90px);
  z-index:-1;
}
@keyframes nebula{0%{transform:rotate(0deg) scale(1)}100%{transform:rotate(360deg) scale(1.2)}}
header{
  display:flex;
  justify-content:space-between;
  align-items:center;
  padding:16px 20px;
  background:rgba(255,255,255,0.04);
  border-bottom:1px solid rgba(255,255,255,0.04);
  backdrop-filter:blur(10px);
}
header .title-block{
  display:flex;
  gap:10px;
  align-items:center;
}
header .title-block h1{
  font-size:18px;
  margin:0;
}
header .title-block .sub{
  font-size:12px;
  color:#00e6ff;
}
header .btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;
  padding:7px 14px;
  border-radius:10px;
  text-decoration:none;
  font-weight:600;
  transition:0.3s;
}
header .btn:hover{transform:scale(1.05);}
.page{
  width:100%;
  max-width:1150px;
  margin:25px auto 50px;
  padding:0 15px;
}
.card{
  background:rgba(255,255,255,0.05);
  border:1px solid rgba(255,255,255,0.05);
  border-radius:16px;
  padding:18px 18px 10px;
  box-shadow:0 10px 25px rgba(0,0,0,.15);
}
.card h2{
  margin:0 0 12px 0;
  font-size:20px;
  color:#fff;
  text-shadow:0 0 8px rgba(0,230,255,.3);
}
.filters{
  display:flex;
  flex-wrap:wrap;
  gap:14px;
  margin-bottom:15px;
}
.filter-item label{
  display:block;
  font-size:12px;
  margin-bottom:4px;
  color:#fff;
}
.filter-item select{
  background:rgba(0,0,0,0.3);
  border:1px solid rgba(255,255,255,0.07);
  border-radius:10px;
  padding:5px 10px;
  color:#fff;
  min-width:140px;
}
.filter-submit{
  align-self:flex-end;
}
.filter-submit button{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  border:none;
  color:#fff;
  padding:7px 14px;
  border-radius:10px;
  font-weight:600;
  cursor:pointer;
}
.table-wrapper{
  overflow-x:auto;
  margin-top:10px;
}
table{
  width:100%;
  border-collapse:collapse;
  min-width:650px;
}
th,td{
  border:1px solid rgba(255,255,255,0.04);
  padding:8px 6px;
  text-align:center;
  font-size:13px;
}
th{
  background:rgba(0,0,0,0.25);
  color:#fff;
  font-weight:600;
}
td{
  background:rgba(0,0,0,0.15);
  color:#eee;
}
.btn-download{
  background:#28a745;
  border:none;
  color:#fff!important;
  text-decoration:none;
  padding:5px 10px;
  border-radius:8px;
  font-size:12px;
  display:inline-block;
}
.btn-download:hover{background:#209038;}
.empty-row{
  text-align:center;
  color:#ffbebe;
  font-weight:600;
}
.back-link{
  display:inline-block;
  margin-top:15px;
  background:rgba(0,230,255,.09);
  border:1px solid rgba(0,230,255,.25);
  color:#fff;
  text-decoration:none;
  padding:7px 14px;
  border-radius:10px;
  font-size:13px;
  transition:.3s;
}
.back-link:hover{background:rgba(0,230,255,.3);}
@media(max-width:700px){
  .filters{flex-direction:column;align-items:flex-start;}
  header{flex-wrap:wrap;gap:8px}
  .card{padding:14px 12px 10px}
}
</style>
</head>
<body>

<header>
  <div class="title-block">
    <div>
      <h1>عرض الأسئلة المرفوعة</h1>
      <div class="sub"><?php echo htmlspecialchars($teacher_subject, ENT_QUOTES, 'UTF-8'); ?></div>
    </div>
  </div>
  <a href="upload_questions.php" class="btn">⬅ العودة الى صفحة الاسئلة</a>
</header>

<div class="page">
  <div class="card">
    <h2>فلترة الأسئلة</h2>
    <form method="get" class="filters">
      <div class="filter-item">
        <label>المرحلة</label>
        <select name="stage">
          <option value="">الكل</option>
          <?php
          foreach ($teacher_stages as $stg) {
              $sel = ($filter_stage == $stg) ? 'selected' : '';
              echo "<option value='".htmlspecialchars($stg, ENT_QUOTES, 'UTF-8')."' $sel>".htmlspecialchars($stg, ENT_QUOTES, 'UTF-8')."</option>";
          }
          ?>
        </select>
      </div>

      <div class="filter-item">
        <label>الفصل</label>
        <select name="semester">
          <option value="">الكل</option>
          <option value="ف1" <?php echo ($filter_sem=='ف1'?'selected':''); ?>>ف1</option>
          <option value="ف2" <?php echo ($filter_sem=='ف2'?'selected':''); ?>>ف2</option>
          <option value="نصف السنة" <?php echo ($filter_sem=='نصف السنة'?'selected':''); ?>>نصف السنة</option>
          <option value="آخر السنة" <?php echo ($filter_sem=='آخر السنة'?'selected':''); ?>>آخر السنة</option>
        </select>
      </div>

      <div class="filter-item">
        <label>نوع الأسئلة</label>
        <select name="exam_type">
          <option value="">الكل</option>
          <option value="ش1" <?php echo ($filter_exam=='ش1'?'selected':''); ?>>ش1</option>
          <option value="ش2" <?php echo ($filter_exam=='ش2'?'selected':''); ?>>ش2</option>
          <option value="ش3" <?php echo ($filter_exam=='ش3'?'selected':''); ?>>ش3</option>
          <option value="اليومي" <?php echo ($filter_exam=='اليومي'?'selected':''); ?>>اليومي</option>
          <option value="بدون" <?php echo ($filter_exam=='بدون'?'selected':''); ?>>بدون (نصف/آخر السنة)</option>
        </select>
      </div>

      <div class="filter-submit">
        <button type="submit">🔍 عرض</button>
      </div>
    </form>
  </div>

  <div class="card" style="margin-top:20px;">
    <h2>الأسئلة التي قمت برفعها</h2>
    <div class="table-wrapper">
      <table>
        <tr>
          <th>#</th>
          <th>المرحلة</th>
          <th>الفصل</th>
          <th>النوع</th>
          <th>النموذج</th>
          <th>اسم المدرّس</th>
          <th>تاريخ الرفع</th>
          <th>تحميل</th>
        </tr>
        <?php
        if ($q && mysqli_num_rows($q) > 0) {
            $i = 1;
            while ($row = mysqli_fetch_assoc($q)) {
                $exam_type_display  = ($row['exam_type'] == '' ? '—' : $row['exam_type']);
                $exam_model_display = ($row['exam_model'] == '' ? '—' : $row['exam_model']);

                echo "<tr>
                    <td>".$i."</td>
                    <td>".htmlspecialchars($row['stage'], ENT_QUOTES, 'UTF-8')."</td>
                    <td>".htmlspecialchars($row['semester'], ENT_QUOTES, 'UTF-8')."</td>
                    <td>".htmlspecialchars($exam_type_display, ENT_QUOTES, 'UTF-8')."</td>
                    <td>".htmlspecialchars($exam_model_display, ENT_QUOTES, 'UTF-8')."</td>
                    <td>".htmlspecialchars($teacher_name, ENT_QUOTES, 'UTF-8')."</td>
                    <td>".date('Y-m-d H:i', strtotime($row['uploaded_at']))."</td>
                    <td><a class='btn-download' href='".htmlspecialchars($row['file_path'], ENT_QUOTES, 'UTF-8')."' target='_blank'>⬇ تنزيل</a></td>
                </tr>";
                $i++;
            }
        } else {
            echo "<tr><td colspan='8' class='empty-row'>لا توجد أسئلة مرفوعة بهذه المعايير.</td></tr>";
        }
        ?>
      </table>
    </div>

    <a class="back-link" href="upload_questions.php">⬅ العودة الى صفحة رفع الأسئلة</a>
  </div>
</div>

</body>
</html>
