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

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    die("Ungültige ID.");
}

$db = Database::getInstance();
$sqlLoadSender = "SELECT id FROM sender_identities WHERE id = ?";
try {
    $stmt = $db->prepare($sqlLoadSender);
    $stmt->execute([$id]);
    ErrorLogger::logSqlSuccess('absender_loeschen: load sender | SQL: ' . $sqlLoadSender . ' | params: ' . json_encode([$id], JSON_UNESCAPED_UNICODE));
    $sender = $stmt->fetch();
} catch (Throwable $e) {
    ErrorLogger::logSqlError('absender_loeschen: load sender failed | SQL: ' . $sqlLoadSender . ' | params: ' . json_encode([$id], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    die("Fehler beim Laden des Absenders.");
}

if (!$sender) {
    die("Absender nicht gefunden.");
}

try {
    $stmt = $db->prepare("DELETE FROM sender_identities WHERE id = ?");
    $stmt->execute([$id]);
    $userId = $_SESSION['admin_id'] ?? ($_SESSION['user_id'] ?? 0);
    if ($userId) {
        logSettingChange($userId, 'delete_sender_identity', 'sender_identities', json_encode([
            'id' => (int)$id
        ], JSON_UNESCAPED_UNICODE));
    }

    $_SESSION['success_message'] = "Absender wurde gelöscht.";
} catch (PDOException $e) {
    ErrorLogger::log("Fehler beim Löschen des Absenders: " . $e->getMessage());
}

header("Location: absender.php");
exit;

