<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('assert.exception', 1);
date_default_timezone_set('Europe/Moscow');

mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

define('APP_ROOT', dirname(__DIR__));
define('START_TIME', microtime(true));

set_include_path(get_include_path().PATH_SEPARATOR.APP_ROOT);

if (!file_exists(APP_ROOT.'/config.yaml'))
    die('Fatal: config.yaml not found');

global $config;
$config = yaml_parse_file(APP_ROOT.'/config.yaml');
if ($config === false)
    die('Fatal: failed to parse config.yaml');

// i know what i'm doing. do you?
umask($config['umask']);

require_once 'functions.php';
require_once 'engine_functions.php';
require_once 'vendor/autoload.php';

global $globalContext;
$globalContext = engine\GlobalContext::getInstance();

try {
    if (isCli()) {
        $_SERVER['HTTP_HOST'] = $config['domain'];
        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
        $globalContext->setIsDevelopmentEnvironment(str_ends_with(dirname(__DIR__), 'www-dev'));
    } else {
        // IE moment
        if (($pos = strpos($_SERVER['HTTP_HOST'], ':')) !== false)
            $_SERVER['HTTP_HOST'] = substr($_SERVER['HTTP_HOST'], 0, $pos);
        $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
        if (array_key_exists('HTTP_X_REAL_IP', $_SERVER))
            $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP'];
        $globalContext->setIsDevelopmentEnvironment(str_ends_with(dirname($_SERVER['DOCUMENT_ROOT']), 'www-dev'));
    }
} catch (RuntimeException $e) {
    die('Fatal error: '.$e->getMessage());
}

$logger = isDev()
    ? new engine\logging\FileLogger(APP_ROOT.'/log/debug.log')
    : new engine\logging\DatabaseLogger();
$logger->enable();
$globalContext->setLogger($logger);
unset($logger);

if (!isDev()) {
    if (file_exists(APP_ROOT.'/config-runtime.php'))
        $config += require_once 'config-runtime.php';
    else
        die('config-runtime.php not found');

    // turn off errors output on production domains
    error_reporting(0);
    ini_set('display_errors', 0);
}
