<?php
session_start();
require_once "../includes/db.php";
if (!isset($_SESSION['admin'])) { header("Location: index.php"); exit; }

$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
if ($exam_id <= 0) { die("Missing exam_id"); }

// Delete question
if (isset($_GET['delete_q'])) {
    $qid = intval($_GET['delete_q']);
    $conn->query("DELETE FROM questions WHERE id=$qid AND exam_id=$exam_id");
    header("Location: view_questions.php?exam_id=".$exam_id);
    exit;
}

// Exam info
$exam = $conn->query("SELECT * FROM exams WHERE id=$exam_id")->fetch_assoc();
if (!$exam) { die("Exam not found."); }

// Questions
$q = $conn->query("SELECT * FROM questions WHERE exam_id=$exam_id ORDER BY id DESC");
?>
<!DOCTYPE html>
<html>
<head>
  <title>View Questions</title>
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<div class="container">
  <h3>Questions: <?= htmlspecialchars($exam['title']) ?> (<?= htmlspecialchars($exam['course_name']) ?> — <?= htmlspecialchars($exam['unit_exam']) ?>)</h3>
  <div class="mb-3">
    <a class="btn btn-success" href="add_question.php?exam_id=<?= $exam_id ?>">➕ Add Question</a>
    <a class="btn btn-secondary" href="dashboard.php">⬅ Back to Dashboard</a>
  </div>

  <table class="table table-striped align-middle">
    <thead class="table-dark">
      <tr>
        <th>ID</th>
        <th>Question</th>
        <th>Media</th>
        <th>Options</th>
        <th>Correct</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    <?php if ($q->num_rows === 0): ?>
      <tr><td colspan="6" class="text-center">No questions yet.</td></tr>
    <?php else: while($row = $q->fetch_assoc()): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td style="max-width:300px; white-space:pre-wrap;"><?= htmlspecialchars($row['question_text'] ?? '') ?></td>
        <td style="max-width:180px">
          <?php if (!empty($row['question_file'])):
            $f = "../uploads/" . $row['question_file'];
            $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
            if (in_array($ext, ['png','jpg','jpeg','gif','webp'])) {
              echo '<img src="'.$f.'" alt="" style="max-width:160px;max-height:100px">';
            } elseif (in_array($ext, ['mp3','wav','m4a','ogg'])) {
              echo '<audio controls style="width:160px;"><source src="'.$f.'"></audio>';
            } else {
              echo '<a href="'.$f.'" target="_blank">Download</a>';
            }
          endif; ?>
        </td>
        <td>
          <?php
          // Support legacy (option_a..d) and new (option_1..4)
          if (isset($row['option_a'])) {
            $opts = ['A'=>$row['option_a'],'B'=>$row['option_b'],'C'=>$row['option_c'],'D'=>$row['option_d']];
            foreach($opts as $k=>$v){ echo "<div><strong>$k.</strong> ".htmlspecialchars($v ?? '')."</div>"; }
          } else {
            for ($i=1;$i<=4;$i++){
              $txt = $row["option_{$i}"] ?? '';
              echo "<div><strong>$i.</strong> ".htmlspecialchars($txt)."</div>";
              $fileKey = "option_{$i}_file";
              if (!empty($row[$fileKey])) {
                $fopt = "../uploads/".$row[$fileKey];
                $ext = strtolower(pathinfo($fopt, PATHINFO_EXTENSION));
                echo "<div class='small ms-2'>";
                if (in_array($ext, ['png','jpg','jpeg','gif','webp'])) {
                  echo "Opt $i: <img src='$fopt' style='max-width:120px;max-height:80px'>";
                } elseif (in_array($ext, ['mp3','wav','m4a','ogg'])) {
                  echo "Opt $i: <audio controls style='width:140px;'><source src='$fopt'></audio>";
                } else {
                  echo "Opt $i: <a href='$fopt' target='_blank'>file</a>";
                }
                echo "</div>";
              }
            }
          }
          ?>
        </td>
        <td>
          <?php
            if (isset($row['correct_answer'])) echo htmlspecialchars($row['correct_answer']);
            elseif (isset($row['correct_option'])) echo htmlspecialchars($row['correct_option']);
          ?>
        </td>
        <td>
          <!-- Optional: add edit_question.php later -->
          <a class="btn btn-danger btn-sm" onclick="return confirm('Delete this question?')" href="view_questions.php?exam_id=<?= $exam_id ?>&delete_q=<?= $row['id'] ?>">Delete</a>
        </td>
      </tr>
    <?php endwhile; endif; ?>
    </tbody>
  </table>
</div>
</body>
</html>
