<?php
// admin/emails/templates.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;
}

$title = 'E-Mail-Vorlagen';
$db = Database::getInstance();
$searchTerm = '';
$templates = [];
$params = [];
$whereSql = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['search'])) {
    $searchTerm = trim((string) $_POST['search']);
    if ($searchTerm !== '') {
        $whereSql = 'WHERE t.name LIKE :search OR t.subject LIKE :search';
        $params[':search'] = '%' . $searchTerm . '%';
    }
}

try {
    $sql = "SELECT t.*, l.name AS layout_name
            FROM email_templates t
            LEFT JOIN email_layouts l ON t.layout_id = l.id
            $whereSql
            ORDER BY t.id DESC";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('E-Mail-Vorlagen geladen | table: email_templates | context: ' . json_encode(['search' => $searchTerm], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('E-Mail-Vorlagen konnten nicht geladen werden | table: email_templates | error: ' . $e->getMessage());
    $_SESSION['error'] = 'Fehler beim Laden der Vorlagen.';
}

ob_start();
?>
<div class="page-header h2">E-Mail-Vorlagen verwalten</div>

<?php if (!empty($_SESSION['success'])): ?>
  <div class="alert alert-success auto-dismiss"><?= htmlspecialchars((string) $_SESSION['success'], ENT_QUOTES, 'UTF-8') ?></div>
  <?php unset($_SESSION['success']); ?>
<?php endif; ?>

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

<form method="post" class="mb-3">
  <div class="input-group">
    <input type="text" name="search" value="<?= htmlspecialchars($searchTerm, ENT_QUOTES, 'UTF-8') ?>" class="form-control" placeholder="Nach Name oder Betreff suchen...">
    <button class="btn btn-outline-secondary" type="submit">Suchen</button>
    <a href="templates.php" class="btn btn-outline-danger">Zuruecksetzen</a>
  </div>
</form>

<p><a href="template_create.php" class="btn btn-primary mb-3">Neue Vorlage</a></p>

<table class="table table-striped align-middle">
  <thead>
    <tr>
      <th>Name</th>
      <th>Betreff</th>
      <th>Editor</th>
      <th>Layout</th>
      <th>Aktionen</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($templates as $template): ?>
      <tr>
        <td><?= htmlspecialchars((string) $template['name'], ENT_QUOTES, 'UTF-8') ?></td>
        <td><?= htmlspecialchars((string) $template['subject'], ENT_QUOTES, 'UTF-8') ?></td>
        <td><?= htmlspecialchars(mrGetEmailTemplateModeLabel((string) ($template['editor_mode'] ?? 'code')), ENT_QUOTES, 'UTF-8') ?></td>
        <td><?= htmlspecialchars((string) ($template['layout_name'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
        <td>
          <a href="template_edit.php?id=<?= (int) $template['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
          <a href="template_view.php?id=<?= (int) $template['id'] ?>" class="btn btn-sm btn-outline-secondary" target="_blank" title="Vorschau anzeigen">Vorschau</a>
          <a href="template_copy.php?id=<?= (int) $template['id'] ?>" class="btn btn-sm btn-outline-secondary">Kopieren</a>
          <a href="template_delete.php?id=<?= (int) $template['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Diese Vorlage wirklich loeschen?')">Loeschen</a>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

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

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