<?php
class App
{
    private Router $router;
    private Request $request;

    public function __construct()
    {
        $this->request = new Request();
        $this->router = new Router();
        $this->registerCoreRoutes();
        $this->registerModuleRoutes();
    }

    public function run(): void
    {
        // Global error handler
        set_exception_handler(function (\Throwable $e) {
            Logger::critical($e->getMessage(), [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
            ]);

            $appConfig = require ROOT_PATH . '/config/app.php';
            if ($appConfig['debug']) {
                http_response_code(500);
                echo '<h1>Error</h1><pre>' . htmlspecialchars($e->getMessage()) . '</pre>';
                echo '<pre>' . htmlspecialchars($e->getTraceAsString()) . '</pre>';
            } else {
                http_response_code(500);
                $viewFile = ROOT_PATH . '/views/errors/500.php';
                if (file_exists($viewFile)) {
                    include $viewFile;
                } else {
                    echo '<h1>500 Internal Server Error</h1><p>Something went wrong.</p>';
                }
            }
            exit;
        });

        // Language switching via URL
        if (isset($_GET['lang']) && in_array($_GET['lang'], ['en', 'ar'])) {
            Lang::set($_GET['lang']);
        }

        $this->router->dispatch($this->request);
    }

    private function registerCoreRoutes(): void
    {
        $r = $this->router;

        // Guest routes
        $r->addRoute('GET', '/login', 'AuthController@showLogin', null, null, ['GuestMiddleware']);
        $r->addRoute('POST', '/login', 'AuthController@login', null, null, ['GuestMiddleware']);

        // Auth routes
        $r->addRoute('POST', '/logout', 'AuthController@logout', null, null, ['AuthMiddleware']);
        $r->addRoute('GET', '/dashboard', 'DashboardController@index', null, null, ['AuthMiddleware']);
        $r->addRoute('GET', '/', function () { Response::redirect('/dashboard'); });

        $r->addRoute('GET', '/profile', 'ProfileController@show', null, null, ['AuthMiddleware']);
        $r->addRoute('POST', '/profile', 'ProfileController@update', null, null, ['AuthMiddleware']);
        $r->addRoute('GET', '/change-password', 'ProfileController@showChangePassword', null, null, ['AuthMiddleware']);
        $r->addRoute('POST', '/change-password', 'ProfileController@changePassword', null, null, ['AuthMiddleware']);
        $r->addRoute('GET', '/lang/{code}', 'LangController@switchLang');
    }

    private function registerModuleRoutes(): void
    {
        $moduleRoutes = ModuleRegistry::getRoutes();
        foreach ($moduleRoutes as $route) {
            $this->router->addRoute(
                $route[0],            // method
                $route[1],            // pattern
                $route[2],            // handler
                $route[3] ?? null,    // permission
                $route['_module'],    // module name
                ['AuthMiddleware']    // all module routes require auth
            );
        }
    }
}