<?php
class AuthMiddleware {
    public static function authenticate($type = 'customer') {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (empty($authHeader) || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            jsonResponse(false, 'Unauthorized', ['error' => 'Missing or invalid Authorization header'], null, 401);
        }

        $token = $matches[1];
        $payload = verifyJWT($token);

        if (!$payload) {
            jsonResponse(false, 'Unauthorized', ['error' => 'Invalid or expired token'], null, 401);
        }

        if ($payload['type'] !== $type) {
            jsonResponse(false, 'Forbidden', ['error' => 'Insufficient permissions'], null, 403);
        }

        // Make user data globally accessible for the request lifecycle
        $GLOBALS['user'] = $payload;
        return $payload;
    }
}
