<?php
// admin/formulare/formulare.php

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';

// Authentifizierung
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$title = 'Formulare Übersicht';
$db = Database::getInstance();
$formulare = [];

try {
    // Alle Formulare abrufen
    $formulare = $db->query("SELECT * FROM forms ORDER BY created_at DESC")->fetchAll();
    ErrorLogger::logSqlSuccess("Formularübersicht geladen");

    // Zugewiesene Listen je Formular abrufen
    foreach ($formulare as &$formular) {
        $stmt = $db->prepare("SELECT l.name FROM form_list fl JOIN lists l ON fl.list_id = l.id WHERE fl.form_id = ?");
        $stmt->execute([$formular['id']]);
        $formular['listen'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
        ErrorLogger::logSqlSuccess("Listen für Formular {$formular['id']} geladen");
    }

} catch (Exception $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der Formulare: " . $e->getMessage());
}

ob_start();
?>
<div class="page-header h2">
  📝 Formulare &raquo; Übersicht
</div>

<p>
  <a href="formular_create.php" class="btn btn-primary mb-3">➕ Neues Formular erstellen</a>
</p>

<?php if (empty($formulare)): ?>
  <div class="alert alert-info auto-dismiss">ℹ️ Es wurden noch keine Formulare erstellt.</div>
<?php else: ?>
  <table class="table table-striped table-bordered align-middle">
    <thead>
      <tr>
        <th>Name</th>
        <th>Zugewiesene Listen</th>
        <th>Erstellt am</th>
        <th>Aktionen</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($formulare as $f): ?>
        <tr>
          <td><?= htmlspecialchars($f['name']) ?></td>
          <td>
            <?php if (!empty($f['listen'])): ?>
              <ul class="mb-0">
                <?php foreach ($f['listen'] as $listName): ?>
                  <li><?= htmlspecialchars($listName) ?></li>
                <?php endforeach; ?>
              </ul>
            <?php else: ?>
              <em>Keine</em>
            <?php endif; ?>
          </td>
          <td><?= date('d.m.Y H:i', strtotime($f['created_at'])) ?></td>
          <td>
            <a href="formular_edit.php?id=<?= $f['id'] ?>" class="btn btn-sm btn-outline-secondary">Bearbeiten</a>
            <a href="formular_vorschau.php?id=<?= $f['id'] ?>" target="_blank" class="btn btn-sm btn-outline-primary">Vorschau</a>
            <a href="formular_embed_code.php?id=<?= $f['id'] ?>" class="btn btn-sm btn-outline-info">Einbetten</a>
            <a href="formular_delete.php?id=<?= $f['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Formular wirklich löschen?')">Löschen</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
<?php endif; ?>

<!-- Meldungen automatisch entfernen -->
<script>
setTimeout(() => {
  document.querySelectorAll('.alert.auto-dismiss').forEach(el => el.remove());
}, 5000);
</script>

<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';
