<?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; // Session user
$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();
    }
    // Redirect after form submission
    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();
?>

<!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>
    function lockInput(input) {
      if (input.value.trim() !== '') input.readOnly = true;
    }

    function validateForm() {
      const inputs = document.querySelectorAll('input.answer-field');
      for (let input of inputs) {
        if (input.value.trim() === '') {
          alert('Please answer all questions.');
          return false;
        }
      }
      return true;
    }

    // 5 minutes timer (300 seconds)
    let totalSeconds = 300;

    function startTimer() {
      const timerDisplay = document.getElementById('timer');
      const form = document.getElementById('questionForm');

      const interval = setInterval(() => {
        let minutes = Math.floor(totalSeconds / 60);
        let seconds = totalSeconds % 60;

        timerDisplay.textContent = `Time Left: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        if (totalSeconds <= 0) {
          clearInterval(interval);
          alert('Time is up! Your answers will be submitted automatically.');
          form.submit();
          // Redirect to d.php after submission
          window.location.href = 'd.php';
        }

        totalSeconds--;
      }, 1000);
    }

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

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

  <form method="post" onsubmit="return validateForm();" id="questionForm">
    <?php $i = 0; while ($row = $result->fetch_assoc()):
      $choices = [$row['q_ans'], $row['c1'], $row['c2'], $row['c3']];
      shuffle($choices);
    ?>
    <div class="card mb-3">
      <div class="card-body">
        <h5 class="card-title">Q<?= $i + 1 ?>: <?= htmlspecialchars($row['q_name']) ?></h5>
        <p>Options: <?= implode(' | ', array_map('htmlspecialchars', $choices)) ?></p>
        <input type="text" class="form-control answer-field" name="answers[]" onblur="lockInput(this)" autocomplete="off" />
        <input type="hidden" name="questions[]" value="<?= htmlspecialchars($row['q_name']) ?>" />
        <input type="hidden" name="subjects[]" value="<?= htmlspecialchars($row['subject']) ?>" />
      </div>
    </div>
    <?php $i++; endwhile; ?>
    <button class="btn btn-primary" type="submit">Submit Answers</button>
  </form>
</body>
</html>
