<?php
namespace YTKNS;

define('YTKNS_STARTUP', microtime(true));
define('YTKNS_ROOT', __DIR__);
define('YTKNS_SRC', YTKNS_ROOT . '/src');
define('YTKNS_TPL', YTKNS_ROOT . '/templates');
define('YTKNS_UPLOADS', YTKNS_ROOT . '/uploads');
define('YTKNS_PUB', YTKNS_ROOT . '/public');
define('YTKNS_SCREENSHOTS', YTKNS_PUB . '/ss');
define('YTKNS_DEBUG', is_file(YTKNS_ROOT . '/.debug'));

require_once __DIR__ . '/config.php';

define('ALLOWED_UPLOADS', [
    'audio/mpeg', 'application/x-font-gdos', 'audio/ogg', 'application/ogg',
    'image/jpeg', 'image/png', 'image/gif',
]);
define('SITE_EFFECTS', [
    \YTKNS\Effects\BackgroundAudioEffect::class,
    \YTKNS\Effects\BackgroundImageEffect::class,
    \YTKNS\Effects\ForegroundImageEffect::class,
    \YTKNS\Effects\ZoomTextEffect::class,
    \YTKNS\Effects\NewlyCreatedPageEffect::class,
]);
define('EFFECT_UPLOADS', [
    'BackgroundAudio' => ['ogg', 'mp3'],
    'BackgroundImage' => ['img'],
    'ForegroundImage' => ['img'],
]);

error_reporting(YTKNS_DEBUG ? -1 : 0);
ini_set('display_errors', YTKNS_DEBUG ? 'On' : 'Off');

mb_internal_encoding('utf-8');
date_default_timezone_set('utc');

// Display exception report
set_exception_handler(function(\Throwable $ex) {
    http_response_code(500);

    $out = file_get_contents(YTKNS_TPL . (YTKNS_DEBUG ? '/debug/index.html' : '/errors/500.html'));
    echo strtr($out, [
        ':raw_ex' => (string)$ex,
        ':type' => get_class($ex),
        ':msg' => $ex->getMessage(),
    ]);

    exit;
});

// Turn uncaught errors into uncaught exceptions.
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline) {
    throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
    return true;
}, -1);

// Register class autoloader
spl_autoload_register(function(string $className) {
    if(substr($className, 0, 6) !== 'YTKNS\\')
        return;

    $classPath = YTKNS_SRC . str_replace('\\', '/', substr($className, 5)) . '.php';

    if(is_file($classPath))
        require_once $classPath;
});

DB::init(PDO_DSN, PDO_USER, PDO_PASS, DB::FLAGS);

Config::init();
Config::setDefault('user.invite_only', true);
Config::setDefault('domain.main', 'ytkns.com');
Config::setDefault('domain.zone', '%s.ytkns.com');