<?php
define('FMF_STARTUP', microtime(true));
define('FMF_ROOT', __DIR__);
define('FMF_DEBUG', is_file(FMF_ROOT . '/.debug'));
define('FMF_PHP_MIN_VER', '7.3.0');
define('FMF_LAYOUT', FMF_ROOT . '/layout');
define('FMF_INCLUDE', FMF_ROOT . '/include');

if(version_compare(PHP_VERSION, FMF_PHP_MIN_VER, '<')) {
    die('At least PHP <b>' . FMF_PHP_MIN_VER . '</b> is required.');
}

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

date_default_timezone_set('UTC');
mb_internal_encoding('UTF-8');
set_include_path(get_include_path() . PATH_SEPARATOR . FMF_INCLUDE);

if(!is_file(FMF_ROOT . '/config.php'))
    die('Configuration is missing.');

require_once FMF_ROOT . '/vendor/autoload.php';
require_once FMF_ROOT . '/config.php';

try {
    $pdo = new PDO(CHIE_DB_DSN, CHIE_DB_USER, CHIE_DB_PASS, [
        PDO::ATTR_CASE => PDO::CASE_NATURAL,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
        PDO::ATTR_STRINGIFY_FETCHES => false,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::MYSQL_ATTR_INIT_COMMAND => "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';",
    ]);

    $mailer = new Swift_Mailer(
        (new Swift_SmtpTransport(CHIE_SMTP_HOST, CHIE_SMTP_PORT))
            ->setEncryption(CHIE_SMTP_ENC)
            ->setUsername(CHIE_SMTP_USER)
            ->setPassword(CHIE_SMTP_PASS)
    );
} catch(Exception $ex) {
    die($ex->getMessage());
}

include_once '_csrf.php';
include_once '_user.php';

function die_ex(string $message, int $status = 400): void {
    http_response_code($status);
    include FMF_LAYOUT . '/notice.php';
    exit;
}

CSRF::setGlobalSecretKey(CHIE_CSRF_SECRET);
purge_old_sessions();
session_activate($_COOKIE['fmfauth'] ?? '');

$userInfo = user_info(current_user_id());
if(!empty($userInfo)) {
    define('FMF_DATE_FORMAT', $userInfo['user_date_format']);
    date_default_timezone_set($userInfo['user_time_zone']);
    CSRF::setGlobalIdentity($_COOKIE['fmfauth'] ?? '');

    if(!empty($userInfo['user_banned'])) {
        $banTimestamp = $userInfo['user_banned'];
        $banReason = $userInfo['user_banned_reason'];
        include FMF_LAYOUT . '/banned.php';
        destroy_session($_COOKIE['fmfauth'] ?? '');
        exit;
    }
} else {
    define('FMF_DATE_FORMAT', 'D Y-m-d H:i:s T');
    CSRF::setGlobalIdentity($_SERVER['REMOTE_ADDR']);
}
unset($userInfo);