<?php
// quiz_tm1.php – Truppmann Teil 1 Quiz (Mehrfachantworten, direktes Feedback, PHP rendert alles)

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// -------------------- DB-Verbindung --------------------
$host = 'localhost';
$user = 'kd54698_cloud';
$pass = 'w3r24asd!!!';
$db   = 'kd54698_cloud';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Verbindung fehlgeschlagen: " . $conn->connect_error);
}
$conn->set_charset('utf8mb4');

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// -------------------- Fragen + Antworten laden --------------------
$sqlQ = "
  SELECT id, bereich, nummer, question_text, explanation
  FROM tm_questions
  ORDER BY bereich ASC, nummer ASC, id ASC
";
$resQ = $conn->query($sqlQ);
if ($resQ === false) {
    die("SQL-Fehler (tm_questions): " . $conn->error);
}

$questions = [];
while ($q = $resQ->fetch_assoc()) {
    $questions[$q['id']] = $q;
}
$resQ->close();

$answersByQuestion = [];
if ($questions) {
    $ids = implode(',', array_map('intval', array_keys($questions)));
    $sqlA = "
      SELECT id, question_id, answer_text, is_correct, sort_order
      FROM tm_answers
      WHERE question_id IN ($ids)
      ORDER BY question_id ASC, sort_order ASC, id ASC
    ";
    $resA = $conn->query($sqlA);
    if ($resA === false) {
        die("SQL-Fehler (tm_answers): " . $conn->error);
    }
    while ($a = $resA->fetch_assoc()) {
        $answersByQuestion[$a['question_id']][] = $a;
    }
    $resA->close();
}

