<?php
namespace App\Middleware;
use App\Core\Library\Crypto;

class AuthGuard
{
    public static function handle()
    {

        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? null;

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized - Missing token']);
            exit;
        }

        $token = trim(substr($authHeader, 7));

        try {
            $decoded = Crypto::decryptJwtToken($token);

            // Get the user data from the decoded token 
            if (!isset($decoded->id) || !isset($decoded->comp_id)) {
                throw new \Exception('Invalid token structure');
            }

            $_SERVER['HTTP_USER_DATA'] = $decoded;
        } catch (\Exception $e) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized - Invalid token', 'message' => $e->getMessage()]);
            exit;
        }
    }
}
