<?php
declare(strict_types=1);

/**
 * Front controller. Every page enters here as index.php?m=<module>&a=<action>.
 * Query-string routing keeps this working on IIS with no rewrite module.
 */

require_once __DIR__ . '/includes/bootstrap.php';

/** Whitelist of module => allowed actions => file. Nothing outside this map is reachable. */
$routes = [
    'auth' => [
        'login'    => 'auth/login.php',
        'logout'   => 'auth/logout.php',
        'account'  => 'auth/account.php',
        'password' => 'auth/password.php',
    ],
    'dashboard' => [
        'index' => 'dashboard/index.php',
    ],
    'companies' => [
        'index'  => 'companies/list.php',
        'list'   => 'companies/list.php',
        'view'   => 'companies/view.php',
        'form'   => 'companies/form.php',
        'save'   => 'companies/save.php',
        'delete' => 'companies/delete.php',
        'export' => 'companies/export.php',
    ],
    'visits' => [
        'index' => 'visits/queue.php',
        'queue' => 'visits/queue.php',
        'save'  => 'visits/save.php',
        'quick' => 'visits/quick.php',
        'pause' => 'visits/pause.php',
    ],
    'products' => [
        'save'   => 'products/save.php',
        'delete' => 'products/delete.php',
    ],
    'links' => [
        'save'   => 'links/save.php',
        'delete' => 'links/delete.php',
    ],
    'notes' => [
        'save'   => 'notes/save.php',
        'delete' => 'notes/delete.php',
    ],
    'tags' => [
        'index'  => 'tags/index.php',
        'save'   => 'tags/save.php',
        'delete' => 'tags/delete.php',
    ],
    'users' => [
        'index'    => 'users/index.php',
        'save'     => 'users/save.php',
        'password' => 'users/password.php',
    ],
    'signals' => [
        'index'  => 'signals/index.php',
        'review' => 'signals/review.php',
        'run'    => 'signals/run.php',
    ],
    'reports' => [
        'index'    => 'reports/coverage.php',
        'coverage' => 'reports/coverage.php',
    ],
];

$module = (string) get_param('m', 'dashboard');
$action = (string) get_param('a', 'index');

if (!isset($routes[$module][$action])) {
    http_response_code(404);
    $module = 'dashboard';
    $action = 'index';
    if (!Auth::check()) {
        redirect('auth', 'login');
    }
    Flash::add('warn', 'That page does not exist.');
}

$file = BASE_DIR . '/modules/' . $routes[$module][$action];

if (!is_file($file)) {
    http_response_code(500);
    exit('Module file is missing: ' . e($routes[$module][$action]));
}

// Everything except the login screen requires a session.
if ($module !== 'auth' || !in_array($action, ['login', 'logout'], true)) {
    Auth::requireLogin();
}

/** Available to the layout for highlighting the active nav item. */
$CURRENT_MODULE = $module;
$CURRENT_ACTION = $action;

require $file;
