<?php
/**
 * Front controller.
 */

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';

sq_handle_consult();

$path = sq_current_path();
$routes = require dirname(__DIR__) . '/app/routes.php';

if (isset($routes[$path])) {
    sq_render($routes[$path], array('path' => $path));
    exit;
}

if (preg_match('#^/articles/([^/]+)$#', $path, $matches)) {
    $slug = $matches[1];
    $articles = sq_load_json('articles.json');
    $article = null;
    foreach ($articles as $item) {
        if (($item['slug'] ?? '') === $slug) {
            $article = $item;
            break;
        }
    }
    if ($article) {
        sq_render('pages/article-single', array(
            'path'    => $path,
            'article' => $article,
        ));
        exit;
    }
}

$page_slug = trim($path, '/');
if ($page_slug !== '') {
    $page = sq_find_page($page_slug);
    if ($page) {
        sq_render('pages/page-generic', array(
            'path' => $path,
            'page' => $page,
        ));
        exit;
    }
}

http_response_code(404);
sq_render('pages/404', array('path' => $path));
