<?php
session_start();
require_once 'inc/connect.php';

// Handle POST fetch API calls
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	
	
header('Content-Type: application/json');
	
    $action = $_POST['action'] ?? '';

    if ($action === 'load_all') {
        $q = $mysqli->query("SELECT * FROM question_bank ORDER BY date_of_entry DESC");
        $rows = [];
        while ($row = $q->fetch_assoc()) {
            $rows[] = $row;
        }

        ob_start();
        ?>
        <table border="1" cellpadding="10" cellspacing="0" style="width:100%; border-collapse: collapse;">
            <thead style="background:#f4f4f4;">
                <tr>
                    <th>Serial</th>
                    <th>Exam ID</th>
                    <th>Question ID</th>
                    <th>Type</th>
                    <th>Role</th>
                    <th>Content</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($rows as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['serial']) ?></td>
                    <td><?= htmlspecialchars($row['examination_id']) ?></td>
                    <td><?= htmlspecialchars($row['question_id']) ?></td>
                    <td><?= htmlspecialchars($row['type']) ?></td>
                    <td><?= htmlspecialchars($row['content_role']) ?></td>
                    <td style="max-width:300px;"><?= nl2br(htmlspecialchars($row['content'])) ?></td>
                    <td><?= htmlspecialchars($row['status']) ?></td>
                    <td><?= htmlspecialchars($row['date_of_entry']) ?></td>
                    <td>
                        <button onclick="editQuestion(<?= $row['serial'] ?>)">Edit</button>
                        <button onclick="deleteQuestion('<?= $row['question_id'] ?>')">Delete</button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php
        echo json_encode(['success' => true, 'html' => ob_get_clean()]);
        exit;
    }

    if ($action === 'load') {
        $serial = intval($_POST['serial'] ?? 0);
        if ($serial <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid serial']);
            exit;
        }

        $stmt = $mysqli->prepare("SELECT * FROM question_bank WHERE serial = ?");
        $stmt->bind_param("i", $serial);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();

        if ($result) {
            echo json_encode(['status' => 'success', 'data' => $result]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Question not found']);
        }
        exit;
    }

    if ($action === 'edit') {
        $serial = intval($_POST['serial'] ?? 0);
        $content = trim($_POST['content'] ?? '');
        $type = $_POST['type'] ?? 'mcq';
        $role = $_POST['content_role'] ?? 'question';
        $status = $_POST['status'] ?? 'active';
        $info = $_POST['additional_information'] ?? '';
        $explanation = $_POST['question_explanation'] ?? '';

        if ($serial <= 0) {
            echo json_encode(['error' => 'Invalid serial']);
            exit;
        }

        $stmt = $mysqli->prepare("UPDATE question_bank SET content = ?, type = ?, content_role = ?, status = ?, additional_information = ?, question_explanation = ? WHERE serial = ?");
        $stmt->bind_param("ssssssi", $content, $type, $role, $status, $info, $explanation, $serial);
        $stmt->execute();

        echo json_encode(['success' => true, 'message' => 'Question updated']);
        exit;
    }

    if ($action === 'delete') {
        if (isset($_POST['question_id'])) {
            $qid = $_POST['question_id'];
            $stmt = $mysqli->prepare("DELETE FROM question_bank WHERE question_id = ?");
            $stmt->bind_param("s", $qid);
        } elseif (isset($_POST['serial'])) {
            $serial = intval($_POST['serial']);
            $stmt = $mysqli->prepare("DELETE FROM question_bank WHERE serial = ?");
            $stmt->bind_param("i", $serial);
        } else {
            echo json_encode(['error' => 'Missing ID']);
            exit;
        }

        $stmt->execute();
        echo json_encode(['status' => 'success', 'message' => 'Question deleted']);
        exit;
    }

    echo json_encode(['error' => 'Invalid action']);
    exit;
}
?>



<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>All Exam Questions</title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
  <?php include 'inc/admin_nav.php'; ?>

  <div class="content-wrapper p-4">
    <section class="content-header">
      <h1 class="mb-3">All Questions</h1>
    </section>

    <section class="content">
      <table id="tokenTable" class="table table-bordered table-striped">
        <thead>
          <tr>
            <th>Serial</th>
            <th>Question ID</th>
            <th>Exam ID</th>
            <th>Type</th>
            <th>Role</th>
            <th>Content</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $res = $mysqli->query("SELECT serial, question_id, examination_id, type, content_role, content, status FROM question_bank ORDER BY serial DESC");
          while ($row = $res->fetch_assoc()):
          ?>
            <tr id="row-<?= $row['serial'] ?>">
              <td><?= htmlspecialchars($row['serial']) ?></td>
              <td><?= htmlspecialchars($row['question_id']) ?></td>
              <td><?= htmlspecialchars($row['examination_id']) ?></td>
              <td><?= htmlspecialchars($row['type']) ?></td>
              <td><?= htmlspecialchars($row['content_role']) ?></td>
              <td><?= htmlspecialchars(substr(strip_tags($row['content']), 0, 80)) ?>...</td>
              <td><?= htmlspecialchars($row['status']) ?></td>
              <td>
                <button class="btn btn-primary btn-sm" onclick="editQuestion(<?= $row['serial'] ?>)">Edit</button>
                <button class="btn btn-danger btn-sm" onclick="deleteQuestion(<?= $row['serial'] ?>)">Delete</button>
              </td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </section>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form id="editForm">
        <div class="modal-header">
          <h5 class="modal-title">Edit Question</h5>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body" id="editFormBody">
          <!-- Fetched form goes here -->
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Update</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>

<script>
  $(function () {
    $('#tokenTable').DataTable();
  });

  function editQuestion(serial) {
    fetch('questionmodifycenter.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'action=load&serial=' + serial
    })
    .then(res => res.text())
    .then(html => {
      $('#editFormBody').html(html);
      $('#editModal').modal('show');
    });
  }

  $('#editForm').on('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    formData.append('action', 'update');
    fetch('questionmodifycenter.php', {
      method: 'POST',
      body: formData
    })
    .then(res => res.text())
    .then(response => {
      alert(response.trim());
      location.reload();
    });
  });

  function deleteQuestion(serial) {
    if (!confirm("Are you sure you want to delete this question?")) return;
    fetch('questionmodifycenter.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'action=delete&serial=' + serial
    })
    .then(res => res.text())
    .then(response => {
      alert(response.trim());
      document.getElementById('row-' + serial).remove();
    });
  }
</script>
</body>
</html>
