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

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

// Authentifizierung prüfen
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    http_response_code(403);
    echo "Zugriff verweigert.";
    exit;
}

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

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

    if (!$form) {
        $error = "Formular nicht gefunden.";
        ErrorLogger::log("Formular-Embed fehlgeschlagen: Formular ID $formId nicht vorhanden", 'WARN');
    } else {
            ErrorLogger::logSqlSuccess('formular_embed_form_laden | message: Formular ' . $formId . ' geladen.');
    }

    // Benutzerdefinierte Felder abrufen
    $customFields = $db->prepare("
        SELECT cf.field_key, cf.label, cf.field_type, cf.is_required
        FROM form_fields ff
        JOIN custom_field_definitions cf ON ff.field_id = cf.id
        WHERE ff.form_id = ? 
        ORDER BY ff.sort_order ASC
    ");
    $customFields->execute([$formId]);
    $customFields = $customFields->fetchAll();
            ErrorLogger::logSqlSuccess('formular_embed_felder_laden | message: Felddefinitionen für Formular ' . $formId . ' geladen.');

    // Tags abrufen
    $stmt = $db->prepare("
        SELECT t.name 
        FROM form_tags ft
        JOIN tags t ON ft.tag_id = t.id
        WHERE ft.form_id = ?
    ");
    $stmt->execute([$formId]);
    $formTags = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'name');
            ErrorLogger::logSqlSuccess('formular_embed_tags_laden | message: Tags für Formular ' . $formId . ' geladen.');

} catch (Exception $e) {
            ErrorLogger::logSqlError('formular_embed_laden | error: ' . $e->getMessage());
    $error = "Fehler beim Laden des Formulars.";
}

$config = include __DIR__ . '/../../includes/config.php';
$actionUrl = rtrim($config['app']['base_url'], '/') . "/formular_submit.php";

// HTML für Eingabefelder aufbauen
$fieldsHtml = '';

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

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

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

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

// Gesamtes Formular-HTML
$formHtml = <<<HTML
<form action="{$actionUrl}" method="post" class="mr9-form">
  <input type="hidden" name="form_id" value="{$form['id']}">

  <div class="mr9-field">
    <label for="email">E-Mail:</label>
    <input type="email" name="email" id="email" required placeholder="Deine E-Mail">
  </div>

  {$fieldsHtml}

  <div class="mr9-honey">
    <label>Bitte nicht ausfüllen:</label>
    <input type="text" name="check_email" value="">
  </div>

  <div class="mr9-actions">
    <button type="submit">Absenden</button>
  </div>
</form>
HTML;

// CSS-Stil
$cssCode = <<<CSS
/* Mailresponder Formular-Styles */
<style>
  *, *::before, *::after {
    box-sizing: border-box;
  }

  .mr9-form {
    max-width: 500px;
    margin: 0 auto;
    padding: 1em;
    font-family: sans-serif;
    background: #f8f8f8;
    border: 1px solid #ddd;
    border-radius: 6px;
  }

  .mr9-field {
    margin-bottom: 1em;
  }

  .mr9-field label {
    display: block;
    margin-bottom: 0.3em;
    font-weight: bold;
  }

  .mr9-field input,
  .mr9-field select {
    width: 100%;
    padding: 0.5em;
    font-size: 1em;
  }

  .mr9-actions {
    text-align: right;
  }

  .mr9-actions button {
    padding: 0.6em 1.2em;
    font-size: 1em;
    cursor: pointer;
  }

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

  .mr9-field-checkbox label {
    display: inline;
    margin-bottom: 0;
    font-weight: bold;
  }

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

  .mr9-honey {
    display: none;
    visibility: hidden;
    height: 0;
    overflow: hidden;
  }
</style>
CSS;

$title = "Formular einbetten: " . htmlspecialchars($form['name'] ?? '');

ob_start();
?>

<div class="page-header">📋 <?= $title ?></div>

<?php if ($error): ?>
  <div class="alert alert-danger auto-dismiss">❌ <?= htmlspecialchars($error) ?></div>
<?php else: ?>
  <?php if (!empty($formTags)): ?>
    <div class="mb-3">
      <strong><i class="ti ti-tag"></i> Zugewiesene Tags:</strong>
      <?= htmlspecialchars(implode(', ', $formTags)) ?>
    </div>
  <?php endif; ?>

  <h4>📄 HTML-Code (in deine Webseite einfügen)</h4>
  <pre><code><?= htmlspecialchars($formHtml) ?></code></pre>

  <h4>🎨 CSS-Code (in deine eigene CSS-Datei einfügen)</h4>
  <pre><code><?= htmlspecialchars($cssCode) ?></code></pre>
<?php endif; ?>

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

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