<?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();
$title = 'Liste bearbeiten';
$error = '';

$listId = (int) ($_GET['id'] ?? 0);
if ($listId <= 0) {
    header('Location: listen.php');
    exit;
}

$list = null;
$fromIdentities = [];
$emailTemplates = [];

$sqlLoadList = 'SELECT * FROM lists WHERE id = ?';
try {
    $stmt = $db->prepare($sqlLoadList);
    $stmt->execute([$listId]);
    ErrorLogger::logSqlSuccess('listen_edit: load list | SQL: ' . $sqlLoadList . ' | params: ' . json_encode([$listId], JSON_UNESCAPED_UNICODE));
    $list = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
} catch (Throwable $e) {
    ErrorLogger::logSqlError('listen_edit: load list failed | SQL: ' . $sqlLoadList . ' | params: ' . json_encode([$listId], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
}

if ($list === null) {
    header('Location: listen.php');
    exit;
}

$sqlFromIdentities = 'SELECT id, name, email FROM sender_identities WHERE is_active = 1 ORDER BY name ASC';
try {
    $fromIdentities = $db->query($sqlFromIdentities)->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('listen_edit: load sender identities | SQL: ' . $sqlFromIdentities . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('listen_edit: load sender identities failed | SQL: ' . $sqlFromIdentities . ' | params: [] | error: ' . $e->getMessage());
    $error = 'Fehler beim Laden der Absender.';
}

$sqlEmailTemplates = 'SELECT id, name, subject FROM email_templates ORDER BY name ASC';
try {
    $emailTemplates = $db->query($sqlEmailTemplates)->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('listen_edit: load email templates | SQL: ' . $sqlEmailTemplates . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('listen_edit: load email templates failed | SQL: ' . $sqlEmailTemplates . ' | params: [] | error: ' . $e->getMessage());
    if ($error === '') {
        $error = 'Fehler beim Laden der E-Mail-Templates.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $requiresDoi = isset($_POST['requires_doi']) ? 1 : 0;
    $notifyOnSignup = isset($_POST['notify_on_signup']) ? 1 : 0;
    $fromIdentityId = ($_POST['from_identity_id'] ?? '') !== '' ? (int) $_POST['from_identity_id'] : null;
    $doiTemplateId = ($_POST['doi_template_id'] ?? '') !== '' ? (int) $_POST['doi_template_id'] : null;
    $welcomeTemplateId = ($_POST['welcome_template_id'] ?? '') !== '' ? (int) $_POST['welcome_template_id'] : null;

    if ($name === '') {
        $error = 'Der Name der Liste ist erforderlich.';
    } elseif ($requiresDoi && !$doiTemplateId) {
        $error = 'Bei aktivem Double-Opt-In muss ein DOI-Template ausgewaehlt werden.';
    } else {
        try {
            $stmt = $db->prepare('UPDATE lists SET name = ?, description = ?, requires_doi = ?, from_identity_id = ?, notify_on_signup = ?, doi_template_id = ?, welcome_template_id = ? WHERE id = ?');
            $stmt->execute([$name, $description, $requiresDoi, $fromIdentityId, $notifyOnSignup, $doiTemplateId, $welcomeTemplateId, $listId]);
            ErrorLogger::logSqlSuccess('listen_edit: update list | params: ' . json_encode([
                'list_id' => $listId,
                'requires_doi' => $requiresDoi,
                'doi_template_id' => $doiTemplateId,
                'welcome_template_id' => $welcomeTemplateId,
            ], JSON_UNESCAPED_UNICODE));

            $userId = $_SESSION['admin_id'] ?? ($_SESSION['user_id'] ?? 0);
            if ($userId) {
                logSettingChange($userId, 'update_list', 'lists', json_encode([
                    'list_id' => $listId,
                    'name' => $name,
                    'requires_doi' => $requiresDoi,
                    'from_identity_id' => $fromIdentityId,
                    'notify_on_signup' => $notifyOnSignup,
                    'doi_template_id' => $doiTemplateId,
                    'welcome_template_id' => $welcomeTemplateId,
                ], JSON_UNESCAPED_UNICODE));
            }

            header('Location: listen.php');
            exit;
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('listen_edit: update list failed | error: ' . $e->getMessage());
            $error = 'Fehler beim Speichern: ' . $e->getMessage();
        }
    }

    $list['name'] = $name;
    $list['description'] = $description;
    $list['requires_doi'] = $requiresDoi;
    $list['notify_on_signup'] = $notifyOnSignup;
    $list['from_identity_id'] = $fromIdentityId;
    $list['doi_template_id'] = $doiTemplateId;
    $list['welcome_template_id'] = $welcomeTemplateId;
}

$pageHelp = renderPageHelp([
    'sections' => [
        [
            'heading' => 'Was macht diese Seite?',
            'items' => [
                'Hier aenderst du die Grunddaten einer bestehenden Liste.',
                'Du steuerst damit Name, Beschreibung, Absender und Mail-Templates der Liste.',
            ],
        ],
        [
            'heading' => 'Was muss ich eingeben oder auswaehlen?',
            'items' => [
                'Passe bei Bedarf Listennamen, Beschreibung und den verwendeten Absender an.',
                'Waehle fuer Double-Opt-In und Welcome die passenden E-Mail-Templates aus.',
            ],
        ],
        [
            'heading' => 'Worauf sollte ich achten?',
            'items' => [
                'Bei aktivem Double-Opt-In muss ein DOI-Template hinterlegt sein.',
                'Ohne passendes DOI-Template kann keine Bestaetigungs-E-Mail versendet werden.',
            ],
        ],
    ],
]);

ob_start();
?>
<div class="page-header h2">Liste bearbeiten</div>
<?= $pageHelp ?>

<?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">Name der Liste</label>
    <input type="text" name="name" id="name" class="form-control" value="<?= htmlspecialchars((string) ($list['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" required>
  </div>

  <div class="mb-3">
    <label for="description" class="form-label">Beschreibung</label>
    <textarea name="description" id="description" class="form-control"><?= htmlspecialchars((string) ($list['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?></textarea>
  </div>

  <div class="form-check mb-3">
    <input class="form-check-input" type="checkbox" name="requires_doi" id="requires_doi" value="1" <?= !empty($list['requires_doi']) ? 'checked' : '' ?>>
    <label class="form-check-label" for="requires_doi">
      Double-Opt-In erforderlich
    </label>
  </div>

  <div class="form-check mb-3">
    <input class="form-check-input" type="checkbox" name="notify_on_signup" id="notify_on_signup" value="1" <?= !empty($list['notify_on_signup']) ? 'checked' : '' ?>>
    <label class="form-check-label" for="notify_on_signup">
      Absender bei neuer Formular-Anmeldung informieren
    </label>
  </div>

  <div class="mb-3">
    <label for="from_identity_id" class="form-label">Absender auswaehlen</label>
    <select name="from_identity_id" id="from_identity_id" class="form-select" required>
      <option value="">-- Absender waehlen --</option>
      <?php foreach ($fromIdentities as $sender): ?>
        <option value="<?= (int) $sender['id'] ?>" <?= ((int) ($sender['id'] ?? 0) === (int) ($list['from_identity_id'] ?? 0)) ? 'selected' : '' ?>>
          <?= htmlspecialchars((string) $sender['name'], ENT_QUOTES, 'UTF-8') ?> &lt;<?= htmlspecialchars((string) $sender['email'], ENT_QUOTES, 'UTF-8') ?>&gt;
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="mb-3">
    <label for="doi_template_id" class="form-label">DOI-Template</label>
    <select name="doi_template_id" id="doi_template_id" class="form-select">
      <option value="">-- DOI-Template waehlen --</option>
      <?php foreach ($emailTemplates as $template): ?>
        <option value="<?= (int) $template['id'] ?>" <?= ((int) ($template['id'] ?? 0) === (int) ($list['doi_template_id'] ?? 0)) ? 'selected' : '' ?>>
          <?= htmlspecialchars((string) $template['name'], ENT_QUOTES, 'UTF-8') ?> - <?= htmlspecialchars((string) $template['subject'], ENT_QUOTES, 'UTF-8') ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="mb-3">
    <label for="welcome_template_id" class="form-label">Welcome-Template</label>
    <select name="welcome_template_id" id="welcome_template_id" class="form-select">
      <option value="">-- Welcome-Template waehlen --</option>
      <?php foreach ($emailTemplates as $template): ?>
        <option value="<?= (int) $template['id'] ?>" <?= ((int) ($template['id'] ?? 0) === (int) ($list['welcome_template_id'] ?? 0)) ? 'selected' : '' ?>>
          <?= htmlspecialchars((string) $template['name'], ENT_QUOTES, 'UTF-8') ?> - <?= htmlspecialchars((string) $template['subject'], ENT_QUOTES, 'UTF-8') ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <button type="submit" class="btn btn-primary">Speichern</button>
  <a href="listen.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';