<?php

use Core\System\Env;

function db(): PDO
{
    static $pdo = null;

    if ($pdo instanceof PDO) {
        return $pdo;
    }

    Env::bootstrap(defined('ROOT_PATH') ? ROOT_PATH : null);

    $host     = Env::get('DB_HOST', 'localhost') ?? 'localhost';
    $port     = Env::get('DB_PORT', '3306') ?? '3306';
    $dbname   = trim((string) Env::get('DB_NAME', ''));
    $username = trim((string) Env::get('DB_USER', ''));
    $password = (string) Env::get('DB_PASS', '');

    if ($dbname === '' || $username === '') {
        throw new RuntimeException('Database configuration is incomplete.');
    }

    try {
        date_default_timezone_set('UTC');

        $pdo = new PDO(
            "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4",
            $username,
            $password,
            [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]
        );

        try {
            $pdo->exec("SET time_zone = '+00:00'");
        } catch (Throwable $e) {
            // Ignore if the DB account cannot change the session timezone.
        }
    } catch (PDOException $e) {
        error_log('Database connection failed: ' . $e->getMessage());
        throw new RuntimeException('Database connection failed.');
    }

    return $pdo;
}
