<?php
// src/Database/DatabaseManager.php
namespace App\Database;

use PDO;
use PDOException;

class DatabaseManager
{
    private static ?PDO $pdo = null;

    public static function connect(): PDO
    {
        if (self::$pdo === null) {
            $host = $_ENV['DB_HOST'] ?? 'localhost';
            $port = $_ENV['DB_PORT'] ?? '5432';
            $dbname = $_ENV['DB_NAME'] ?? 'moh_db';
            $username = $_ENV['DB_USER'] ?? 'moh_user';
            $password = $_ENV['DB_PASSWORD'] ?? 'moh_password';

            $dsn = "pgsql:host={$host};port={$port};dbname={$dbname}";

            try {
                self::$pdo = new PDO($dsn, $username, $password, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]);
            } catch (PDOException $e) {
                throw new PDOException($e->getMessage(), (int)$e->getCode());
            }
        }

        return self::$pdo;
    }
}