<?php
require_once __DIR__ . '/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$userId        = (int)$_SESSION['user_id'];
$institutionId = (int)$_SESSION['institution_id'];

$errors  = [];
$success = "";

// quiz_id must be present
if (!isset($_GET['quiz_id']) || !ctype_digit($_GET['quiz_id'])) {
    header('Location: manual_mode_setup.php');
    exit;
}
$quizId = (int)$_GET['quiz_id'];

// Fetch quiz details (and ensure belongs to this institution)
$stmt = $conn->prepare("
    SELECT id, quiz_name, class_name, subject, total_questions
    FROM manual_quizzes
    WHERE id = ? AND institution_id = ?
    LIMIT 1
");
$stmt->bind_param('ii', $quizId, $institutionId);
$stmt->execute();
$quiz = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$quiz) {
    header('Location: manual_mode_setup.php');
    exit;
}

$totalQuestions = (int)$quiz['total_questions'];

// Check if key already exists
$existingKey = null;
$stmt = $conn->prepare("
    SELECT id, correct_answers
    FROM manual_answer_keys
    WHERE quiz_id = ?
    LIMIT 1
");
$stmt->bind_param('i', $quizId);
$stmt->execute();
$res = $stmt->get_result()->fetch_assoc();
$stmt->close();
if ($res) {
    $existingKey = $res;
}

// If existing, prefill array
$prefill = array_fill(1, $totalQuestions, '');
if ($existingKey) {
    $parts = explode(',', $existingKey['correct_answers']);
    for ($i = 0; $i < $totalQuestions; $i++) {
        $qNum = $i + 1;
        if (isset($parts[$i])) {
            $val = strtoupper(trim($parts[$i]));
            $prefill[$qNum] = in_array($val, ['A','B','C','D'], true) ? $val : '';
        }
    }
}

// Handle POST – save/update key
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $answers = [];
    for ($i = 1; $i <= $totalQuestions; $i++) {
        $key = 'q' . $i;
        $val = isset($_POST[$key]) ? strtoupper(trim($_POST[$key])) : '';
        if (!in_array($val, ['A','B','C','D'], true)) {
            $errors[] = "Please set a valid option (A/B/C/D) for Question {$i}.";
        }
        $answers[] = $val;
    }

    if (empty($errors)) {
        $ansStr = implode(',', $answers);

        if ($existingKey) {
            // update
            $stmt = $conn->prepare("
                UPDATE manual_answer_keys
                SET correct_answers = ?
                WHERE id = ?
            ");
            $stmt->bind_param('si', $ansStr, $existingKey['id']);
            $stmt->execute();
            $stmt->close();
            $success = "Answer key updated successfully.";
        } else {
            // insert
            $stmt = $conn->prepare("
                INSERT INTO manual_answer_keys
                    (quiz_id, correct_answers)
                VALUES (?, ?)
            ");
            $stmt->bind_param('is', $quizId, $ansStr);
            $stmt->execute();
            $stmt->close();
            $success = "Answer key saved successfully.";
        }

        // refresh prefill
        for ($i = 0; $i < $totalQuestions; $i++) {
            $qNum = $i + 1;
            $prefill[$qNum] = $answers[$i];
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<div class="row mt-4">
  <div class="col-12 mb-3">
    <a href="manual_mode_setup.php" class="small">&larr; Back to Manual Quizzes</a>
  </div>
</div>

<div class="row g-4">
  <div class="col-lg-6 col-md-7">
    <div class="card">
      <div class="card-body">
        <h5 class="mb-2">Set Answer Key</h5>
        <p class="text-muted small mb-2">
          Quiz: <strong><?php echo htmlspecialchars($quiz['quiz_name']); ?></strong><br>
          Class: <?php echo htmlspecialchars($quiz['class_name']); ?> &middot;
          Subject: <?php echo htmlspecialchars($quiz['subject']); ?>
        </p>

        <?php if (!empty($errors)): ?>
          <div class="alert alert-danger py-2 small">
            <ul class="mb-0">
              <?php foreach ($errors as $err): ?>
                <li><?php echo htmlspecialchars($err); ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <?php if ($success): ?>
          <div class="alert alert-success py-2 small">
            <?php echo htmlspecialchars($success); ?>
          </div>
        <?php endif; ?>

        <form method="post">
          <div class="row">
            <?php for ($i = 1; $i <= $totalQuestions; $i++): ?>
              <div class="col-6 mb-2">
                <label class="form-label small mb-1">Q<?php echo $i; ?></label>
                <select name="q<?php echo $i; ?>" class="form-select form-select-sm" required>
                  <option value="">-</option>
                  <option value="A" <?php echo $prefill[$i]==='A' ? 'selected' : ''; ?>>A</option>
                  <option value="B" <?php echo $prefill[$i]==='B' ? 'selected' : ''; ?>>B</option>
                  <option value="C" <?php echo $prefill[$i]==='C' ? 'selected' : ''; ?>>C</option>
                  <option value="D" <?php echo $prefill[$i]==='D' ? 'selected' : ''; ?>>D</option>
                </select>
              </div>
            <?php endfor; ?>
          </div>

          <div class="mt-3 d-flex justify-content-end">
            <button type="submit" class="btn btn-primary">
              Save Answer Key
            </button>
          </div>
        </form>

      </div>
    </div>
  </div>

  <div class="col-lg-6 col-md-5">
    <div class="card h-100">
      <div class="card-body">
        <h6 class="mb-2">How this is used?</h6>
        <p class="small text-muted mb-2">
          The answer key is used to evaluate each student and to power
          learning-style and silent-skill detection. Patterns of correct and
          incorrect answers are analysed to understand how the student thinks.
        </p>
        <ul class="small text-muted mb-0">
          <li>Score calculation (correct / wrong / unanswered)</li>
          <li>Identifying consistently weak zones in the paper</li>
          <li>Behaviour pattern (careful / careless / conceptual gaps)</li>
        </ul>
      </div>
    </div>
  </div>
</div>

<?php
include __DIR__ . '/includes/footer.php';
?>
