<?php
// ============================================================
// core/Database/Database.php — Lazy PDO Singleton (Refactored)
// يدعم قواعد بيانات متعددة لكل منها Host/User/Pass مختلف
// ============================================================

class Database
{
    private static array $instances = [];

    // خريطة الربط مع متغيرات البيئة (ENV)
    private static array $map = [
        'main' => [
            'name' => 'DB_PRIMARY_NAME_V2',
            'host' => 'DB_PRIMARY_HOST_V2',
            'user' => 'DB_PRIMARY_USER_V2',
            'pass' => 'DB_PRIMARY_PASS_V2',
        ],
        'tracking' => [
            'name' => 'DB_TRACKING_NAME',
            'host' => 'DB_TRACKING_HOST',
            'user' => 'DB_TRACKING_USER',
            'pass' => 'DB_TRACKING_PASS',
        ],
        'ride' => [
            'name' => 'DB_RIDE_NAME',
            'host' => 'DB_RIDE_HOST',
            'user' => 'DB_RIDE_USER',
            'pass' => 'DB_RIDE_PASS',
        ],
    ];

    public static function get(string $name = 'main'): PDO
    {
        if (!isset(self::$instances[$name])) {
            self::$instances[$name] = self::connect($name);
        }
        return self::$instances[$name];
    }

    private static function connect(string $name): PDO
    {
        if (!isset(self::$map[$name])) {
            throw new InvalidArgumentException("Unknown database: $name");
        }

        $cfg = self::$map[$name];
        
        $dbname = getenv($cfg['name']);
        $host   = getenv($cfg['host']) ?: 'localhost';
        $user   = getenv($cfg['user']);
        $pass   = getenv($cfg['pass']);

        if (!$dbname || !$user) {
            error_log("[FATAL] Database config missing for: $name (Check ENV keys: {$cfg['name']}, {$cfg['user']})");
            throw new RuntimeException("Database configuration error.");
        }

        $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
        $options = [
            PDO::ATTR_EMULATE_PREPARES   => false,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_PERSISTENT         => true,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
            PDO::ATTR_TIMEOUT            => 10,
        ];

        try {
            return new PDO($dsn, $user, $pass, $options);
        } catch (PDOException $e) {
            error_log("[DB] Connection failed ($name) at $host: " . $e->getMessage());
            throw $e;
        }
    }

    private function __construct() {}
    private function __clone() {}
}
