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

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

// Authentifizierung & Rollenprüfung
$auth = new AuthController();
if (!$auth->isLoggedIn() || $_SESSION['admin_role'] !== 'admin') {
    http_response_code(403);
    echo "Zugriff verweigert.";
    exit;
}

$db = Database::getInstance();
$id = (int)($_GET['id'] ?? 0);

try {
    // Formulardaten laden
    $stmt = $db->prepare("SELECT * FROM forms WHERE id = ?");
    $stmt->execute([$id]);
    $form = $stmt->fetch();

    if (!$form) {
        echo "Formular nicht gefunden.";
        exit;
    }

    // Zugehörige Listen, Felder, Tags
    $listen = $db->query("SELECT id, name FROM lists ORDER BY name")->fetchAll();
    $felder = $db->query("SELECT id, field_key, label FROM custom_field_definitions ORDER BY label")->fetchAll();
    $tags = $db->query("SELECT id, name FROM tags ORDER BY name")->fetchAll();

    $formListIds = $db->prepare("SELECT list_id FROM form_list WHERE form_id = ?");
    $formListIds->execute([$id]);
    $formListIds = $formListIds->fetchAll(PDO::FETCH_COLUMN);

    $formFieldIds = $db->prepare("SELECT field_id FROM form_fields WHERE form_id = ?");
    $formFieldIds->execute([$id]);
    $formFieldIds = $formFieldIds->fetchAll(PDO::FETCH_COLUMN);

    $formTagIds = $db->prepare("SELECT tag_id FROM form_tags WHERE form_id = ?");
    $formTagIds->execute([$id]);
    $formTagIds = $formTagIds->fetchAll(PDO::FETCH_COLUMN);

    ErrorLogger::logSqlSuccess('formular_edit_laden | message: Formular ' . $id . ' geladen.');
} catch (Exception $e) {
    ErrorLogger::logSqlError('formular_edit_laden | error: ' . $e->getMessage());
    echo "Fehler beim Laden.";
    exit;
}

// Formular speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $successMessage = trim($_POST['success_message'] ?? '');
    $redirectUrl = trim($_POST['redirect_url'] ?? '');
    $redirectUrlConfirm = trim($_POST['redirect_url_confirm'] ?? '');
    $showAnrede = isset($_POST['show_anrede']) ? 1 : 0;
    $showVorname = isset($_POST['show_vorname']) ? 1 : 0;
    $showNachname = isset($_POST['show_nachname']) ? 1 : 0;
    $selectedLists = $_POST['lists'] ?? [];
    $selectedFields = $_POST['felder'] ?? [];
    $selectedTags = $_POST['tags'] ?? [];
    $primaryListId = !empty($selectedLists) ? (int) $selectedLists[0] : null;

    try {
        $db->beginTransaction();

        // Formular aktualisieren
        $db->prepare("UPDATE forms SET name = ?, success_message = ?, redirect_url = ?, redirect_url_confirm = ?, show_anrede = ?, show_vorname = ?, show_nachname = ?, list_id = ? WHERE id = ?")
           ->execute([$name, $successMessage, $redirectUrl, $redirectUrlConfirm, $showAnrede, $showVorname, $showNachname, $primaryListId, $id]);

        // Listen neu zuweisen
        $db->prepare("DELETE FROM form_list WHERE form_id = ?")->execute([$id]);
        foreach ($selectedLists as $listId) {
            $db->prepare("INSERT INTO form_list (form_id, list_id) VALUES (?, ?)")->execute([$id, $listId]);
        }

        // Felder neu zuweisen
        $db->prepare("DELETE FROM form_fields WHERE form_id = ?")->execute([$id]);
        foreach ($selectedFields as $fieldId) {
            $db->prepare("INSERT INTO form_fields (form_id, field_id) VALUES (?, ?)")->execute([$id, $fieldId]);
        }

        // Tags neu zuweisen
        $db->prepare("DELETE FROM form_tags WHERE form_id = ?")->execute([$id]);
        foreach ($selectedTags as $tagId) {
            $db->prepare("INSERT INTO form_tags (form_id, tag_id) VALUES (?, ?)")->execute([$id, $tagId]);
        }

        $db->commit();
        ErrorLogger::logSqlSuccess('formular_edit_speichern | message: Formular ' . $id . ' erfolgreich aktualisiert.');
        header("Location: formulare.php?success=updated");
        exit;

    } catch (Exception $e) {
        $db->rollBack();
        ErrorLogger::logSqlError('formular_edit_speichern | error: ' . $e->getMessage());
        echo "Fehler beim Speichern.";
    }
}

