<?php
/**
 * Simple Authentication Middleware
 */

declare(strict_types=1);

namespace App\Middleware;

use App\Core\JWT;

final class AuthMiddleware
{
    public static function check(): array
    {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (!str_starts_with($authHeader, 'Bearer ')) {
            json_error('Unauthorized: Missing or invalid token', 401);
        }

        $token = substr($authHeader, 7);
        $secret = env('JWT_SECRET');
        
        if (!$secret || strlen($secret) < 32) {
            error_log('FATAL: JWT_SECRET is missing or too short');
            json_error('Server configuration error', 500);
        }
        
        $decoded = JWT::decode($token, $secret);
        
        if (!$decoded) {
            // Check if it's specifically expired if your JWT class supports it, 
            // otherwise just send the standard 401 with a code.
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'انتهت صلاحية الجلسة',
                'code'    => 'TOKEN_EXPIRED',
                'redirect'=> '/login.php'
            ]);
            exit;
        }

        return $decoded;
    }
}
