<?php
require_once __DIR__ . '/../app/Core.php';
require_once __DIR__ . '/../app/controllers/AuthController.php';
require_once __DIR__ . '/../app/controllers/DashboardController.php';
require_once __DIR__ . '/../app/controllers/ContactsController.php';
require_once __DIR__ . '/../app/controllers/TemplatesController.php';
require_once __DIR__ . '/../app/controllers/MessagesController.php';
require_once __DIR__ . '/../app/controllers/SettingsController.php';
require_once __DIR__ . '/../app/controllers/SearchController.php';
require_once __DIR__ . '/../app/controllers/WebhookController.php';

start_session();
date_default_timezone_set(config('app.timezone', 'America/Chicago'));

$route = $_GET['route'] ?? 'dashboard/index';
if (!app_config_exists() && $route !== 'auth/login') {
    render_boot_error_page(
        'Application configuration error',
        'The app is not installed yet. Run the installer to create config/config.php and the database schema.',
        'Missing file: config/config.php',
        ['Open installer' => 'install.php']
    );
}

$map = [
    'auth' => AuthController::class,
    'dashboard' => DashboardController::class,
    'contacts' => ContactsController::class,
    'templates' => TemplatesController::class,
    'messages' => MessagesController::class,
    'settings' => SettingsController::class,
    'search' => SearchController::class,
    'webhook' => WebhookController::class,
];

[$controllerName, $action] = array_pad(explode('/', $route), 2, 'index');
if (!isset($map[$controllerName])) {
    http_response_code(404);
    exit('Route not found.');
}

try {
    if ($controllerName !== 'auth' && $controllerName !== 'webhook') {
        $pdo = Database::connection();
        $missingTables = app_missing_tables($pdo);
        if ($missingTables) {
            render_boot_error_page(
                'Application configuration error',
                'The app is connected to the database, but required tables are missing. Run migrations to repair the schema.',
                "Missing tables:
- " . implode("
- ", $missingTables),
                ['Open installer' => 'install.php', 'Run repair' => 'install.php?action=repair']
            );
        }
    }

    require_auth();
    $controller = new $map[$controllerName]();
    if (!method_exists($controller, $action)) {
        http_response_code(404);
        exit('Action not found.');
    }
    $controller->$action();
} catch (PDOException $e) {
    $detail = $e->getMessage();
    $links = ['Open installer' => 'install.php'];
    if (str_contains($detail, 'Base table or view not found')) {
        $links['Run repair'] = 'install.php?action=repair';
        render_boot_error_page('Application configuration error', 'The app is connected to the database, but the schema is incomplete.', $detail, $links);
    }
    render_boot_error_page('Application configuration error', 'The app could not complete startup. Use the installer or update config/config.php.', $detail, $links);
} catch (Throwable $e) {
    render_boot_error_page('Application configuration error', 'The app could not complete startup. Use the installer or update config/config.php.', $e->getMessage(), ['Open installer' => 'install.php']);
}
