<?php

require_once __DIR__ . '/env_loader.php';

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

    if ($pdo === null) {
        $host = $_ENV['DB_HOST'] ?? getenv('DB_HOST') ?? 'localhost';
        $port = $_ENV['DB_PORT'] ?? getenv('DB_PORT') ?? '3306';
        $dbname = $_ENV['DB_NAME'] ?? getenv('DB_NAME') ?? 'bot';
        $user = $_ENV['DB_USER'] ?? getenv('DB_USER') ?? 'root';
        $pass = $_ENV['DB_PASS'] ?? getenv('DB_PASS') ?? '';

        $dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4";

        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];

        $pdo = new PDO($dsn, $user, $pass, $options);
        
        // Configurar zona horaria
        $timezone = $_ENV['TZ'] ?? getenv('TZ') ?? 'America/Mexico_City';
        date_default_timezone_set($timezone);
        
        // Configurar timezone de MySQL
        $pdo->exec("SET time_zone = '" . date('P') . "'");
    }

    return $pdo;
}
