<?php

/**
 * AuthorizationService
 * Handles authentication and authorization for the AdsPreview system
 */
class AuthorizationService {
    
    /**
     * JWT-based authentication check for all API methods
     */
    public static function requireAuth() {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? null;
        
        if (!$authHeader || !preg_match('/^Bearer\s+(.*)$/i', $authHeader, $matches)) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'UNAUTHORIZED',
                    'message' => 'Kein gültiges Auth-Token übergeben.'
                ]
            ]);
            exit;
        }
        
        $jwt = $matches[1];
        require_once __DIR__ . '/AuthService.php';
        $user = AuthService::verifyJWT($jwt);
        
        if (!$user) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'UNAUTHORIZED',
                    'message' => 'Token ungültig oder abgelaufen.'
                ]
            ]);
            exit;
        }
        
        return $user;
    }
    
    /**
     * Check if the logged-in user can access the requested client directory
     */
    public static function requireClientAccess($clientDir) {
        $user = self::requireAuth();
        
        // Admins have general access, but check disallowedClients
        if (isset($user['role']) && $user['role'] === 'admin') {
            $adminData = self::getAdminData($user['username']);
            $disallowedClients = $adminData['disallowedClients'] ?? [];
            
            if (in_array($clientDir, $disallowedClients)) {
                http_response_code(403);
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => false,
                    'error' => [
                        'code' => 'FORBIDDEN',
                        'message' => "Zugriff auf Client '{$clientDir}' ist für diesen Administrator nicht erlaubt."
                    ]
                ]);
                exit;
            }
            return $user;
        }
        
        // Client users can only access their own directory
        if ($user['role'] === 'client' && $user['dir'] !== $clientDir) {
            http_response_code(403);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'FORBIDDEN',
                    'message' => 'Nicht berechtigt für diesen Bereich.'
                ]
            ]);
            exit;
        }
        
        return $user;
    }
    
    /**
     * Load admin data from storage
     */
    public static function getAdminData($username) {
        $adminFile = __DIR__ . '/../../storage/data/admins.json';
        if (file_exists($adminFile)) {
            $admins = json_decode(file_get_contents($adminFile), true);
            foreach ($admins as $admin) {
                if ($admin['username'] === $username) {
                    return $admin;
                }
            }
        }
        return [];
    }
    
    /**
     * Check if user is admin
     */
    public static function requireAdminAccess() {
        $user = self::requireAuth();
        if (!isset($user['role']) || $user['role'] !== 'admin') {
            http_response_code(403);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'FORBIDDEN',
                    'message' => 'Nur Administratoren können diese Funktion nutzen.'
                ]
            ]);
            exit;
        }
        return $user;
    }
}
