<?php
// admin/empfaenger/empfaenger_delete.php
//
// ============================================================
//  EMPFÃ„NGER LÃ–SCHEN (HARD DELETE) â€“ inkl. aller Nutzer-Daten
// ============================================================
//
// Dieses Script lÃ¶scht einen EmpfÃ¤nger (Recipient) vollstÃ¤ndig
// aus dem System â€“ inklusive aller DatensÃ¤tze, die direkt oder
// indirekt dem EmpfÃ¤nger zugeordnet sind.
//
// ðŸ”¥ WICHTIGER HINWEIS (FK / CASCADE):
// - In deiner DB-Struktur existieren Foreign Keys mit ON DELETE CASCADE,
//   z.B. von send_queue -> recipients, und email_opens/link_tracking -> send_queue.
// - Trotzdem lÃ¶schen wir die wichtigsten Tabellen explizit, damit
//   a) alles nachvollziehbar geloggt wird,
//   b) keine â€œAltlastenâ€ bleiben (z.B. Daten ohne FK oder per Email gespeichert).
//
// ------------------------------------------------------------
// BETROFFENE TABELLEN (direkt / indirekt):
// ------------------------------------------------------------
// A) Direkt Ã¼ber recipient_id (EmpfÃ¤nger-ID):
//  1) email_bounces             - Bounces (recipient_id UND email vorhanden)
//  2) transaction_log           - Transaktions-Events pro EmpfÃ¤nger
//  3) pdf_download_stats        - PDF Download Tracking pro EmpfÃ¤nger
//  4) recipients_pause          - Pausenstatus pro EmpfÃ¤nger
//  5) recipient_tags            - Tag-Zuordnungen
//  6) recipient_custom_fields   - Custom-Felder (Definitionen separat)
//  7) recipient_fields          - Standard-Felder
//  8) recipient_list_optin      - DOI/Opt-In Nachweise (personenbezogen)
//  9) recipient_lists           - Listen-Zuordnung (Abos)
// 10) send_queue                - Versandqueue (FK zu recipients, CASCADE mÃ¶glich)
//
// B) Indirekt Ã¼ber queue_id (durch send_queue.id):
// 11) email_opens               - Ã–ffnungen (FK: queue_id -> send_queue.id, CASCADE)
// 12) email_link_tracking       - Klicktracking (FK: queue_id -> send_queue.id, CASCADE)
//
// C) Ãœber email (ohne recipient_id):
// 13) formular_logs             - Form-Log enthÃ¤lt email (personenbezogen)
// 14) password_resets           - Reset-Tokens nach email (falls EmpfÃ¤nger Login nutzt)
//
// D) Final:
// 15) recipients                - Hauptdatensatz des EmpfÃ¤ngers
//
// ------------------------------------------------------------
// MR9 Vorgaben:
// - Authentifizierung prÃ¼fen
// - SQL-Operationen mit ErrorLogger loggen (Success + Error)
// - try/catch + Transaction + Rollback
// - CodeblÃ¶cke ausfÃ¼hrlich kommentieren
// - Redirect mit Statusparametern (Hinweise werden im UI auto-dismissed)
// ------------------------------------------------------------

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';

// ------------------------------------------------------------
// 1) Auth prÃ¼fen
// ------------------------------------------------------------
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$db = Database::getInstance();

// ------------------------------------------------------------
// 2) EmpfÃ¤nger-ID validieren
// ------------------------------------------------------------
$id = $_GET['id'] ?? null;

if (!$id || !is_numeric($id)) {
    ErrorLogger::log("UngÃ¼ltige oder fehlende ID in empfaenger_delete.php: " . print_r($id, true), 'WARN');
    header('Location: empfaenger.php?error=invalid_id');
    exit;
}

$recipientId = (int)$id;

