
<?php
// Explizit Header setzen vor jeder Ausgabe
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

// Preflight OPTIONS Requests explizit beantworten und beenden
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

class Router {
        
    public static function handle() {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = $_SERVER['REQUEST_METHOD'];

        if ($uri === '/api/auth/login' && $method === 'POST') {
            require_once __DIR__ . '/../Api/AuthController.php';
            AuthController::login();
            return;
        }
        if ($uri === '/api/auth/user' && $method === 'GET') {
            require_once __DIR__ . '/../Api/UserController.php';
            UserController::currentUser();
            return;
        }
        // Admin: Benutzerliste
        if ($uri === '/api/admin/users' && $method === 'GET') {
            require_once __DIR__ . '/../Services/AuthService.php';
            $headers = getallheaders();
            $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
            $token = str_replace('Bearer ', '', $auth);
            $user = AuthService::verifyJWT($token);

            if ($user && $user['role'] === 'admin') {
                require_once __DIR__ . '/../Api/UserController.php';
                UserController::listAll();
                return;
            } else {
                http_response_code(403);
                echo json_encode([
                    'success' => false,
                    'error' => [
                        'code' => 'FORBIDDEN',
                        'message' => 'Nicht berechtigt.'
                    ]
                ]);
                return;
            }
        }

        // Admin: Benutzer anlegen
        if ($uri === '/api/admin/users' && $method === 'POST') {
            require_once __DIR__ . '/../Services/AuthService.php';
            $headers = getallheaders();
            $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
            $token = str_replace('Bearer ', '', $auth);
            $user = AuthService::verifyJWT($token);

            if ($user && $user['role'] === 'admin') {
                require_once __DIR__ . '/../Api/UserController.php';
                UserController::create();
                return;
            } else {
                http_response_code(403);
                echo json_encode([
                    'success' => false,
                    'error' => [
                        'code' => 'FORBIDDEN',
                        'message' => 'Nicht berechtigt.'
                    ]
                ]);
                return;
            }
        }

        // Parametrisierte Admin CRUD für Users & Clients
        if (preg_match('#^/api/admin/(users|clients)(?:/(\d+))?$#', $uri, $m)) {
            require_once __DIR__ . '/../Api/EntityController.php';
            $type = $m[1];
            $id = isset($m[2]) ? (int)$m[2] : null;
            switch ($method) {
                case 'GET':
                    EntityController::list($type);
                    break;
                case 'POST':
                    EntityController::create($type);
                    break;
                case 'PUT':
                    EntityController::update($type, $id);
                    break;
                case 'DELETE':
                    EntityController::delete($type, $id);
                    break;
            }
            return;
        }

        // Passwort-Update Route
        if (preg_match('#^/api/admin/(users|clients)/(\d+)/password$#', $uri, $m) && $method === 'PUT') {
            require_once __DIR__ . '/../Api/EntityController.php';
            $type = $m[1];
            $id = (int)$m[2];
            EntityController::updatePassword($type, $id);
            return;
        }

        // Projekt→Client Mapping für Admin Smart URL Resolution
        if ($uri === '/api/admin/project-client-mapping' && $method === 'GET') {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            ProjectsController::getProjectClientMapping();
            return;
        }

        if ($uri === '/api/projects' && $method === 'GET') {
            require_once __DIR__ . '/../Services/AuthService.php';
            $headers = getallheaders();
            $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
            $token = str_replace('Bearer ', '', $auth);
            $user = AuthService::verifyJWT($token);

            file_put_contents(__DIR__ . '/user_debug.log', date('c') . ' AUTH: ' . var_export($auth, true) . ' TOKEN: ' . var_export($token, true) . PHP_EOL, FILE_APPEND);

            if ($user && $user['role'] === 'client' && !empty($user['dir'])) {
                require_once __DIR__ . '/../Api/ProjectsController.php';
                ProjectsController::listForClient($user['dir']);
                return;
            } else {
                http_response_code(403);
                echo json_encode([
                    'success' => false,
                    'error' => [
                        'code' => 'FORBIDDEN',
                        'message' => 'Nicht berechtigt oder kein Client.'
                    ]
                ]);
                return;
            }
        }

        // Admin: Benutzer löschen
        if (preg_match('#^/api/admin/users/(\d+)$#', $uri, $m) && $method === 'DELETE') {
            require_once __DIR__ . '/../Services/AuthService.php';
            $headers = getallheaders();
            $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
            $token = str_replace('Bearer ', '', $auth);
            $user = AuthService::verifyJWT($token);

            if ($user && $user['role'] === 'admin') {
                require_once __DIR__ . '/../Api/UserController.php';
                UserController::delete((int)$m[1]);
                return;
            } else {
                http_response_code(403);
                echo json_encode([
                    'success' => false,
                    'error' => [
                        'code' => 'FORBIDDEN',
                        'message' => 'Nicht berechtigt.'
                    ]
                ]);
                return;
            }
        }

        // Test-Route für area-Zugriff
        if (preg_match('#^/api/test/([^/]+)$#', $uri, $m)) {
            $value = urldecode($m[1]);
            $base = __DIR__ . "/../../area/$value";
            $real = realpath($base);
            $result = [
                'requested' => $base,
                'realpath' => $real,
                'is_dir' => $real && is_dir($real),
                'is_readable' => $real && is_readable($real),
                'files' => $real && is_dir($real) ? scandir($real) : null
            ];
            header('Content-Type: application/json');
            echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
            return;
        }

        // Projekt-Reihenfolge speichern
        if (preg_match('#^/api/projects/([^/]+)/project-order$#', $uri, $m) && $method === 'POST') {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            $clientDir = urldecode($m[1]);
            ProjectsController::saveProjectOrder($clientDir);
            return;
        }

        // Einzelnes Projekt-Objekt (inkl. Logo, Poster etc.)
        if (preg_match('#^/api/projects/([^/]+)/([^/]+)$#', $uri, $m) && $method === 'GET') {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            $clientDir = urldecode($m[1]);
            $projectName = urldecode($m[2]);
            ProjectsController::projectDetails($clientDir, $projectName);
            return;
        }

        // Rekursive Ads-Übersicht als Baumstruktur (muss VOR der generischen /ads-Route stehen!)
        if (preg_match('#^/api/projects/([^/]+)/([^/]+)/ads-overview$#', $uri, $m)) {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            $clientDir = urldecode($m[1]);
            $projectName = urldecode($m[2]);
            ProjectsController::adsOverview($clientDir, $projectName);
            return;
        }


        // Endpunkt für config.yaml in beliebiger Tiefe: /ads/.../config.yaml
        if (preg_match('#^/api/projects/([^/]+)/([^/]+)/ads/(.+)/config\.yaml$#', $uri, $m)) {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            $clientDir = urldecode($m[1]);
            $projectName = urldecode($m[2]);
            $folders = array_map('urldecode', explode('/', $m[3]));
            ProjectsController::getConfig($clientDir, $projectName, ...$folders);
            return;
        }

        // Endpunkt für Dateien in beliebiger Tiefe: /ads/.../files
        if (preg_match('#^/api/projects/([^/]+)/([^/]+)/ads/(.+)/files$#', $uri, $m)) {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            $clientDir = urldecode($m[1]);
            $projectName = urldecode($m[2]);
            $folders = array_map('urldecode', explode('/', $m[3]));
            ProjectsController::adsFolderFiles($clientDir, $projectName, ...$folders);
            return;
        }
        // Endpunkt für Unterordner in beliebiger Tiefe: /ads/... (aber nicht /files)
        if (preg_match('#^/api/projects/([^/]+)/([^/]+)/ads(?:/(.+))?$#', $uri, $m) && (empty($m[3]) || !preg_match('#/files$#', $uri))) {
            require_once __DIR__ . '/../Api/ProjectsController.php';
            $clientDir = urldecode($m[1]);
            $projectName = urldecode($m[2]);
            if (empty($m[3])) {
                // Nur Tab-Ordner für /ads
                ProjectsController::adsFolders($clientDir, $projectName);
            } else {
                // Sowohl Ordner als auch Dateien für tiefere Pfade
                $folders = array_map('urldecode', explode('/', $m[3]));
                ProjectsController::adsFolderContent($clientDir, $projectName, ...$folders);
            }
            return;
        }

        // 404
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error' => [
                'code' => 'NOT_FOUND',
                'message' => 'Route nicht gefunden.'
            ]
        ]);
    }
}
