<?php

namespace App\Core;

use PDO;
use PDOException;
use Dotenv\Dotenv;

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

    private function __construct() {}

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

        self::loadEnv();

        try {

            self::$connection = new PDO(
                sprintf(
                    "mysql:host=%s;dbname=%s;charset=utf8mb4",
                    $_ENV['DB_HOST'],
                    $_ENV['DB_NAME']
                ),
                $_ENV['DB_USER'],
                $_ENV['DB_PASS'],
                [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                ]
            );

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

        return self::$connection;
    }

    private static function loadEnv(): void
    {
        if (!isset($_ENV['DB_HOST'])) {

            $rootPath = dirname(__DIR__, 2);

            if (file_exists($rootPath . '/.env')) {

                $dotenv = Dotenv::createImmutable($rootPath);
                $dotenv->load();
            }
        }
    }

    private static function handleException(PDOException $e): void
    {
        if (($_ENV['APP_ENV'] ?? 'production') === 'production') {
            error_log($e->getMessage());
            die('Database connection error.');
        }

        die('Database Error: ' . $e->getMessage());
    }
}
