<?php
session_start();

require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';
require_once __DIR__ . '/../../includes/core/FormularLogger.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    http_response_code(403);
    echo 'Zugriff verweigert.';
    exit;
}

$db = Database::getInstance();
$formId = (int) ($_GET['id'] ?? 0);
$form = null;
$customFields = [];
$formTags = [];
$error = '';

try {
    $stmt = $db->prepare('SELECT * FROM forms WHERE id = ? LIMIT 1');
    $stmt->execute([$formId]);
    $form = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

    if ($form === null) {
        $error = 'Formular nicht gefunden.';
        ErrorLogger::logSqlError('formular_vorschau_form_laden | error: Formular ' . $formId . ' nicht gefunden.');
    } else {
        ErrorLogger::logSqlSuccess('formular_vorschau_form_laden | message: Formular ' . $formId . ' geladen.');

        $fieldStmt = $db->prepare(
            'SELECT cfd.field_key, cfd.label, cfd.field_type, cfd.is_required
             FROM form_fields ff
             INNER JOIN custom_field_definitions cfd ON cfd.id = ff.field_id
             WHERE ff.form_id = ?
             ORDER BY ff.sort_order ASC'
        );
        $fieldStmt->execute([$formId]);
        $customFields = $fieldStmt->fetchAll(PDO::FETCH_ASSOC);
        ErrorLogger::logSqlSuccess('formular_vorschau_felder_laden | message: Felddefinitionen fuer Formular ' . $formId . ' geladen.');

        $tagStmt = $db->prepare(
            'SELECT t.name
             FROM form_tags ft
             INNER JOIN tags t ON t.id = ft.tag_id
             WHERE ft.form_id = ?
             ORDER BY t.name ASC'
        );
        $tagStmt->execute([$formId]);
        $formTags = array_column($tagStmt->fetchAll(PDO::FETCH_ASSOC), 'name');
        ErrorLogger::logSqlSuccess('formular_vorschau_tags_laden | message: Tags fuer Formular ' . $formId . ' geladen.');
    }
} catch (Throwable $e) {
    $error = 'Fehler beim Laden der Formular-Vorschau.';
    ErrorLogger::logSqlError('formular_vorschau_laden | error: ' . $e->getMessage());
}

if ($form !== null) {
    FormularLogger::log(
        $formId,
        $_SESSION['user_email'] ?? ($_SESSION['email'] ?? 'admin@preview.local'),
        anonymizeIp($_SERVER['REMOTE_ADDR'] ?? 'unknown'),
        FormularLogger::ACTION_SUCCESS,
        'Admin-Vorschau geoeffnet',
        true
    );
}

$config = include __DIR__ . '/../../includes/config.php';
$actionUrl = rtrim((string) ($config['app']['base_url'] ?? ''), '/') . '/formular_submit.php';
$hasRedirect = !empty($form['redirect_url']);

$fieldsHtml = '';

if ($form !== null && !empty($form['show_anrede'])) {
    $fieldsHtml .= <<<HTML
    <div class="mr9-field">
      <label for="anrede">Anrede</label>
      <select name="anrede" id="anrede">
        <option value="">Bitte w&auml;hlen</option>
        <option value="Herr">Herr</option>
        <option value="Frau">Frau</option>
        <option value="Divers">Divers</option>
      </select>
    </div>
HTML;
}

if ($form !== null && !empty($form['show_vorname'])) {
    $required = !empty($form['require_vorname']) ? ' required' : '';
    $requiredHint = !empty($form['require_vorname']) ? ' <span class="mr9-required">*</span>' : '';
    $fieldsHtml .= <<<HTML
    <div class="mr9-field">
      <label for="vorname">Vorname{$requiredHint}</label>
      <input type="text" name="vorname" id="vorname"{$required}>
    </div>
HTML;
}

if ($form !== null && !empty($form['show_nachname'])) {
    $required = !empty($form['require_nachname']) ? ' required' : '';
    $requiredHint = !empty($form['require_nachname']) ? ' <span class="mr9-required">*</span>' : '';
    $fieldsHtml .= <<<HTML
    <div class="mr9-field">
      <label for="nachname">Nachname{$requiredHint}</label>
      <input type="text" name="nachname" id="nachname"{$required}>
    </div>
HTML;
}

foreach ($customFields as $field) {
    $fieldsHtml .= renderCustomFormField($field);
}

$title = 'Formular-Vorschau';
$pageHelp = renderPageHelp([
    'title' => 'Kurzinfo',
    'sections' => [
        [
            'heading' => 'Was macht diese Seite?',
            'items' => [
                'Hier testest du das Formular mit derselben Submit-Route wie im Live-Betrieb.',
                'Die Vorschau ist kein statischer Mockup, sondern eine echte Formular-Uebermittlung an formular_submit.php.',
            ],
        ],
        [
            'heading' => 'Worauf sollte ich achten?',
            'items' => [
                'Jeder Test kann reale Eintraege, Tags und Listen-Zuordnungen erzeugen.',
                'Wenn fuer das Formular eine Weiterleitung hinterlegt ist, springt die Vorschau nach dem Absenden auf diese Zielseite.',
            ],
        ],
    ],
]);

