<?php
// src/Database.php
class Database {
    private static $connection = null;
    
    public static function getConnection(array $config) {
        if (self::$connection === null) {
            foreach (['db_host','db_port','db_name','db_user','db_pass'] as $k) {
                if (!array_key_exists($k, $config)) {
                    throw new RuntimeException('Falta clave de config: ' . $k);
                }
            }
            
            $dsn = sprintf(
                'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
                $config['db_host'],
                (int)$config['db_port'],
                $config['db_name']
            );
            
            try {
                self::$connection = new PDO($dsn, $config['db_user'], $config['db_pass'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_PERSISTENT => true, // Conexión persistente
                    PDO::ATTR_EMULATE_PREPARES => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone = '+00:00'"
                ]);
            } catch (PDOException $e) {
                error_log('Error de conexión a MySQL: ' . $e->getMessage());
                http_response_code(500);
                echo 'Error de conexión a la base de datos';
                exit;
            }
        }
        
        return self::$connection;
    }
    
    public static function closeConnection() {
        self::$connection = null;
    }
}