<?php

declare(strict_types=1);

namespace Core;

use PDO;

class Database
{
    protected PDO $pdo;

    public function __construct(array $config)
    {
        $this->pdo = new PDO(
            $config['dsn'],
            $config['username'] ?? null,
            $config['password'] ?? null,
            $config['options'] ?? []
        );
    }

    public function pdo(): PDO
    {
        return $this->pdo;
    }

    public function query(string $sql, array $parameters = []): array
    {
        $statement = $this->pdo->prepare($sql);
        $statement->execute($parameters);

        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    public function first(string $sql, array $parameters = []): ?array
    {
        $rows = $this->query($sql, $parameters);

        return $rows[0] ?? null;
    }

    public function execute(string $sql, array $parameters = []): bool
    {
        $statement = $this->pdo->prepare($sql);

        return $statement->execute($parameters);
    }
}
