<?php

declare(strict_types=1);

namespace App\Core;

use PDO;
use PDOException;

final class Database
{
    private static ?PDO $pdo = null;
    private static bool $attempted = false;

    public static function pdo(): ?PDO
    {
        if (self::$pdo instanceof PDO || self::$attempted) {
            return self::$pdo;
        }

        self::$attempted = true;
        $database = config('database.name');
        $username = config('database.username');

        if (!$database || !$username) {
            return null;
        }

        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=%s',
            config('database.host', '127.0.0.1'),
            (int) config('database.port', 3306),
            $database,
            config('database.charset', 'utf8mb4')
        );

        try {
            self::$pdo = new PDO($dsn, (string) $username, (string) config('database.password', ''), [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
        } catch (PDOException) {
            self::$pdo = null;
        }

        return self::$pdo;
    }
}
