<?php
/**
 * auth-guard.php
 * ZWECK: Automatischer Re-Login über "Remember Me" Cookies.
 */

// 0. PUTZKOMMANDO: Abgelaufene Tokens löschen
$pdo->exec("DELETE FROM public.\"{$config['userTokenTable']}\" WHERE expires_at < NOW()");

// Prüfen: Cookie vorhanden aber keine aktive Session?
if (isset($_COOKIE['remember_me']) && (!isset($_SESSION['uid']) || (int)$_SESSION['uid'] <= 1)) {
    
    $parts = explode(':', $_COOKIE['remember_me']);
    $selector = $parts[0] ?? '';
    $validator = $parts[1] ?? '';

    // 1. Token in der DB suchen
    $stmt = $pdo->prepare("SELECT * FROM public.\"{$config['userTokenTable']}\" WHERE selector = ? AND expires_at > NOW()");
    $stmt->execute([$selector]);
    $tokenRow = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($tokenRow && password_verify($validator, $tokenRow['token_hash'])) {
        
        // 2. Nutzer-Daten laden
        $stmtUser = $pdo->prepare("SELECT username FROM public.\"{$config['userTable']}\" WHERE uid = ?");
        $stmtUser->execute([$tokenRow['uid']]);
        $username = $stmtUser->fetchColumn();

        if ($username) {
            // --- SILENT LOGIN ERFOLGREICH ---
            $_SESSION['uid'] = (int)$tokenRow['uid'];
            $_SESSION['username'] = $username;
            $_SESSION['CREATED'] = time(); // Session-Timer zurücksetzen

            // WICHTIG: Alte Fehler-Zustände löschen, damit auth.php keinen 401 wirft
            unset($_SESSION['STATUS_EXPIRED']);
            unset($_SESSION['LAST_USER_NAME']);

            // 3. ROLLING EXPIRY: Token verlängern (z.B. 90 Tage)
            $remExpiry = $config['rememberMeExpirySeconds'] ?? 7776000;

            $pdo->prepare("UPDATE public.\"{$config['userTokenTable']}\" SET expires_at = NOW() + INTERVAL '$remExpiry seconds' WHERE selector = ?")
                ->execute([$selector]);

            setcookie('remember_me', $_COOKIE['remember_me'], [
                'expires' => time() + $remExpiry,
                'path' => '/',
                'secure' => true,
                'httponly' => true,
                'samesite' => 'Lax'
            ]);
        }
    }
}