$title = 'Formular bearbeiten';
$pageHelp = renderPageHelp([
    'sections' => [
        [
            'heading' => 'Was macht diese Seite?',
            'items' => [
                'Hier bearbeitest du ein vorhandenes Formular und seine Einstellungen.',
                'Damit steuerst du, welche Daten abgefragt und wie neue Einträge verarbeitet werden.',
            ],
        ],
        [
            'heading' => 'Was muss ich eingeben oder auswählen?',
            'items' => [
                'Passe Name, Ziel-Liste, sichtbare Felder und Optionen an.',
                'Aktualisiere nur die Einstellungen, die für neue Formular-Einträge gelten sollen.',
            ],
        ],
        [
            'heading' => 'Worauf sollte ich achten?',
            'items' => [
                'Änderungen wirken sich auf das eingebundene Formular nach dem Speichern aus.',
                'Prüfe bestehende Einbindungen und Abläufe, wenn du Felder oder Pflichtangaben änderst.',
            ],
        ],
    ],
]);
ob_start();
?>
<div class="page-header h2">&#9998; Formulare &raquo; Bearbeiten</div>

<?= $pageHelp ?>

<form method="post">
  <div class="mb-3">
    <label class="form-label">Formularname</label>
    <input type="text" name="name" required class="form-control" value="<?= htmlspecialchars($form['name']) ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Erfolgsmeldung (nach Anmeldung)</label>
    <input type="text" name="success_message" class="form-control" value="<?= htmlspecialchars($form['success_message'] ?? '') ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Weiterleitung nach Einschreibung</label>
    <input type="url" name="redirect_url" class="form-control" value="<?= htmlspecialchars($form['redirect_url']) ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Weiterleitung nach Bestätigung (Double Opt-in)</label>
    <input type="url" name="redirect_url_confirm" class="form-control" value="<?= htmlspecialchars($form['redirect_url_confirm'] ?? '') ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Zugewiesene Listen</label>
    <?php foreach ($listen as $list): ?>
      <div class="form-check">
        <input type="checkbox" class="form-check-input" name="lists[]" value="<?= $list['id'] ?>" <?= in_array($list['id'], $formListIds) ? 'checked' : '' ?>>
        <label class="form-check-label"><?= htmlspecialchars($list['name']) ?></label>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="mb-3">
    <label class="form-label">Eintragungsfelder (außer E-Mail)</label>
    <div class="form-check">
      <input type="checkbox" class="form-check-input" name="show_anrede" value="1" <?= !empty($form['show_anrede']) ? 'checked' : '' ?>>
      <label class="form-check-label">Anrede</label>
    </div>
    <div class="form-check">
      <input type="checkbox" class="form-check-input" name="show_vorname" value="1" <?= !empty($form['show_vorname']) ? 'checked' : '' ?>>
      <label class="form-check-label">Vorname</label>
    </div>
    <div class="form-check">
      <input type="checkbox" class="form-check-input" name="show_nachname" value="1" <?= !empty($form['show_nachname']) ? 'checked' : '' ?>>
      <label class="form-check-label">Nachname</label>
    </div>
  </div>

  <div class="mb-3">
    <label class="form-label">Zusätzliche benutzerdefinierte Felder</label>
    <?php foreach ($felder as $feld): ?>
      <div class="form-check">
        <input type="checkbox" class="form-check-input" name="felder[]" value="<?= $feld['id'] ?>" <?= in_array($feld['id'], $formFieldIds) ? 'checked' : '' ?>>
        <label class="form-check-label"><?= htmlspecialchars($feld['label']) ?> (<?= $feld['field_key'] ?>)</label>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="mb-3">
    <label for="tags" class="form-label"><i class="ti ti-tag"></i> Zugewiesene Tags</label>
    <select name="tags[]" id="tags" class="form-control" multiple>
      <?php foreach ($tags as $tag): ?>
        <option value="<?= $tag['id'] ?>" <?= in_array($tag['id'], $formTagIds) ? 'selected' : '' ?>>
          <?= htmlspecialchars($tag['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
    <small class="form-text text-muted">Wähle einen oder mehrere Tags für das Formular.</small>
  </div>

  <button type="submit" class="btn btn-primary">Speichern</button>
  <a href="formulare.php" class="btn btn-secondary">Abbrechen</a>
</form>

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