<?php

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

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

$db = Database::getInstance();
$config = require __DIR__ . '/../../includes/config.php';
$layoutEditorAssetVersion = @filemtime(__DIR__ . '/../../assets/email-layout-editor.js') ?: time();
$title = 'Neues Layout erstellen';
$error = '';

$layout = mrPrepareLayoutEditorState([
    'name' => '',
    'editor_mode' => 'layout_builder',
    'source_content' => mrCreateDefaultLayoutBuilderSource(),
    'header_html' => '',
    'footer_html' => '',
    'builder_schema_version' => 1,
]);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string) ($_POST['name'] ?? ''));
    $layout = array_merge($layout, [
        'name' => $name,
        'editor_mode' => mrNormalizeLayoutEditorMode((string) ($_POST['editor_mode'] ?? 'layout_builder')),
        'source_content' => (string) ($_POST['source_content'] ?? ''),
        'header_html' => (string) ($_POST['header_html'] ?? ''),
        'footer_html' => (string) ($_POST['footer_html'] ?? ''),
    ]);

    if ($name === '') {
        $error = 'Name ist erforderlich.';
    } else {
        $payload = mrPrepareLayoutEditorPayload($_POST);
        $layout = array_merge($layout, $payload);

        try {
            $stmt = $db->prepare('INSERT INTO email_layouts (name, editor_mode, source_content, builder_schema_version, header_html, footer_html) VALUES (?, ?, ?, ?, ?, ?)');
            $stmt->execute([
                $name,
                $payload['editor_mode'],
                $payload['source_content'],
                $payload['builder_schema_version'],
                $payload['header_html'],
                $payload['footer_html'],
            ]);
            ErrorLogger::logSqlSuccess('Layout erstellt | table: email_layouts | context: ' . json_encode(['name' => $name, 'editor_mode' => $payload['editor_mode']], JSON_UNESCAPED_UNICODE));
            $_SESSION['success'] = 'Layout gespeichert.';
            header('Location: layouts.php');
            exit;
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('Fehler beim Erstellen des Layouts | table: email_layouts | error: ' . $e->getMessage());
            $error = 'Fehler beim Speichern: ' . $e->getMessage();
        }
    }
}

$modeCatalog = mrLayoutEditorModeCatalog();

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

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

