<?php
// inc/check_login.php
include('db.php');

session_start();

if (!isset($_SESSION['user_id']) && isset($_COOKIE['remember_token'])) {
    $token = $_COOKIE['remember_token'];

    // Prüfen, ob der Token in der Datenbank existiert und gültig ist
    $sql = "SELECT users.id, users.username, users.email, users.role FROM login_tokens JOIN users ON login_tokens.user_id = users.id WHERE login_tokens.token = ? AND login_tokens.expires_at > NOW()";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "s", $token);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);

    if ($user) {
        // Token ist gültig, alle Benutzerdaten in die Session laden
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['role'] = $user['role'];

        // Optional: Ablaufdatum des Tokens verlängern (Rolling Expiration)
        $new_expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));
        $update_sql = "UPDATE login_tokens SET expires_at = ? WHERE token = ?";
        $update_stmt = mysqli_prepare($conn, $update_sql);
        mysqli_stmt_bind_param($update_stmt, "ss", $new_expires_at, $token);
        mysqli_stmt_execute($update_stmt);
    } else {
        // Token ist ungültig oder abgelaufen, Cookie löschen
        setcookie('remember_token', '', time() - 3600, "/");
    }
}

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
