<?php
// admin/listen_delete.php

// Session und Abhängigkeiten laden
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();
$error = '';

$listId = $_GET['id'] ?? null;
if (!$listId || !is_numeric($listId)) {
    http_response_code(400);
    echo 'Ungültige Listen-ID.';
    exit;
}

try {
    // Liste laden
    $stmt = $db->prepare('SELECT * FROM lists WHERE id = ?');
    $stmt->execute([$listId]);
    ErrorLogger::logSqlSuccess('Liste für Löschung geladen | table: lists | context: ' . json_encode(['list_id' => (int) $listId], JSON_UNESCAPED_UNICODE));
    $listData = $stmt->fetch();

    if (!$listData) {
        throw new Exception('Liste nicht gefunden.');
    }

    // Zugehörige Templates löschen (wenn vorhanden)
    if (!empty($listData['doi_template_id'])) {
        $db->prepare('DELETE FROM email_templates WHERE id = ?')->execute([$listData['doi_template_id']]);
        ErrorLogger::logSqlSuccess('DOI-Template gelöscht | table: email_templates | context: ' . json_encode(['template_id' => (int) $listData['doi_template_id']], JSON_UNESCAPED_UNICODE));
    }
    if (!empty($listData['welcome_template_id'])) {
        $db->prepare('DELETE FROM email_templates WHERE id = ?')->execute([$listData['welcome_template_id']]);
        ErrorLogger::logSqlSuccess('Welcome-Template gelöscht | table: email_templates | context: ' . json_encode(['template_id' => (int) $listData['welcome_template_id']], JSON_UNESCAPED_UNICODE));
    }

    // Liste löschen
    $db->prepare('DELETE FROM lists WHERE id = ?')->execute([$listId]);
    ErrorLogger::logSqlSuccess('Liste gelöscht | table: lists | context: ' . json_encode(['list_id' => (int) $listId], JSON_UNESCAPED_UNICODE));

    $userId = $_SESSION['admin_id'] ?? ($_SESSION['user_id'] ?? 0);
    if ($userId) {
        logSettingChange($userId, 'delete_list', 'lists', json_encode([
            'list_id' => (int) $listId,
            'name' => $listData['name'] ?? null,
            'doi_template_id' => $listData['doi_template_id'] ?? null,
            'welcome_template_id' => $listData['welcome_template_id'] ?? null,
        ], JSON_UNESCAPED_UNICODE));
    }

    // Logging
    ErrorLogger::log("Liste #$listId wurde gelöscht", 'INFO');

    // Redirect
    header('Location: listen.php');
    exit;
} catch (Exception $e) {
    ErrorLogger::logSqlError('Fehler beim Löschen der Liste | table: lists | error: ' . $e->getMessage());
    $error = 'Fehler beim Löschen: ' . $e->getMessage();
    ErrorLogger::log($error, 'ERROR');
}

$title = 'Liste löschen';
ob_start();
?>
<div class="page-header h2">🗑️ Liste löschen</div>

<?php if ($error): ?>
  <div class="alert alert-danger auto-dismiss">❌ <?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<a href="listen.php" class="btn btn-secondary">Zurück</a>

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

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