try {
    // ------------------------------------------------------------
    // 3) EmpfÃ¤nger laden (E-Mail wird fÃ¼r email-basierte Tabellen benÃ¶tigt)
    // ------------------------------------------------------------
    $stmt = $db->prepare("SELECT id, email FROM recipients WHERE id = ? LIMIT 1");
    $stmt->execute([$recipientId]);

    ErrorLogger::logSqlSuccess("EmpfÃ¤nger fÃ¼r LÃ¶schung geladen | table: recipients | context: " . json_encode(['recipient_id' => $recipientId], JSON_UNESCAPED_UNICODE));

    $recipient = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$recipient) {
        ErrorLogger::log("EmpfÃ¤nger nicht gefunden (Delete): recipients.id={$recipientId}", 'INFO');
        header('Location: empfaenger.php?error=not_found');
        exit;
    }

    $email = (string)($recipient['email'] ?? '');

    // ------------------------------------------------------------
    // 4) Transaktion starten â€“ Konsistenz sicherstellen
    // ------------------------------------------------------------
    $db->beginTransaction();

    // ZÃ¤hler fÃ¼r Redirect/Debug (optional)
    $deleted = [
        'email_bounces'           => 0,
        'transaction_log'         => 0,
        'pdf_download_stats'      => 0,
        'recipients_pause'        => 0,
        'recipient_tags'          => 0,
        'recipient_custom_fields' => 0,
        'recipient_fields'        => 0,
        'recipient_list_optin'    => 0,
        'recipient_lists'         => 0,
        'send_queue'              => 0,
        // indirekt via queue_id (wird durch FK meist automatisch gelÃ¶scht)
        'email_opens'             => 0,
        'email_link_tracking'     => 0,
        // email-basiert
        'formular_logs'           => 0,
        'password_resets'         => 0,
        'member_password_resets'  => 0,
        // final
        'recipients'              => 0,
    ];

    // ------------------------------------------------------------
    // 5) Indirekte Tabellen (queue_id) â€“ optional explizit lÃ¶schen
    //    Vorteil: wir loggen die LÃ¶schzahlen sauber.
    //    Vorgehen:
    //    - Zuerst alle send_queue IDs fÃ¼r diesen EmpfÃ¤nger holen
    //    - Dann opens & link_tracking per IN(...) lÃ¶schen
    // ------------------------------------------------------------
    $queueIds = [];
    $stmt = $db->prepare("SELECT id FROM send_queue WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);

    ErrorLogger::logSqlSuccess("Queue-IDs fÃ¼r EmpfÃ¤nger geladen (fÃ¼r Tracking-LÃ¶schung) | table: send_queue | context: " . json_encode(['recipient_id' => $recipientId], JSON_UNESCAPED_UNICODE));

    $queueIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($queueIds)) {
        // Dynamische Platzhalter fÃ¼r IN(...)
        $placeholders = implode(',', array_fill(0, count($queueIds), '?'));

        // 5.1) email_opens lÃ¶schen
        $stmt = $db->prepare("DELETE FROM email_opens WHERE queue_id IN ($placeholders)");
        $stmt->execute($queueIds);
        $deleted['email_opens'] = $stmt->rowCount();
        ErrorLogger::logSqlSuccess("Email-Ã–ffnungen gelÃ¶scht (email_opens) | table: email_opens | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['email_opens']], JSON_UNESCAPED_UNICODE));

        // 5.2) email_link_tracking lÃ¶schen
        $stmt = $db->prepare("DELETE FROM email_link_tracking WHERE queue_id IN ($placeholders)");
        $stmt->execute($queueIds);
        $deleted['email_link_tracking'] = $stmt->rowCount();
        ErrorLogger::logSqlSuccess("Email-Link-Tracking gelÃ¶scht (email_link_tracking) | table: email_link_tracking | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['email_link_tracking']], JSON_UNESCAPED_UNICODE));
    }

    // ------------------------------------------------------------
    // 6) email_bounces lÃ¶schen
    //    - LÃ¶schen per recipient_id
    //    - UND zusÃ¤tzlich per email (falls EintrÃ¤ge ohne korrekte ID existieren)
    // ------------------------------------------------------------
    $stmt = $db->prepare("
        DELETE FROM email_bounces
        WHERE recipient_id = ?
           OR (email = ? AND email <> '')
    ");
    $stmt->execute([$recipientId, $email]);
    $deleted['email_bounces'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Email-Bounces gelÃ¶scht | table: email_bounces | context: " . json_encode(['recipient_id' => $recipientId, 'email' => $email, 'deleted_rows' => $deleted['email_bounces']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 7) transaction_log lÃ¶schen (EmpfÃ¤nger-Events)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM transaction_log WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['transaction_log'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Transaction-Log-EintrÃ¤ge gelÃ¶scht | table: transaction_log | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['transaction_log']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 8) pdf_download_stats lÃ¶schen (Download-Tracking)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM pdf_download_stats WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['pdf_download_stats'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("PDF-Download-Stats gelÃ¶scht | table: pdf_download_stats | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['pdf_download_stats']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 9) recipients_pause lÃ¶schen (Pause-Daten)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipients_pause WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['recipients_pause'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Recipients-Pause gelÃ¶scht | table: recipients_pause | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipients_pause']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 10) recipient_tags lÃ¶schen (Tags)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipient_tags WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['recipient_tags'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Recipient-Tags gelÃ¶scht | table: recipient_tags | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipient_tags']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 11) recipient_custom_fields lÃ¶schen (Custom-Felder)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipient_custom_fields WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['recipient_custom_fields'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Recipient-Custom-Fields gelÃ¶scht | table: recipient_custom_fields | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipient_custom_fields']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 12) recipient_fields lÃ¶schen (Standard-Felder)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipient_fields WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['recipient_fields'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Recipient-Fields gelÃ¶scht | table: recipient_fields | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipient_fields']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 13) recipient_list_optin lÃ¶schen (DOI/Opt-In Nachweise)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipient_list_optin WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['recipient_list_optin'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Recipient-List-Optin (DOI) gelÃ¶scht | table: recipient_list_optin | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipient_list_optin']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 14) recipient_lists lÃ¶schen (Listen-Abos)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipient_lists WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['recipient_lists'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Recipient-Lists (Listen-Abos) gelÃ¶scht | table: recipient_lists | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipient_lists']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 15) send_queue lÃ¶schen (Versandqueue)
    //     Hinweis:
    //     - In DB ist FK recipient_id -> recipients ON DELETE CASCADE gesetzt.
    //     - Wir lÃ¶schen trotzdem explizit, damit geloggt wird und auch
    //       eventuell â€œhÃ¤ngendeâ€ Queue-EintrÃ¤ge vor dem recipients-delete weg sind.
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM send_queue WHERE recipient_id = ?");
    $stmt->execute([$recipientId]);
    $deleted['send_queue'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("Send-Queue EintrÃ¤ge gelÃ¶scht | table: send_queue | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['send_queue']], JSON_UNESCAPED_UNICODE));

    // ------------------------------------------------------------
    // 16) Email-basierte Tabellen (ohne recipient_id)
    //     -> lÃ¶schen nach Email-Adresse (personenbezogen)
    // ------------------------------------------------------------
    if ($email !== '') {
        // 16.1) formular_logs (Formular-Aktionen, IP etc.)
        $stmt = $db->prepare("DELETE FROM formular_logs WHERE email = ?");
        $stmt->execute([$email]);
        $deleted['formular_logs'] = $stmt->rowCount();

        ErrorLogger::logSqlSuccess("Formular-Logs gelÃ¶scht (email-basiert) | table: formular_logs | context: " . json_encode(['email' => $email, 'deleted_rows' => $deleted['formular_logs']], JSON_UNESCAPED_UNICODE));

        // 16.2) password_resets (Reset Tokens)
        $stmt = $db->prepare("DELETE FROM password_resets WHERE email = ?");
        $stmt->execute([$email]);
        $deleted['password_resets'] = $stmt->rowCount();

        ErrorLogger::logSqlSuccess("Password-Resets gelÃ¶scht (email-basiert) | table: password_resets | context: " . json_encode(['email' => $email, 'deleted_rows' => $deleted['password_resets']], JSON_UNESCAPED_UNICODE));
    }

    // ------------------------------------------------------------
    // 17) FINAL: recipients lÃ¶schen (Hauptdatensatz)
    // ------------------------------------------------------------
    $stmt = $db->prepare("DELETE FROM recipients WHERE id = ? LIMIT 1");
    $stmt->execute([$recipientId]);
    $deleted['recipients'] = $stmt->rowCount();

    ErrorLogger::logSqlSuccess("EmpfÃ¤nger gelÃ¶scht (recipients) | table: recipients | context: " . json_encode(['recipient_id' => $recipientId, 'deleted_rows' => $deleted['recipients']], JSON_UNESCAPED_UNICODE));

    // Wenn EmpfÃ¤nger nicht gelÃ¶scht wurde -> Rollback
    if ($deleted['recipients'] < 1) {
        $db->rollBack();
        ErrorLogger::log("Rollback: recipients konnte nicht gelÃ¶scht werden (rowCount=0), id={$recipientId}", 'WARN');
        header('Location: empfaenger.php?error=delete_failed');
        exit;
    }

    // ------------------------------------------------------------
    // 18) Commit â€“ alles erfolgreich gelÃ¶scht
    // ------------------------------------------------------------
    $db->commit();

    // ------------------------------------------------------------
    // 19) Redirect (optional mit Summen â€“ hilfreich fÃ¼rs Debugging)
    // ------------------------------------------------------------
    header('Location: empfaenger.php?success=deleted'
        . '&b=' . urlencode((string)$deleted['email_bounces'])
        . '&q=' . urlencode((string)$deleted['send_queue'])
        . '&o=' . urlencode((string)$deleted['email_opens'])
        . '&c=' . urlencode((string)$deleted['email_link_tracking'])
    );
    exit;

} catch (PDOException $e) {
    // ------------------------------------------------------------
    // SQL-Fehler: Rollback + SQL-Error loggen
    // ------------------------------------------------------------
    if ($db->inTransaction()) {
        $db->rollBack();
    }

    ErrorLogger::logSqlError("Fehler beim Hard-Delete des EmpfÃ¤ngers (inkl. aller Tabellen) | file: empfaenger_delete.php | context: " . json_encode(['recipient_id' => $recipientId], JSON_UNESCAPED_UNICODE) . " | error: " . $e->getMessage());

    header('Location: empfaenger.php?error=delete_failed');
    exit;

} catch (Exception $e) {
    // ------------------------------------------------------------
    // Allgemeiner Fehler: Rollback + Log
    // ------------------------------------------------------------
    if ($db->inTransaction()) {
        $db->rollBack();
    }

    ErrorLogger::log(
        "Allgemeiner Fehler in empfaenger_delete.php: " . $e->getMessage(),
        'ERROR'
    );

    header('Location: empfaenger.php?error=delete_failed');
    exit;
}

