<?php
/// file: app/Core/Model.php

declare(strict_types=1);

namespace App\Core;

use PDO;

abstract class Model
{
    abstract protected static function table(): string;

    protected static function pdo(): PDO
    {
        return Database::pdo();
    }

    /** @return array<string, mixed>|null */
    public static function find(int $id): ?array
    {
        $t = static::table();
        $st = self::pdo()->prepare("SELECT * FROM `{$t}` WHERE id = ? LIMIT 1");
        $st->execute([$id]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    /** @return array<string, mixed>|null */
    public static function findBy(string $column, string $value): ?array
    {
        $t = static::table();
        $st = self::pdo()->prepare("SELECT * FROM `{$t}` WHERE `{$column}` = ? LIMIT 1");
        $st->execute([$value]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    /** @return list<array<string, mixed>> */
    public static function all(string $orderBy = 'id DESC'): array
    {
        $t = static::table();
        $st = self::pdo()->query("SELECT * FROM `{$t}` ORDER BY {$orderBy}");
        return $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}
