<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Database;
use PDO;

abstract class BaseModel
{
    protected string $table;
    protected string $primaryKey = 'id';
    private ?PDO $connection = null;

    public function __construct(?PDO $connection = null)
    {
        $this->connection = $connection;
    }

    public function find(int $id): ?array
    {
        $statement = $this->db()->prepare("SELECT * FROM {$this->table} WHERE {$this->primaryKey} = :id LIMIT 1");
        $statement->execute(['id' => $id]);
        $row = $statement->fetch();

        return $row ?: null;
    }

    public function all(int $limit = 50, int $offset = 0): array
    {
        $statement = $this->db()->prepare("SELECT * FROM {$this->table} ORDER BY {$this->primaryKey} DESC LIMIT :limit OFFSET :offset");
        $statement->bindValue('limit', $limit, PDO::PARAM_INT);
        $statement->bindValue('offset', $offset, PDO::PARAM_INT);
        $statement->execute();

        return $statement->fetchAll();
    }

    protected function db(): PDO
    {
        if (!$this->connection instanceof PDO) {
            $this->connection = Database::connection();
        }

        return $this->connection;
    }
}
