<?php

class Database
{
    private static $host;
    private static $dbname;
    private static $username;
    private static $password;
    private static $conn;

    private function __construct() {}

    public static function connect()
    {
        if (self::$conn !== null) {
            return self::$conn;
        }

        // Load .env if not already loaded
        self::loadEnv();

        try {
            self::$conn = new PDO(
                "mysql:host=" . self::$host . ";dbname=" . self::$dbname . ";charset=utf8mb4",
                self::$username,
                self::$password,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]
            );

        } catch (PDOException $e) {
            self::handleError($e);
        }

        return self::$conn;
    }

    private static function loadEnv()
    {
        $envPath = dirname(__DIR__) . '/.env';

        if (!file_exists($envPath)) {
            die('Environment file not found.');
        }

        $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        foreach ($lines as $line) {
            if (strpos(trim($line), '#') === 0) {
                continue;
            }

            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);

            $_ENV[$key] = $value;
        }

        self::$host     = $_ENV['DB_HOST'] ?? 'localhost';
        self::$dbname   = $_ENV['DB_NAME'] ?? 'dc2025_excl_transport';
        self::$username = $_ENV['DB_USER'] ?? 'dc2025_admin';
        self::$password = $_ENV['DB_PASS'] ?? 'M1963@noor123';
    }

    private static function handleError($e)
    {
        if (getenv('APP_ENV') === 'production') {
            error_log($e->getMessage());
            die('Database connection error.');
        } else {
            die('Database Error: ' . $e->getMessage());
        }
    }
}
