<?php
require_once 'includes/init.php';

$db = Database::getInstance();

$token = $_GET['token'] ?? null;
$message = '';
$type = 'error';
$pause = null;

if ($token == 'test') { echo '<h1>Danke für ihren Test</h1>'; exit; }

if ($token) {
    $sqlLoadToken = "
        SELECT rl.recipient_id, rl.list_id, r.email
        FROM recipient_lists rl
        JOIN recipients r ON r.id = rl.recipient_id
        WHERE rl.pause_token = ?
    ";

    try {
        $stmt = $db->prepare($sqlLoadToken);
        $stmt->execute([$token]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        ErrorLogger::logSqlSuccess('versandpause: load token | SQL: ' . $sqlLoadToken . ' | params: ' . json_encode([$token], JSON_UNESCAPED_UNICODE));

        if ($data) {
            $recipient_id = $data['recipient_id'];
            $list_id = $data['list_id'];
            $email = $data['email'];

            $sqlLoadPause = "
                SELECT * FROM recipients_pause
                WHERE recipient_id = ? AND NOW() <= pause_end
                ORDER BY pause_end DESC LIMIT 1
            ";
            $stmt = $db->prepare($sqlLoadPause);
            $stmt->execute([$recipient_id]);
            $pause = $stmt->fetch(PDO::FETCH_ASSOC);
            ErrorLogger::logSqlSuccess('versandpause: load active pause | SQL: ' . $sqlLoadPause . ' | params: ' . json_encode([$recipient_id], JSON_UNESCAPED_UNICODE));

            if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$pause) {
                $pause_days = max(1, min(90, (int)($_POST['pause_days'] ?? 0)));
                $pause_start = date('Y-m-d H:i:s');

                $sqlInsertPause = 'INSERT INTO recipients_pause (recipient_id, pause_start, pause_days) VALUES (?, ?, ?)';
                $stmt = $db->prepare($sqlInsertPause);
                $stmt->execute([$recipient_id, $pause_start, $pause_days]);
                ErrorLogger::logSqlSuccess('versandpause: insert pause | SQL: ' . $sqlInsertPause . ' | params: ' . json_encode([$recipient_id, $pause_start, $pause_days], JSON_UNESCAPED_UNICODE));

                $sqlUpdateRecipient = "UPDATE recipients SET status = 'pause' WHERE id = ?";
                $stmt = $db->prepare($sqlUpdateRecipient);
                $stmt->execute([$recipient_id]);
                ErrorLogger::logSqlSuccess('versandpause: update recipient status | SQL: ' . $sqlUpdateRecipient . ' | params: ' . json_encode([$recipient_id], JSON_UNESCAPED_UNICODE));

                $message = "Deine Versandpause wurde aktiviert. Du erhältst für die nächsten <strong>{$pause_days} Tage</strong> keine E-Mails.";
                $type = 'success';
            } elseif ($pause) {
                $message = "Für deine E-Mail <strong>{$email}</strong> besteht bereits eine Versandpause bis <strong>" . date('d.m.Y H:i', strtotime($pause['pause_end'])) . '</strong>.';
                $type = 'info';
            }
        } else {
            $message = 'Ungültiger oder abgelaufener Link.';
            $type = 'error';
        }
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('versandpause: workflow failed | params: ' . json_encode([$token], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
        $message = 'Interner Fehler. Bitte versuchen Sie es später erneut.';
        $type = 'error';
    }
} else {
    $message = 'Zugriff verweigert. Kein gültiger Token.';
    $type = 'error';
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Versandpause</title>
    <link rel="stylesheet" href="templates/style.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 30px;
            background: #f7f7f7;
        }
        .container {
            background: #fff;
            padding: 30px;
            max-width: 600px;
            margin: 40px auto;
            border-radius: 8px;
            box-shadow: 0 0 12px rgba(0,0,0,0.1);
        }
        h2 {
            color: #333;
        }
        .msg.success { background: #e0f8e0; border-left: 5px solid #4CAF50; padding: 15px; }
        .msg.error   { background: #ffe0e0; border-left: 5px solid #f44336; padding: 15px; }
        .msg.info    { background: #e7f1ff; border-left: 5px solid #2196F3; padding: 15px; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Versandpause</h2>

        <?php if ($message): ?>
            <div class="msg <?= $type ?>">
                <?= $message ?>
            </div>
        <?php endif; ?>

        <?php if ($token && !$pause && $type !== 'success'): ?>
            <form method="post" class="mt-4">
                <label for="pause_days">Wie viele Tage möchtest du pausieren?</label>
                <input type="number" name="pause_days" id="pause_days" class="form-control" min="1" max="90" value="7" required>
                <button type="submit" class="btn btn-primary mt-2">Pause aktivieren</button>
            </form>
        <?php endif; ?>

        <p class="mt-4"><a href="https://<?= $_SERVER['HTTP_HOST'] ?>">Zur Startseite</a></p>
    </div>
</body>
</html>
