<?php
// check_auth.php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 1. DATEIEN LADEN (Damit das Skript weiß, wer $pdo ist)
$debugLogFile = __DIR__ . '/check_auth_debug.log';
require_once __DIR__ . '/logging_functions.php';
$dbConfig = require __DIR__ . '/db-connection.php';

try {
    // 2. DATENBANK-VERBINDUNG AUFBAUEN
    $dsn = "pgsql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['dbname']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

    // Zeitzone zwingen (Wichtig für NOW() Abgleich)
    $pdo->exec("SET TIME ZONE 'Europe/Berlin'");

} catch (PDOException $e) {
    die("Fehler: Keine Verbindung zur Datenbank möglich.");
}

$cookieToken = $_COOKIE['remember_me'] ?? null;
$sessionUid = $_SESSION['uid'] ?? null;

// ==========================================
// 2. AUTH-GUARD (DER STILLE LOGIN)
// ==========================================
if (!$sessionUid && $cookieToken) {
    $parts = explode(':', $cookieToken);
    if (count($parts) === 2) {
        $selector = $parts[0];
        $validator = $parts[1];

        $sql = "SELECT * FROM user_tokens_test WHERE selector = ? AND expires_at > NOW()";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$selector]);
        $tokenRow = $stmt->fetch();

        if ($tokenRow && password_verify($validator, $tokenRow['token_hash'])) {
            $_SESSION['uid'] = $tokenRow['uid'];
            $sessionUid = $tokenRow['uid'];
            internal_debug_log("Dashboard Guard: Silent Login erfolgreich (UID: $sessionUid)", $debugLogFile);
        } else {
            internal_debug_log("Dashboard Guard: Login fehlgeschlagen (Abgelaufen oder ungültig)", $debugLogFile);
        }
    }
}

echo "<h2>🔐 Auth-System Test-Dashboard</h2>";

// FORMULAR FÜR MANUELLE UID-EINGABE
echo "<div style='background: #f4f4f4; padding: 15px; margin-bottom: 20px; border-radius: 5px;'>
        <form method='GET'>
            <input type='hidden' name='action' value='login'>
            <label><b>Test-UID festlegen:</b> </label>
            <input type='number' name='custom_uid' value='" . ($sessionUid ?? 9) . "' style='width: 60px;'>
            <button type='submit'>Login simulieren (10 Sek. Token)</button>
        </form>
      </div>";

echo "<table border='1' cellpadding='10' style='border-collapse: collapse; font-family: sans-serif; width: 100%;'>";
echo "<tr><th>Komponente</th><th>Status</th><th>Erklärung</th></tr>";

echo "<tr>
        <td><b>PHP Session</b></td>
        <td>" . ($sessionUid ? "✅ Aktiv (UID: $sessionUid)" : "❌ Inaktiv") . "</td>
        <td>Verschwindet bei 'NUR Session löschen'.</td>
      </tr>";

echo "<tr>
        <td><b>Langzeit-Cookie</b></td>
        <td>" . ($cookieToken ? "✅ Vorhanden" : "❌ Fehlt") . "</td>
        <td>Bleibt im Browser erhalten.</td>
      </tr>";

echo "</table>";

echo "<h3>Aktionen:</h3>";
echo "<ul>
        <li><a href='?action=kill_session'>1. NUR Session löschen</a> (Testet den Guard)</li>
        <li><a href='?action=logout'>2. Komplett Logout</a> (Reset)</li>
        <li><a href='check_auth.php'>3. Dashboard aktualisieren</a></li>
      </ul>";

// ==========================================
// 3. LOGIK FÜR DIE AKTIONEN
// ==========================================
if (isset($_GET['action'])) {
    
    if ($_GET['action'] == 'login') {
        $targetUid = $_GET['custom_uid'] ?? 9;
        $_SESSION['uid'] = $targetUid;

        $selector = bin2hex(random_bytes(8));
        $validator = bin2hex(random_bytes(32));
        $token_hash = password_hash($validator, PASSWORD_DEFAULT);

        try {
            $sql = "INSERT INTO user_tokens_test (uid, selector, token_hash, expires_at) 
                    VALUES (?, ?, ?, NOW() + INTERVAL '10 seconds')";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$targetUid, $selector, $token_hash]);

            setcookie('remember_me', $selector . ':' . $validator, time() + 3600, "/", "", true, true);
            internal_debug_log("Dashboard: Token erstellt (UID: $targetUid)", $debugLogFile);
        } catch (PDOException $e) {
            internal_debug_log("Dashboard ERROR: " . $e->getMessage(), $debugLogFile);
        }
        
        header("Location: check_auth.php");
        exit;
    }

    if ($_GET['action'] == 'kill_session') {
        $_SESSION = [];
        session_destroy();
        header("Location: check_auth.php");
        exit;
    }

    if ($_GET['action'] == 'logout') {
        if ($cookieToken) {
            $parts = explode(':', $cookieToken);
            $pdo->prepare("DELETE FROM user_tokens_test WHERE selector = ?")->execute([$parts[0]]);
        }
        $_SESSION = [];
        session_destroy();
        setcookie('remember_me', '', time() - 3600, "/");
        header("Location: check_auth.php");
        exit;
    }
}
?>