<?php

class Database
{
    private static $connection;

    public static function getConnection()
    {
        if (!self::$connection) {
            // Carrega de variáveis de ambiente
            $host = getenv('DB_HOST') ?: 'localhost';
            $user = getenv('DB_USER');
            $pass = getenv('DB_PASS');
            $name = getenv('DB_NAME');

            if (!$user || !$pass || !$name) {
                http_response_code(500);
                exit('Database configuration missing');
            }

            self::$connection = new mysqli($host, $user, $pass, $name);

            if (self::$connection->connect_error) {
                error_log('DB Connection Error: ' . self::$connection->connect_error);
                http_response_code(500);
                exit('Database connection error');
            }

            self::$connection->set_charset('utf8mb4');
        }

        return self::$connection;
    }

    public static function closeConnection()
    {
        if (self::$connection) {
            self::$connection->close();
            self::$connection = null;
        }
    }
}