ob_start();
?>
<style>
  .form-preview-shell {
    max-width: 880px;
    margin: 0 auto 3rem;
  }

  .form-preview-meta {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 1rem;
    margin-bottom: 1.5rem;
  }

  .form-preview-card,
  .form-preview-test {
    background: #fff;
    border: 1px solid #d9e2ec;
    border-radius: 12px;
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
  }

  .form-preview-card {
    padding: 1rem 1.1rem;
  }

  .form-preview-card h3,
  .form-preview-test h3 {
    margin: 0 0 0.6rem;
    font-size: 1rem;
  }

  .form-preview-note {
    margin-bottom: 1.25rem;
    padding: 1rem 1.1rem;
    border-left: 4px solid #0d6efd;
    background: #eef5ff;
    border-radius: 10px;
  }

  .form-preview-note p:last-child,
  .form-preview-card p:last-child {
    margin-bottom: 0;
  }

  .form-preview-test {
    padding: 1.5rem;
  }

  .mr9-form {
    display: grid;
    gap: 1rem;
  }

  .mr9-field label {
    display: block;
    margin-bottom: 0.35rem;
    font-weight: 600;
    color: #1f2937;
  }

  .mr9-field input,
  .mr9-field select {
    width: 100%;
    padding: 0.7rem 0.8rem;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    background: #fff;
  }

  .mr9-field-checkbox .mr9-check {
    display: flex;
    align-items: center;
    gap: 0.65rem;
  }

  .mr9-field-checkbox label {
    margin-bottom: 0;
  }

  .mr9-field-checkbox input[type="checkbox"] {
    width: auto;
    margin: 0;
  }

  .mr9-required {
    color: #b42318;
  }

  .mr9-honey {
    position: absolute;
    left: -9999px;
    width: 1px;
    height: 1px;
    overflow: hidden;
  }

  .mr9-actions {
    display: flex;
    justify-content: flex-end;
  }

  .mr9-actions button {
    border: 0;
    border-radius: 8px;
    padding: 0.75rem 1.1rem;
    font-weight: 600;
    color: #fff;
    background: #0d6efd;
    cursor: pointer;
  }

  .mr9-actions button:hover {
    background: #0b5ed7;
  }
</style>

<div class="page-header h2">&#128065; Formulare &raquo; Vorschau testen</div>

<?= $pageHelp ?>

<?php if ($error !== ''): ?>
  <div class="alert alert-danger auto-dismiss"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
<?php else: ?>
  <div class="form-preview-shell">
    <div class="form-preview-meta">
      <div class="form-preview-card">
        <h3>Formular</h3>
        <p><strong><?= htmlspecialchars((string) ($form['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong></p>
        <p class="mb-0">ID: <?= (int) ($form['id'] ?? 0) ?></p>
      </div>
      <div class="form-preview-card">
        <h3>Submit-Route</h3>
        <p class="mb-0"><code><?= htmlspecialchars($actionUrl, ENT_QUOTES, 'UTF-8') ?></code></p>
      </div>
      <div class="form-preview-card">
        <h3>Tags</h3>
        <p class="mb-0"><?= htmlspecialchars($formTags !== [] ? implode(', ', $formTags) : 'Keine Tags zugewiesen.', ENT_QUOTES, 'UTF-8') ?></p>
      </div>
    </div>

    <div class="form-preview-note">
      <p><strong>Test-Hinweis:</strong> Diese Vorschau nutzt das Formular produktionsnah. Absenden erzeugt denselben Flow wie im eingebetteten Formular.</p>
      <?php if ($hasRedirect): ?>
        <p class="mb-0">Fuer dieses Formular ist eine Weiterleitung hinterlegt. Nach dem Test wirst du auf die konfigurierte Zielseite weitergeleitet.</p>
      <?php else: ?>
        <p class="mb-0">Fuer dieses Formular ist keine Weiterleitung hinterlegt. Nach dem Test zeigt `formular_submit.php` die normale Rueckmeldung an.</p>
      <?php endif; ?>
    </div>

    <div class="form-preview-test">
      <h3>Formular testen</h3>
      <form action="<?= htmlspecialchars($actionUrl, ENT_QUOTES, 'UTF-8') ?>" method="post" class="mr9-form">
        <input type="hidden" name="form_id" value="<?= (int) ($form['id'] ?? 0) ?>">

        <div class="mr9-field">
          <label for="email">E-Mail <span class="mr9-required">*</span></label>
          <input type="email" name="email" id="email" required placeholder="test@example.com">
        </div>

        <?= $fieldsHtml ?>

        <div class="mr9-honey">
          <label for="check_email">Bitte nicht ausfuellen</label>
          <input type="text" name="check_email" id="check_email" value="">
        </div>

        <div class="mr9-actions">
          <button type="submit">Formular absenden</button>
        </div>
      </form>
    </div>
  </div>
<?php endif; ?>

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