<?php
namespace YTKNS;

use Index\Data\DbTools;
use Syokuhou\FileConfig;

define('YTKNS_STARTUP', microtime(true));
define('YTKNS_CLI', PHP_SAPI === 'cli');
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'));
define('YTKNS_MAINTENANCE', is_file(YTKNS_ROOT . '/.maintenance'));

require_once YTKNS_ROOT . '/vendor/autoload.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);
mb_internal_encoding('UTF-8');
date_default_timezone_set('GMT');

// Display exception report
set_exception_handler(function(\Throwable $ex) {
    if(YTKNS_CLI) {
        echo (string)$ex;
        exit;
    }

    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);

$cfg = FileConfig::fromFile(YTKNS_ROOT . '/ytkns.cfg');

$db = DbTools::create($cfg->getString('database:dsn', 'null:'));
$db->execute('SET SESSION time_zone = \'+00:00\', sql_mode = \'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION\'');

$ctx = new YtknsContext($cfg, $db);

DB::init(
    $cfg->getString('pdo:dsn'),
    $cfg->getString('pdo:user'),
    $cfg->getString('pdo:pass'),
    DB::FLAGS
);