<form method="post" data-layout-editor-form>
  <input type="hidden" name="source_content" value="<?= htmlspecialchars((string) $layout['source_content'], ENT_QUOTES, 'UTF-8') ?>" data-role="layout-source-content">
  <input type="hidden" name="header_html" value="<?= htmlspecialchars((string) $layout['header_html'], ENT_QUOTES, 'UTF-8') ?>" data-role="layout-header-html">
  <input type="hidden" name="footer_html" value="<?= htmlspecialchars((string) $layout['footer_html'], ENT_QUOTES, 'UTF-8') ?>" data-role="layout-footer-html">

  <div class="row g-3 mb-4">
    <div class="col-md-6">
      <label for="name" class="form-label">Name</label>
      <input type="text" id="name" name="name" class="form-control" required value="<?= htmlspecialchars((string) $layout['name'], ENT_QUOTES, 'UTF-8') ?>">
    </div>
    <div class="col-md-6">
      <label for="editor_mode" class="form-label">Bearbeitungsmodus</label>
      <select name="editor_mode" id="editor_mode" class="form-select" data-role="layout-editor-mode">
        <?php foreach ($modeCatalog as $mode => $meta): ?>
          <option value="<?= htmlspecialchars($mode, ENT_QUOTES, 'UTF-8') ?>" <?= ((string) $layout['editor_mode'] === $mode) ? 'selected' : '' ?>>
            <?= htmlspecialchars((string) $meta['label'], ENT_QUOTES, 'UTF-8') ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
  </div>

  <div class="layout-editor-panel" data-layout-editor-panel="layout_builder">
    <div class="layout-builder-shell">
      <div class="layout-builder-card">
        <div class="layout-builder-group">
          <div class="layout-builder-group-title">Kopfbereich</div>
          <div class="layout-builder-grid">
            <div><label class="form-label" for="header_background_color">Hintergrund</label><input type="color" id="header_background_color" class="form-control form-control-color" data-layout-field="header.background_color"></div>
            <div><label class="form-label" for="header_text_color">Textfarbe</label><input type="color" id="header_text_color" class="form-control form-control-color" data-layout-field="header.text_color"></div>
            <div><label class="form-label" for="header_align">Ausrichtung</label><select id="header_align" class="form-select" data-layout-field="header.align"><option value="left">Links</option><option value="center">Zentriert</option><option value="right">Rechts</option></select></div><div><label class="form-label" for="header_text_position">Textposition</label><select id="header_text_position" class="form-select" data-layout-field="header.text_position"><option value="below">Unter dem Logo</option><option value="side">Rechts vom Logo</option></select></div>
            <div><label class="form-label" for="header_logo_width">Logo-Breite</label><input type="number" min="80" max="320" id="header_logo_width" class="form-control" data-layout-field="header.logo_width"></div>
            <div class="form-check align-self-end"><input class="form-check-input" type="checkbox" id="header_show_online_view" data-layout-checkbox="header.show_online_view"><label class="form-check-label" for="header_show_online_view">Online-Ansicht-Link anzeigen</label></div>
          </div>
          <div class="layout-builder-grid mt-3">
            <div><label class="form-label" for="header_logo_url">Logo-URL</label><input type="text" id="header_logo_url" class="form-control" data-layout-field="header.logo_url"></div>
            <div><label class="form-label" for="header_logo_alt">Logo-Alt-Text</label><input type="text" id="header_logo_alt" class="form-control" data-layout-field="header.logo_alt"></div>
          </div>
          <div class="mt-3"><label class="form-label" for="header_headline">Headline</label><input type="text" id="header_headline" class="form-control" data-layout-field="header.headline"></div>
          <div class="mt-3"><label class="form-label" for="header_text">Einleitung</label><textarea id="header_text" class="form-control" rows="4" data-layout-field="header.text"></textarea></div>
          <div class="mt-3"><label class="form-label" for="header_online_view_text">Text Online-Ansicht</label><input type="text" id="header_online_view_text" class="form-control" data-layout-field="header.online_view_text"></div>
        </div>

        <div class="layout-builder-group">
          <div class="layout-builder-group-title">Fussbereich</div>
          <div class="layout-builder-grid">
            <div><label class="form-label" for="footer_background_color">Hintergrund</label><input type="color" id="footer_background_color" class="form-control form-control-color" data-layout-field="footer.background_color"></div>
            <div><label class="form-label" for="footer_text_color">Textfarbe</label><input type="color" id="footer_text_color" class="form-control form-control-color" data-layout-field="footer.text_color"></div>
            <div class="form-check align-self-end"><input class="form-check-input" type="checkbox" id="footer_show_social" data-layout-checkbox="footer.show_social"><label class="form-check-label" for="footer_show_social">Social-Links anzeigen</label></div>
            <div class="form-check align-self-end"><input class="form-check-input" type="checkbox" id="footer_show_unsubscribe" data-layout-checkbox="footer.show_unsubscribe"><label class="form-check-label" for="footer_show_unsubscribe">Abmeldelink anzeigen</label></div>
            <div class="form-check align-self-end"><input class="form-check-input" type="checkbox" id="footer_show_online_view" data-layout-checkbox="footer.show_online_view"><label class="form-check-label" for="footer_show_online_view">Online-Ansicht anzeigen</label></div>
            <div class="form-check align-self-end"><input class="form-check-input" type="checkbox" id="footer_show_pause" data-layout-checkbox="footer.show_pause"><label class="form-check-label" for="footer_show_pause">Versandpause-Link anzeigen</label></div>
          </div>
          <div class="mt-3"><label class="form-label" for="footer_text">Footer-Text</label><textarea id="footer_text" class="form-control" rows="4" data-layout-field="footer.text"></textarea></div>
          <div class="layout-builder-grid mt-3">
            <div><label class="form-label" for="footer_facebook_url">Facebook-URL</label><input type="text" id="footer_facebook_url" class="form-control" data-layout-field="footer.facebook_url"></div>
            <div><label class="form-label" for="footer_instagram_url">Instagram-URL</label><input type="text" id="footer_instagram_url" class="form-control" data-layout-field="footer.instagram_url"></div>
            <div><label class="form-label" for="footer_linkedin_url">LinkedIn-URL</label><input type="text" id="footer_linkedin_url" class="form-control" data-layout-field="footer.linkedin_url"></div>
            <div><label class="form-label" for="footer_youtube_url">YouTube-URL</label><input type="text" id="footer_youtube_url" class="form-control" data-layout-field="footer.youtube_url"></div>
          </div>
          <div class="layout-builder-grid mt-3">
            <div><label class="form-label" for="footer_unsubscribe_text">Text Abmeldelink</label><input type="text" id="footer_unsubscribe_text" class="form-control" data-layout-field="footer.unsubscribe_text"></div>
            <div><label class="form-label" for="footer_online_view_text">Text Online-Ansicht</label><input type="text" id="footer_online_view_text" class="form-control" data-layout-field="footer.online_view_text"></div>
            <div><label class="form-label" for="footer_pause_text">Text Versandpause</label><input type="text" id="footer_pause_text" class="form-control" data-layout-field="footer.pause_text"></div>
          </div>
        </div>
      </div>

      <div class="layout-builder-preview-card">
        <div class="layout-builder-help mb-3">Der Layout-Builder erzeugt Header und Footer als mailtaugliches HTML. Platzhalter wie `[online_view_url]` oder `[unsubscribe_url]` werden beim Versand ersetzt.</div>
        <div class="layout-builder-preview-stage">
          <div class="layout-builder-preview" data-role="layout-builder-preview"></div>
        </div>
      </div>
    </div>
  </div>

  <div class="layout-editor-panel" data-layout-editor-panel="html">
    <div class="row g-3">
      <div class="col-md-12">
        <label for="header_html" class="form-label">Header (HTML)</label>
        <textarea id="header_html" class="form-control" rows="8" name="header_html_visible"><?= htmlspecialchars((string) $layout['header_html'], ENT_QUOTES, 'UTF-8') ?></textarea>
      </div>
      <div class="col-md-12">
        <label for="footer_html" class="form-label">Footer (HTML)</label>
        <textarea id="footer_html" class="form-control" rows="8" name="footer_html_visible"><?= htmlspecialchars((string) $layout['footer_html'], ENT_QUOTES, 'UTF-8') ?></textarea>
      </div>
    </div>
    <div class="form-text mt-2">Wenn du im HTML-Modus arbeitest, werden Header und Footer direkt aus diesen Feldern gespeichert.</div>
  </div>

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

