<?php

// minimum PHP version required to continue
$php_version = '8.1';
if (version_compare(PHP_VERSION, $php_version, '<')) {
    http_response_code(500);
    echo 'This app requires a minimum of PHP ' . $php_version;
    die();
}
unset($php_version);

// PSR-4 like autoloader
spl_autoload_register(
    function ($class_name) {
        $path = __DIR__ . '/../app/' . str_replace('\\', '/', $class_name) . '.php';
        require $path;
    }
);

/**
 * Helper for evaluating/including views
 */
function view(string $_view, array $_data = [])
{
    $_path = __DIR__ . '/../views/' . $_view . '.php';
    extract($_data);
    require $_path;
}

/**
 * Helper for converting and outputting JSON
 */
function json_response(mixed $data, int $status_code = 200)
{
    http_response_code($status_code);
    header('Content-type: application/json');
    echo json_encode($data);
}

/**
 * Helper for generating URLs
 */
function url(string $url, bool $full = false): string
{
    $dir = dirname($_SERVER['SCRIPT_NAME']);
    if ($dir === '/') {
        $dir = '';
    }
    if (!$full) {
        return $dir . $url;
    }
    return isset($_SERVER['HTTPS']) ? 'https' : 'http' . '://' . $_SERVER['HTTP_HOST'] . $dir . $url;
}

// now lets get routing!
require __DIR__ . '/../routes/start.php';