<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/config/config.php';

date_default_timezone_set(APP_TIMEZONE);
mb_internal_encoding('UTF-8');

ini_set('display_errors', APP_DEBUG ? '1' : '0');
ini_set('log_errors', '1');
ini_set('error_log', LOG_DIR . '/php-error.log');
error_reporting(E_ALL);

require_once __DIR__ . '/helpers.php';

spl_autoload_register(static function (string $class): void {
    $file = __DIR__ . DIRECTORY_SEPARATOR . $class . '.php';
    if (is_file($file)) {
        require_once $file;
    }
});

/** Optional source-IP restriction, for an internal-only deployment. */
function enforce_ip_allowlist(): void
{
    if (IP_ALLOWLIST === []) {
        return;
    }
    foreach (IP_ALLOWLIST as $cidr) {
        if (ip_in_cidr(client_ip(), $cidr)) {
            return;
        }
    }
    error_log('[access] blocked source IP ' . client_ip());
    http_response_code(403);
    exit('Access from this network is not permitted.');
}

function ip_in_cidr(string $ip, string $cidr): bool
{
    if (!str_contains($cidr, '/')) {
        return $ip === $cidr;
    }
    [$subnet, $bits] = explode('/', $cidr, 2);
    $ipBin = @inet_pton($ip);
    $snBin = @inet_pton($subnet);
    if ($ipBin === false || $snBin === false || strlen($ipBin) !== strlen($snBin)) {
        return false;
    }
    $bits  = (int) $bits;
    $bytes = intdiv($bits, 8);
    $rem   = $bits % 8;
    if ($bytes > 0 && strncmp($ipBin, $snBin, $bytes) !== 0) {
        return false;
    }
    if ($rem === 0) {
        return true;
    }
    $mask = chr(0xFF << (8 - $rem) & 0xFF);
    return ($ipBin[$bytes] & $mask) === ($snBin[$bytes] & $mask);
}

set_exception_handler(static function (Throwable $ex): void {
    error_log('[uncaught] ' . $ex->getMessage() . ' @ ' . $ex->getFile() . ':' . $ex->getLine());
    http_response_code(500);
    if (APP_DEBUG) {
        echo '<pre style="padding:2rem;font:13px ui-monospace,monospace">';
        echo e($ex->getMessage()) . "\n\n" . e($ex->getTraceAsString());
        echo '</pre>';
    } else {
        echo '<p style="padding:2rem;font:15px system-ui">Something went wrong. '
           . 'The details are in the error log.</p>';
    }
    exit;
});

enforce_ip_allowlist();
Auth::startSession();
Lang::boot();

header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Referrer-Policy: same-origin');
