<?php
// admin/emails/template_copy.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();
$templateId = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($templateId <= 0) {
    $_SESSION['error'] = 'Ungueltige Vorlage.';
    header('Location: templates.php');
    exit;
}

try {
    $stmt = $db->prepare('SELECT * FROM email_templates WHERE id = ?');
    $stmt->execute([$templateId]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    ErrorLogger::logSqlSuccess('Template fuer Kopie geladen | table: email_templates | context: ' . json_encode(['template_id' => $templateId], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('Template fuer Kopie konnte nicht geladen werden | table: email_templates | context: ' . json_encode(['template_id' => $templateId], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $template = null;
}

if ($template === null) {
    $_SESSION['error'] = 'Vorlage nicht gefunden.';
    header('Location: templates.php');
    exit;
}

$title = 'Vorlage kopieren';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newName = trim((string) ($_POST['name'] ?? ''));

    if ($newName === '') {
        $error = 'Bitte gib einen Namen fuer die Kopie ein.';
    } 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([
                $newName,
                (string) ($template['subject'] ?? ''),
                (string) ($template['editor_mode'] ?? 'code'),
                (string) ($template['source_format'] ?? 'html'),
                (int) ($template['builder_schema_version'] ?? 1),
                (string) ($template['body_html'] ?? ''),
                (string) ($template['source_content'] ?? (string) ($template['body_html'] ?? '')),
                $template['layout_id'] !== null ? (int) $template['layout_id'] : null,
            ]);
            ErrorLogger::logSqlSuccess('Template kopiert | table: email_templates | context: ' . json_encode(['source_template_id' => $templateId, 'new_name' => $newName], JSON_UNESCAPED_UNICODE));
            $_SESSION['success'] = 'Vorlage kopiert.';
            header('Location: templates.php');
            exit;
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('Template konnte nicht kopiert werden | table: email_templates | context: ' . json_encode(['template_id' => $templateId], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
            $error = 'Fehler beim Kopieren: ' . $e->getMessage();
        }
    }
}

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

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

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

  <div class="mb-3">
    <label class="form-label">Editor-Modus der Kopie</label>
    <input type="text" class="form-control" value="<?= htmlspecialchars(mrGetEmailTemplateModeLabel((string) ($template['editor_mode'] ?? 'code')), ENT_QUOTES, 'UTF-8') ?>" disabled>
  </div>

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

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

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