<?php
declare(strict_types=1);

namespace App\Core;

use PDO;
use PDOException;

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

    public function connection(): ?PDO
    {
        if ($this->attempted) {
            return $this->connection;
        }

        $this->attempted = true;
        $config = (array) config('database', []);

        try {
            $dsn = sprintf(
                'mysql:host=%s;port=%d;dbname=%s;charset=%s',
                $config['host'] ?? '127.0.0.1',
                (int) ($config['port'] ?? 3306),
                $config['database'] ?? 'riasec',
                $config['charset'] ?? 'utf8mb4'
            );

            $this->connection = new PDO(
                $dsn,
                (string) ($config['username'] ?? 'root'),
                (string) ($config['password'] ?? ''),
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]
            );
        } catch (PDOException) {
            $this->connection = null;
        }

        return $this->connection;
    }
}