<?php
class Model
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = Database::connection();
    }

    protected function fetchAll(string $sql, array $params = []): array
    {
        $statement = $this->db->prepare($sql);
        $statement->execute($params);
        return $statement->fetchAll();
    }

    protected function fetch(string $sql, array $params = []): ?array
    {
        $statement = $this->db->prepare($sql);
        $statement->execute($params);
        return $statement->fetch() ?: null;
    }

    protected function execute(string $sql, array $params = []): bool
    {
        $statement = $this->db->prepare($sql);
        return $statement->execute($params);
    }

    protected function lastInsertId(): string
    {
        return $this->db->lastInsertId();
    }

    protected function addColumnIfNotExists(string $table, string $column, string $definition): void
    {
        $exists = $this->fetch(
            "SELECT COUNT(*) AS cnt FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :table AND column_name = :column",
            ['table' => $table, 'column' => $column]
        );
        if ((int)($exists['cnt'] ?? 0) === 0) {
            $this->execute('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $definition);
        }
    }
}
