<?php
namespace App\Core;

class Middleware {
    public static function requireAuth(): void {
        if (!Auth::check()) {
            if (Request::isAjax()) {
                Response::error('Unauthenticated session.', 401);
            }
            Response::redirect('/login');
        }
    }

    public static function requireAdmin(): void {
        self::requireAuth();
        if (!Auth::isAdmin()) {
            if (Request::isAjax()) {
                Response::error('Forbidden: Administrator access required.', 403);
            }
            Response::redirect('/dashboard?error=unauthorized');
        }
    }

    public static function requireGuest(): void {
        if (Auth::check()) {
            Response::redirect('/dashboard');
        }
    }

    public static function verifyCSRF(): void {
        if (Request::getMethod() === 'POST') {
            $token = Request::post('csrf_token') ?? Request::header('X-CSRF-TOKEN');
            if (!CSRF::validate($token)) {
                if (Request::isAjax()) {
                    Response::error('Invalid or expired CSRF token.', 403);
                }
                die("CSRF Token verification failed. Please refresh the page and try again.");
            }
        }
    }
}