// jetzt in numerischen Index umwandeln, aber answersByQuestion bleibt nach question_id
$questions = array_values($questions);
$total = count($questions);
?>
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>TM1-Quiz – Feuerwehr-Lernapp</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">

  <style>
    body {
      min-height: 100vh;
      margin: 0;
      background: radial-gradient(circle at top, #111827 0, #020617 45%, #000 100%);
      color: #e5e7eb;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
    }
    .quiz-container {
      max-width: 900px;
      margin: 0 auto;
      padding: 1rem;
    }
    .brand-header {
      display: flex;
      align-items: center;
      gap: .75rem;
      margin-bottom: 1rem;
    }
    .brand-logo {
      width: 40px;
      height: 40px;
      border-radius: 14px;
      background: radial-gradient(circle at 30% 0%, #f97316, #b91c1c 65%, #111827 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 0 20px rgba(248,113,113,0.4);
    }
    .brand-logo span {
      font-weight: 800;
      font-size: 1.2rem;
      color: #fff;
    }
    .brand-header h1 {
      font-size: 1.1rem;
      margin: 0;
      line-height: 1.2;
    }
    .brand-header small {
      color: #9ca3af;
      font-size: .8rem;
    }

    .quiz-card {
      position: relative;
      background: linear-gradient(135deg, rgba(15,23,42,0.95), rgba(30,64,175,0.9));
      border-radius: 20px;
      padding: 1.25rem;
      box-shadow: 0 18px 40px rgba(0,0,0,0.6);
      overflow: hidden;
    }
    .quiz-card::before {
      content: "";
      position: absolute;
      inset: -40%;
      background:
        radial-gradient(circle at 0 0, rgba(248,113,113,0.25), transparent 55%),
        radial-gradient(circle at 100% 100%, rgba(251,191,36,0.25), transparent 55%);
      opacity: .8;
      pointer-events: none;
    }
    .quiz-inner {
      position: relative;
      z-index: 1;
    }

    .badge-area {
      display: flex;
      gap: .5rem;
      flex-wrap: wrap;
      margin-bottom: .5rem;
    }
    .badge-area .badge {
      background: rgba(15,23,42,0.7);
      border: 1px solid rgba(148,163,184,0.4);
      color: #e5e7eb;
      font-weight: 500;
      font-size: .7rem;
      text-transform: uppercase;
      letter-spacing: .05em;
    }

    .question-text {
      font-size: 1rem;
      font-weight: 600;
      margin-bottom: .75rem;
    }

    .answers-list {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      flex-direction: column;
      gap: .4rem;
    }
    .answer-item {
      border-radius: 12px;
      border: 1px solid rgba(148,163,184,0.5);
      background: rgba(15,23,42,0.8);
      padding: .5rem .7rem;
      display: flex;
      align-items: flex-start;
      gap: .45rem;
      cursor: pointer;
      transition: background .15s, border-color .15s, transform .05s;
    }
    .answer-item:hover {
      background: rgba(30,64,175,0.85);
      transform: translateY(-1px);
    }
    .answer-item input {
      margin-top: .2rem;
    }
    .answer-text {
      font-size: .9rem;
    }

    .answer-item.correct {
      border-color: #22c55e;
      background: rgba(22,163,74,0.15);
    }
    .answer-item.wrong {
      border-color: #ef4444;
      background: rgba(239,68,68,0.15);
    }
    .answer-item.missed {
      border-style: dashed;
      border-color: #facc15;
      background: rgba(250,204,21,0.08);
    }

    .quiz-footer {
      margin-top: 1rem;
      display: flex;
      flex-wrap: wrap;
      gap: .5rem;
      align-items: center;
      justify-content: space-between;
    }
    .quiz-footer .left,
    .quiz-footer .right {
      display: flex;
      gap: .5rem;
      align-items: center;
      flex-wrap: wrap;
    }

    .btn-fire {
      border-radius: 999px;
      border: none;
      padding: .45rem 1rem;
      font-size: .9rem;
      font-weight: 600;
      display: inline-flex;
      align-items: center;
      gap: .3rem;
      background: linear-gradient(135deg, #ef4444, #f97316);
      color: #fff;
      box-shadow: 0 12px 22px rgba(248,113,113,0.5);
    }
    .btn-fire:disabled {
      opacity: .6;
      box-shadow: none;
    }
    .btn-ghost {
      border-radius: 999px;
      padding: .4rem .9rem;
      font-size: .85rem;
      border: 1px solid rgba(148,163,184,0.7);
      background: rgba(15,23,42,0.7);
      color: #e5e7eb;
    }
    .btn-ghost:disabled {
      opacity: .5;
    }

    .status-pill {
      border-radius: 999px;
      padding: .25rem .7rem;
      font-size: .8rem;
      display: inline-flex;
      align-items: center;
      gap: .3rem;
    }
    .status-pill.ok {
      background: rgba(22,163,74,0.2);
      color: #bbf7d0;
      border: 1px solid #22c55e;
    }
    .status-pill.fail {
      background: rgba(239,68,68,0.2);
      color: #fecaca;
      border: 1px solid #ef4444;
    }
    .status-pill.neutral {
      background: rgba(15,23,42,0.9);
      color: #e5e7eb;
      border: 1px solid rgba(148,163,184,0.5);
    }

    .explanation-box {
      margin-top: .75rem;
      border-radius: 12px;
      border: 1px dashed rgba(148,163,184,0.8);
      padding: .6rem .7rem;
      font-size: .85rem;
      color: #e5e7eb;
      background: rgba(15,23,42,0.9);
      display: none;
    }

    .progress-text {
      font-size: .8rem;
      color: #9ca3af;
    }

    .question-block {
      display: none;
    }
    .question-block.active {
      display: block;
    }

    @media (max-width: 768px) {
      .quiz-card {
        padding: 1rem;
      }
      .quiz-footer {
        align-items: flex-start;
      }
    }
  </style>
</head>
<body>

<div class="quiz-container">
  <div class="brand-header">
    <div class="brand-logo">
      <span>TM</span>
    </div>
    <div>
      <h1>Truppmann Teil&nbsp;1 – Quiz</h1>
      <small>Mehrfachantworten möglich</small>
    </div>
  </div>

  <?php if ($total === 0): ?>
    <div class="alert alert-warning">
      Es wurden noch keine Fragen in <code>tm_questions</code> / <code>tm_answers</code> gepflegt.
    </div>
  <?php else: ?>
    <div class="quiz-card">
      <div class="quiz-inner">

        <div id="questionWrapper">
          <?php foreach ($questions as $idx => $q):
              $qid = $q['id'];
              $bereich = $q['bereich'] ?: 'Allgemein';
              $nummer  = $q['nummer'] !== null ? (int)$q['nummer'] : null;
              $answers = $answersByQuestion[$qid] ?? [];
          ?>
            <div class="question-block<?= $idx === 0 ? ' active' : '' ?>" data-index="<?= (int)$idx ?>">
              <div class="badge-area">
                <span class="badge"><?= h($bereich) ?></span>
                <span class="badge">TM1</span>
                <?php if ($nummer !== null): ?>
                  <span class="badge">Frage <?= (int)$nummer ?></span>
                <?php else: ?>
                  <span class="badge">Frage <?= (int)($idx+1) ?></span>
                <?php endif; ?>
              </div>

              <div class="question-text">
                <?= nl2br(h($q['question_text'])) ?>
              </div>

              <ul class="answers-list">
                <?php if (empty($answers)): ?>
                  <li class="text-muted small">Keine Antworten hinterlegt.</li>
                <?php else: ?>
                  <?php foreach ($answers as $a): ?>
                    <li class="answer-item" data-correct="<?= $a['is_correct'] ? 1 : 0 ?>">
                      <input type="checkbox" class="form-check-input mt-1">
                      <span class="answer-text"><?= h($a['answer_text']) ?></span>
                    </li>
                  <?php endforeach; ?>
                <?php endif; ?>
              </ul>

              <?php if (!empty($q['explanation'])): ?>
                <div class="explanation-box">
                  <strong>Musterlösung / Hinweis:</strong><br>
                  <?= nl2br(h($q['explanation'])) ?>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>

        <div class="quiz-footer mt-2">
          <div class="left">
            <button type="button" class="btn-ghost" id="btnPrev">
              &#x25C0; Zurück
            </button>
            <button type="button" class="btn-fire" id="btnCheck">
              Antwort prüfen
            </button>
            <button type="button" class="btn-ghost" id="btnShowSolution">
              Lösung anzeigen
            </button>
          </div>
          <div class="right">
            <span class="progress-text" id="progressText">
              Frage <strong>1</strong> / <?= (int)$total ?>
            </span>
            <span id="statusPill" class="status-pill neutral">
              Wähle alle zutreffenden Antworten.
            </span>
            <button type="button" class="btn-ghost" id="btnNext">
              Weiter &#x25B6;
            </button>
          </div>
        </div>

      </div>
    </div>
  <?php endif; ?>
</div>

<script>
(function(){
  const blocks = Array.from(document.querySelectorAll('.question-block'));
  if (!blocks.length) return;

  let currentIdx = 0;

  const btnPrev       = document.getElementById('btnPrev');
  const btnNext       = document.getElementById('btnNext');
  const btnCheck      = document.getElementById('btnCheck');
  const btnShow       = document.getElementById('btnShowSolution');
  const statusPill    = document.getElementById('statusPill');
  const progressText  = document.getElementById('progressText');

  function showQuestion(idx) {
    if (idx < 0 || idx >= blocks.length) return;

    blocks.forEach((b,i) => {
      b.classList.toggle('active', i === idx);
    });
    currentIdx = idx;

    // Buttons aktiv/deaktivieren
    if (btnPrev) btnPrev.disabled = (currentIdx === 0);
    if (btnNext) btnNext.disabled = (currentIdx === blocks.length - 1);

    // Status zurücksetzen
    if (statusPill) {
      statusPill.className = 'status-pill neutral';
      statusPill.textContent = 'Wähle alle zutreffenden Antworten.';
    }

    // Progress anpassen
    if (progressText) {
      progressText.innerHTML = 'Frage <strong>' + (currentIdx+1) + '</strong> / ' + blocks.length;
    }

    // Checkboxen & Klassen zurücksetzen
    const currentBlock = blocks[currentIdx];
    const items = currentBlock.querySelectorAll('.answer-item');
    items.forEach(it => {
      it.classList.remove('correct','wrong','missed');
      const cb = it.querySelector('input[type="checkbox"]');
      if (cb) cb.checked = false;
    });

    // Erklärung einklappen
    const expl = currentBlock.querySelector('.explanation-box');
    if (expl) expl.style.display = 'none';
  }

  function checkAnswers() {
    const currentBlock = blocks[currentIdx];
    const items = Array.from(currentBlock.querySelectorAll('.answer-item'));
    if (!items.length) return;

    items.forEach(it => it.classList.remove('correct','wrong','missed'));

    let allOk = true;
    let anySelected = false;

    items.forEach(it => {
      const cb = it.querySelector('input[type="checkbox"]');
      const isCorrect = it.dataset.correct === '1';

      if (cb && cb.checked) anySelected = true;

      if (isCorrect && cb && cb.checked) {
        it.classList.add('correct');
      } else if (!isCorrect && cb && cb.checked) {
        it.classList.add('wrong');
        allOk = false;
      } else if (isCorrect && (!cb || !cb.checked)) {
        it.classList.add('missed');
        allOk = false;
      }
    });

    if (!statusPill) return;

    if (!anySelected) {
      statusPill.className = 'status-pill fail';
      statusPill.textContent = 'Bitte mindestens eine Antwort auswählen.';
      return;
    }

    if (allOk) {
      statusPill.className = 'status-pill ok';
      statusPill.textContent = 'Perfekt, alle richtigen Antworten gewählt! 🚒';
    } else {
      statusPill.className = 'status-pill fail';
      statusPill.textContent = 'Nicht ganz – markierte Antworten prüfen.';
    }
  }

  function showSolution() {
    const currentBlock = blocks[currentIdx];
    const items = Array.from(currentBlock.querySelectorAll('.answer-item'));

    items.forEach(it => {
      const cb = it.querySelector('input[type="checkbox"]');
      const isCorrect = it.dataset.correct === '1';
      if (cb) cb.checked = isCorrect;
    });

    checkAnswers();

    const expl = currentBlock.querySelector('.explanation-box');
    if (expl) expl.style.display = 'block';
  }

  // Klickfläche: ganze Antwortzeile anklickbar
  blocks.forEach(block => {
    block.addEventListener('click', function(ev){
      const item = ev.target.closest('.answer-item');
      if (!item) return;
      if (ev.target.tagName.toLowerCase() === 'input') return;
      const cb = item.querySelector('input[type="checkbox"]');
      if (cb) cb.checked = !cb.checked;
    });
  });

  if (btnPrev) {
    btnPrev.addEventListener('click', function(){
      showQuestion(currentIdx - 1);
    });
  }
  if (btnNext) {
    btnNext.addEventListener('click', function(){
      showQuestion(currentIdx + 1);
    });
  }
  if (btnCheck) {
    btnCheck.addEventListener('click', checkAnswers);
  }
  if (btnShow) {
    btnShow.addEventListener('click', showSolution);
  }

  // Start mit der ersten Frage
  showQuestion(0);
})();
</script>

</body>
</html>
