<?php
declare(strict_types=1);

const APP_ROOT = __DIR__ . '/..';
const APP_VERSION = '1.0.0';

if (!is_file(APP_ROOT . '/config.php')) {
    $script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '');
    if (!str_contains($script, '/install/')) {
        $base = preg_replace('~/[^/]*$~', '', $script);
        header('Location: ' . rtrim((string)$base, '/') . '/install/');
        exit;
    }
    return;
}

$config = require APP_ROOT . '/config.php';
date_default_timezone_set($config['timezone'] ?? 'Asia/Kolkata');

if (session_status() !== PHP_SESSION_ACTIVE && PHP_SAPI !== 'cli') {
    $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
    session_name('gamesji_session');
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'secure' => $secure,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
}

require_once APP_ROOT . '/app/functions.php';
require_once APP_ROOT . '/app/GooglePlayImporter.php';

final class DB
{
    private static ?PDO $pdo = null;

    public static function connection(): PDO
    {
        global $config;
        if (self::$pdo instanceof PDO) {
            return self::$pdo;
        }
        $db = $config['db'];
        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=%s',
            $db['host'],
            (int)($db['port'] ?? 3306),
            $db['name'],
            $db['charset'] ?? 'utf8mb4'
        );
        self::$pdo = new PDO($dsn, $db['user'], $db['pass'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
        ]);
        return self::$pdo;
    }
}

set_exception_handler(static function (Throwable $e): void {
    $id = bin2hex(random_bytes(5));
    log_message('ERROR', $id . ' ' . $e->getMessage() . "\n" . $e->getTraceAsString());
    if (!headers_sent()) {
        http_response_code(500);
        header('Content-Type: text/html; charset=UTF-8');
    }
    if (is_admin()) {
        echo '<h1>Application error</h1><p>Reference: ' . e($id) . '</p>';
    } else {
        echo '<!doctype html><meta charset="utf-8"><title>Temporarily unavailable</title><h1>Temporarily unavailable</h1><p>Please try again shortly.</p>';
    }
});
