<?php
// admin/emails/template_create.php

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

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

$db = Database::getInstance();
$config = include __DIR__ . '/../../includes/config.php';
$editorSettings = mrGetTemplateEditorSettings($config, $db);
$editorAssetVersion = @filemtime(__DIR__ . '/../../assets/email-template-editor.js') ?: time();

$title = 'Neue E-Mail-Vorlage erstellen';
$error = '';
$success = '';

try {
    $layoutsStmt = $db->query('SELECT id, name FROM email_layouts ORDER BY name ASC');
    $layouts = $layoutsStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('Layouts geladen | table: email_layouts | context: ' . json_encode(['order' => 'name ASC'], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('Layouts konnten nicht geladen werden | table: email_layouts | error: ' . $e->getMessage());
    $layouts = [];
}

try {
    $fieldsStmt = $db->query('SELECT label, field_key FROM custom_field_definitions ORDER BY id ASC');
    $customFields = $fieldsStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('Zusatzfelder geladen | table: custom_field_definitions | context: ' . json_encode(['order' => 'id ASC'], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('Zusatzfelder konnten nicht geladen werden | table: custom_field_definitions | error: ' . $e->getMessage());
    $customFields = [];
}

try {
    $tagsStmt = $db->query('SELECT id, name FROM tags ORDER BY name ASC');
    $builderTags = $tagsStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('Builder-Tags geladen | table: tags | context: ' . json_encode(['order' => 'name ASC'], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('Builder-Tags konnten nicht geladen werden | table: tags | error: ' . $e->getMessage());
    $builderTags = [];
}

$template = mrResolveTemplateEditorState([
    'name' => '',
    'subject' => '',
    'layout_id' => null,
    'editor_mode' => $editorSettings['default_mode'],
    'source_format' => $editorSettings['default_mode'] === 'email_builder' ? 'builder_json' : 'html',
    'source_content' => $editorSettings['default_mode'] === 'email_builder' ? mrCreateDefaultBuilderSource() : '',
    'body_html' => '',
], $editorSettings);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string) ($_POST['name'] ?? ''));
    $subject = trim((string) ($_POST['subject'] ?? ''));
    $layoutId = isset($_POST['layout_id']) && $_POST['layout_id'] !== '' ? (int) $_POST['layout_id'] : null;
    $payload = mrPrepareTemplateEditorPayload($_POST, $editorSettings);

    $template = mrResolveTemplateEditorState(array_merge($template, $payload, [
        'name' => $name,
        'subject' => $subject,
        'layout_id' => $layoutId,
    ]), $editorSettings);

    if ($name === '' || $subject === '') {
        $error = 'Name und Betreff sind erforderlich.';
    } else {
        try {
            $sql = 'INSERT INTO email_templates (name, subject, editor_mode, source_format, builder_schema_version, body_html, source_content, layout_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $name,
                $subject,
                $payload['editor_mode'],
                $payload['source_format'],
                $payload['builder_schema_version'],
                $payload['body_html'],
                $payload['source_content'],
                $layoutId,
            ]);
            ErrorLogger::logSqlSuccess('Template erstellt | table: email_templates | context: ' . json_encode([
                'name' => $name,
                'editor_mode' => $payload['editor_mode'],
                'layout_id' => $layoutId,
            ], JSON_UNESCAPED_UNICODE));
            $_SESSION['success'] = 'Vorlage gespeichert.';
            header('Location: templates.php');
            exit;
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('Fehler beim Erstellen der Vorlage | table: email_templates | error: ' . $e->getMessage());
            $error = 'Fehler beim Speichern: ' . $e->getMessage();
        }
    }
}

$standardPlatzhalter = [
    'vorname' => 'Vorname des Empfaengers',
    'nachname' => 'Nachname des Empfaengers',
    'email' => 'E-Mail-Adresse',
    'anrede' => 'Anrede',
    'unsubscribe_url' => 'Abmeldelink',
    'online_view_url' => 'Online-Ansicht',
    'pause_url' => 'Versandpause-Link',
];

$pageHelp = renderPageHelp([
    'sections' => [
        [
            'heading' => 'Was macht diese Seite?',
            'items' => [
                'Hier erstellst du eine neue E-Mail-Vorlage f&uuml;r Kampagnen, Trigger und Follow-up-Abl&auml;ufe.',
                'Der Editor-Modus bleibt an der Vorlage gespeichert und kann sp&auml;ter gezielt angepasst werden.',
            ],
        ],
        [
            'heading' => 'Was muss ich eingeben oder auswaehlen?',
            'items' => [
                'Vergib einen klaren Namen, einen passenden Betreff und w&auml;hle bei Bedarf ein Layout.',
                'Entscheide dich f&uuml;r Code, CKEditor oder den neuen E-Mail-Builder.',
            ],
        ],
        [
            'heading' => 'Worauf sollte ich achten?',
            'items' => [
                'Der Builder ist f&uuml;r mailtaugliche Bl&ouml;cke gedacht und ersetzt keinen freien Webseiten-Editor.',
                'Teste wichtige Vorlagen vor produktivem Versand &uuml;ber Vorschau oder Testmail.',
            ],
        ],
    ],
]);

ob_start();
?>
<div class="page-header h2">E-Mail-Vorlagen &raquo; Neu erstellen</div>

<?= $pageHelp ?>

<?php if ($error !== ''): ?>
  <div class="alert alert-danger auto-dismiss"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>

<form method="post" data-template-editor-form data-builder-tags="<?= htmlspecialchars((string) json_encode($builderTags, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8') ?>">
  <div class="mb-3">
    <label for="name" class="form-label">Vorlagenname</label>
    <input type="text" name="name" id="name" class="form-control" value="<?= htmlspecialchars((string) $template['name'], ENT_QUOTES, 'UTF-8') ?>" required>
  </div>

  <div class="mb-3">
    <label for="subject" class="form-label">Betreff</label>
    <input type="text" name="subject" id="subject" class="form-control" value="<?= htmlspecialchars((string) $template['subject'], ENT_QUOTES, 'UTF-8') ?>" required>
  </div>

  <div class="mb-3">
    <label for="layout_id" class="form-label">Layout</label>
    <select name="layout_id" id="layout_id" class="form-select">
      <option value="">-- Kein Layout --</option>
      <?php foreach ($layouts as $layout): ?>
        <option value="<?= (int) $layout['id'] ?>" <?= ((int) ($template['layout_id'] ?? 0) === (int) $layout['id']) ? 'selected' : '' ?>>
          <?= htmlspecialchars((string) $layout['name'], ENT_QUOTES, 'UTF-8') ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="mb-3">
    <label for="editor_mode" class="form-label">Editor-Modus</label>
    <select name="editor_mode" id="editor_mode" class="form-select" data-role="editor-mode">
      <?php foreach ($editorSettings['allowed_modes'] as $mode): ?>
        <option value="<?= htmlspecialchars($mode, ENT_QUOTES, 'UTF-8') ?>" <?= $template['editor_mode'] === $mode ? 'selected' : '' ?>>
          <?= htmlspecialchars(mrGetEmailTemplateModeLabel($mode), ENT_QUOTES, 'UTF-8') ?>
        </option>
      <?php endforeach; ?>
    </select>
    <div class="form-text template-editor-mode-note" data-role="editor-mode-note"></div>
  </div>

  <input type="hidden" name="source_content" value="<?= htmlspecialchars((string) $template['source_content'], ENT_QUOTES, 'UTF-8') ?>" data-role="source-content">
  <input type="hidden" name="body_html" value="<?= htmlspecialchars((string) $template['body_html'], ENT_QUOTES, 'UTF-8') ?>" data-role="body-html">

  <div class="template-editor-shell">
    <div class="template-editor-panel" data-editor-panel="code">
      <label for="code_body_html" class="form-label">HTML-Inhalt</label>
      <textarea name="code_body_html" id="code_body_html" class="form-control" rows="14" data-role="code-editor"><?= htmlspecialchars((string) $template['body_html'], ENT_QUOTES, 'UTF-8') ?></textarea>
    </div>

    <?php if ($editorSettings['ckeditor_enabled']): ?>
      <div class="template-editor-panel" data-editor-panel="ckeditor">
        <label for="ckeditor_body_html" class="form-label">Inhalt mit CKEditor</label>
        <textarea name="ckeditor_body_html" id="ckeditor_body_html" class="form-control" rows="14" data-role="ckeditor-editor"><?= htmlspecialchars((string) $template['body_html'], ENT_QUOTES, 'UTF-8') ?></textarea>
      </div>
    <?php endif; ?>

    <div class="template-editor-panel" data-editor-panel="email_builder">
      <div class="template-builder-layout">
        <div class="template-builder-workbench">
	          <div class="template-builder-toolbar" data-role="builder-toolbar">
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="text">Text</button>
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="preheader">Preheader</button>
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="image">Bild</button>
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="video">Video</button>
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="button">Button</button>
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="link">Link</button>
	            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="columns">2 Spalten</button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="divider">Trenner</button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-add-block="spacer">Abstand</button>
          </div>
          <div class="template-builder-canvas" data-role="builder-canvas"></div>
        </div>
        <div class="template-builder-preview-card">
          <div class="template-builder-help mb-3">Der Builder erzeugt daraus direkt mailtaugliches HTML f&uuml;r Versand und Vorschau.</div>
          <div class="template-builder-preview-stage">
            <div class="template-builder-preview" data-role="builder-preview"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="mb-3 mt-4">
    <button class="btn btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#platzhalterCollapse" aria-expanded="false" aria-controls="platzhalterCollapse">
      Platzhalter anzeigen
    </button>
    <div class="collapse mt-3" id="platzhalterCollapse">
      <div class="card card-body">
        <strong>Standard-Platzhalter:</strong>
        <ul class="mb-3">
          <?php foreach ($standardPlatzhalter as $key => $description): ?>
            <li><code>[<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>]</code> - <?= htmlspecialchars($description, ENT_QUOTES, 'UTF-8') ?></li>
          <?php endforeach; ?>
        </ul>
        <?php if ($customFields !== []): ?>
          <strong>Zusatzfelder:</strong>
          <ul class="mb-0">
            <?php foreach ($customFields as $field): ?>
              <li><code>[field:<?= htmlspecialchars((string) $field['field_key'], ENT_QUOTES, 'UTF-8') ?>]</code> - <?= htmlspecialchars((string) $field['label'], ENT_QUOTES, 'UTF-8') ?></li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>
    </div>
  </div>

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

<link rel="stylesheet" href="<?= htmlspecialchars($config['app']['base_url'], ENT_QUOTES, 'UTF-8') ?>/assets/email-template-editor.css?v=<?= urlencode((string) $editorAssetVersion) ?>">
<script src="<?= htmlspecialchars($config['app']['base_url'], ENT_QUOTES, 'UTF-8') ?>/assets/email-template-editor.js?v=<?= urlencode((string) $editorAssetVersion) ?>"></script>
<?php if ($editorSettings['ckeditor_enabled']): ?>
  <link rel="stylesheet" href="https://cdn.ckeditor.com/ckeditor5/43.1.0/ckeditor5.css">
  <script src="https://cdn.ckeditor.com/ckeditor5/43.1.0/ckeditor5.umd.js"></script>
<?php endif; ?>
<script>
  setTimeout(() => {
    document.querySelectorAll('.auto-dismiss').forEach((el) => el.remove());
  }, 5000);
</script>

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