<?php
declare(strict_types=1);
namespace Repositories;

final class BlogRepository extends BaseRepository
{
    public function all(array $filters): array
    {
        $limit = max(1, min(30, (int)($filters['limit'] ?? 9)));
        $offset = max(0, ((int)($filters['page'] ?? 1) - 1) * $limit);
        return $this->fetchAll('SELECT id,title,slug,excerpt,featured_image,meta_title,meta_description,published_at FROM blogs WHERE status="published" ORDER BY published_at DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
    }

    public function findBySlug(string $slug): ?array
    {
        return $this->fetchOne('SELECT * FROM blogs WHERE slug=:slug AND status="published" LIMIT 1', ['slug' => $slug]);
    }

    public function related(int $excludeId): array
    {
        return $this->fetchAll('SELECT id,title,slug,excerpt,featured_image,published_at FROM blogs WHERE id<>:id AND status="published" ORDER BY published_at DESC LIMIT 3', ['id' => $excludeId]);
    }
}
