<?php
/**
 * TOPBD — Database Connection Handler using PDO
 */

if (!defined('DB_HOST')) {
    if (file_exists(__DIR__ . '/../config.php')) {
        require_once __DIR__ . '/../config.php';
    } else {
        header('Location: installer.php');
        exit;
    }
}

class Database {
    private static ?PDO $instance = null;

    public static function getConnection(): PDO {
        if (self::$instance === null) {
            try {
                $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
                $options = [
                    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"
                ];
                self::$instance = new PDO($dsn, DB_USER, DB_PASS, $options);
            } catch (PDOException $e) {
                if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
                    die("Database connection error: " . $e->getMessage());
                } else {
                    die("A database connection error occurred. Please verify your config.php settings or run installer.php.");
                }
            }
        }
        return self::$instance;
    }
}

function get_db(): PDO {
    return Database::getConnection();
}