<link rel="stylesheet" href="<?= htmlspecialchars($config['app']['base_url'], ENT_QUOTES, 'UTF-8') ?>/assets/email-layout-editor.css?v=<?= urlencode((string) $layoutEditorAssetVersion) ?>">
<script src="<?= htmlspecialchars($config['app']['base_url'], ENT_QUOTES, 'UTF-8') ?>/assets/email-layout-editor.js?v=<?= urlencode((string) $layoutEditorAssetVersion) ?>"></script>
<script>
  (function () {
    const modeField = document.getElementById('editor_mode');
    const headerVisible = document.getElementById('header_html');
    const footerVisible = document.getElementById('footer_html');
    const headerHidden = document.querySelector('[data-role="layout-header-html"]');
    const footerHidden = document.querySelector('[data-role="layout-footer-html"]');

    function syncHtmlMode() {
      if (!modeField) {
        return;
      }
      if (modeField.value === 'html') {
        headerVisible.value = headerHidden.value;
        footerVisible.value = footerHidden.value;
      }
    }

    function syncHiddenFromVisible() {
      if (modeField && modeField.value === 'html') {
        headerHidden.value = headerVisible.value;
        footerHidden.value = footerVisible.value;
      }
    }

    headerVisible.addEventListener('input', syncHiddenFromVisible);
    footerVisible.addEventListener('input', syncHiddenFromVisible);
    modeField.addEventListener('change', syncHtmlMode);
    syncHtmlMode();
    syncHiddenFromVisible();
  })();
</script>
<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';
