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

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

$subject = $_GET['subject'] ?? '';
$user = $userName;
$date = date('Y-m-d');
$ans_id = "ANS-" . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    foreach ($_POST['answers'] as $index => $answer) {
        $question = $_POST['questions'][$index];
        $subject = $_POST['subjects'][$index];
        $stmt = $connection->prepare("INSERT INTO ans (ans_id, subjects, questions, answers, date_time, user_name) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $ans_id, $subject, $question, $answer, $date, $user);
        $stmt->execute();
    }
    echo "<script type='text/javascript'>window.location.href = 'dashboard.php';</script>";
    exit;
}

$sql = "SELECT * FROM ques WHERE subject = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $subject);
$stmt->execute();
$result = $stmt->get_result();
$questions = [];
while ($row = $result->fetch_assoc()) {
    $choices = [$row['q_ans'], $row['c1'], $row['c2'], $row['c3']];
    shuffle($choices);
    $questions[] = [
        'q_name' => $row['q_name'],
        'subject' => $row['subject'],
        'choices' => $choices
    ];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Questionnaire</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
  <script>
    let currentQuestion = 0;
    let totalQuestions = <?= count($questions) ?>;
    let timer;
    let timePerQ = 30;

    function showQuestion(index) {
      const questions = document.querySelectorAll('.question-card');
      questions.forEach((q, i) => q.style.display = i === index ? 'block' : 'none');
      resetTimer();
    }

    function resetTimer() {
      let remaining = timePerQ;
      const timerDisplay = document.getElementById('timer');
      clearInterval(timer);
      timerDisplay.textContent = `Time Left: 00:${remaining}`;
      timer = setInterval(() => {
        remaining--;
        timerDisplay.textContent = `Time Left: 00:${remaining.toString().padStart(2,'0')}`;
        if (remaining <= 0) {
          clearInterval(timer);
          nextQuestion();
        }
      }, 1000);
    }

    function nextQuestion() {
      const questions = document.querySelectorAll('.question-card');
      if (currentQuestion < questions.length - 1) {
        currentQuestion++;
        showQuestion(currentQuestion);
      } else {
        document.getElementById('questionForm').submit();
      }
    }

    window.onload = function() {
      showQuestion(0);
    }
  </script>
</head>
<body class="container py-4">
  <h2>Subject: <?= htmlspecialchars($subject) ?></h2>

  <div class="alert alert-warning" id="timer" style="font-weight: bold; font-size: 1.3em;">
    Time Left: 00:30
  </div>

  <form method="post" id="questionForm">
    <?php foreach ($questions as $i => $q): ?>
      <div class="card mb-3 question-card" style="display:none;">
        <div class="card-body">
          <h5 class="card-title">Q<?= $i + 1 ?>: <?= htmlspecialchars($q['q_name']) ?></h5>
          <?php foreach ($q['choices'] as $choice): ?>
            <div class="form-check">
              <input class="form-check-input" type="radio" name="answers[<?= $i ?>]" value="<?= htmlspecialchars($choice) ?>" required>
              <label class="form-check-label"> <?= htmlspecialchars($choice) ?> </label>
            </div>
          <?php endforeach; ?>
          <input type="hidden" name="questions[<?= $i ?>]" value="<?= htmlspecialchars($q['q_name']) ?>" />
          <input type="hidden" name="subjects[<?= $i ?>]" value="<?= htmlspecialchars($q['subject']) ?>" />
          <div class="mt-3">
            <button type="button" class="btn btn-primary" onclick="nextQuestion()">Next</button>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
    <button class="btn btn-success mt-3" type="submit">Submit All Answers</button>
  </form>
</body>
</html>
