<?php
declare(strict_types=1);

// send/versandpause_check.php
require_once __DIR__ . '/../includes/init.php';

$now = date('Y-m-d H:i:s');
ErrorLogger::log("Versandpause-Cronjob gestartet um $now", 'INFO');

try {
    $db = Database::getInstance();

    $sql = "
        SELECT rp.recipient_id, r.status, rp.pause_days, rp.pause_end
        FROM recipients_pause rp
        JOIN recipients r ON r.id = rp.recipient_id
        WHERE r.status = 'pause' AND rp.pause_end <= NOW()
    ";
    $stmt = $db->prepare($sql);
    $activateRecipientStmt = $db->prepare("UPDATE recipients SET status = 'active' WHERE id = ?");
    $loadListsStmt = $db->prepare("SELECT list_id FROM recipient_lists WHERE recipient_id = ?");
    $updatePauseTokenStmt = $db->prepare("UPDATE recipient_lists SET pause_token = ? WHERE recipient_id = ? AND list_id = ?");

    $stmt->execute();
    ErrorLogger::logSqlSuccess("Abgelaufene Versandpausen geladen | table: recipients_pause/recipients | context: " . json_encode(["status" => "pause"], JSON_UNESCAPED_UNICODE));
    $empfaenger = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($empfaenger)) {
        ErrorLogger::log("Keine abgelaufenen Versandpausen gefunden", 'INFO');
        return;
    }

    foreach ($empfaenger as $e) {
        $recipientId = $e['recipient_id'];

        $activateRecipientStmt->execute([$recipientId]);
        ErrorLogger::log("Empfänger $recipientId wieder aktiviert", 'INFO');

        $loadListsStmt->execute([$recipientId]);
        ErrorLogger::logSqlSuccess("Listen für Empfänger geladen | table: recipient_lists | context: " . json_encode(["recipient_id" => (int) $recipientId], JSON_UNESCAPED_UNICODE));
        $listen = $loadListsStmt->fetchAll(PDO::FETCH_COLUMN);

        foreach ($listen as $listId) {
            $newToken = bin2hex(random_bytes(32));
            $updatePauseTokenStmt->execute([$newToken, $recipientId, $listId]);
            ErrorLogger::log("Neuer Pause-Token für Empfänger $recipientId in Liste $listId gesetzt", 'INFO');
        }
    }

    ErrorLogger::log("Versandpause-Cronjob erfolgreich abgeschlossen", 'INFO');
} catch (Exception $e) {
    ErrorLogger::logSqlError("Fehler im Versandpause-Cronjob | context: versandpause_check | error: " . $e->getMessage());
    ErrorLogger::log("Fehler im Versandpause-Cronjob: " . $e->getMessage(), 'ERROR');
}
