<?php

declare(strict_types=1);

namespace ServerManager\Middleware;

use ServerManager\Core\Session;

class AuthMiddleware
{
    public function handle(): mixed
    {
        if (!Session::has('user_id')) {
            Session::setFlash('error', 'You must be logged in to access this page.');
            $this->redirect('/login');
        }

        if (Session::get('session_expiry') && time() > Session::get('session_expiry')) {
            Session::destroy();
            Session::setFlash('error', 'Your session has expired. Please log in again.');
            $this->redirect('/login');
        }

        return null;
    }

    private function redirect(string $url): never
    {
        if (!headers_sent()) {
            header("Location: {$url}");
        } else {
            echo '<script>window.location.href="' . $url . '";</script>';
        }
        exit;
    }
}
