<?php
declare(strict_types=1);

namespace Celena\Module\Categories;

use Celena\Core\Database\Connection;
use Celena\Core\Http\Pagination;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Filter;
use Celena\Core\Template\Engine;
use Celena\Module\Settings\Options;

/**
 * Публичный просмотр категории: /category/{slug}
 * Показывает новости этой категории с пагинацией.
 */
final class PublicCategoriesController
{
    public function __construct(
        private readonly Engine $engine,
        private readonly Connection $conn,
        private readonly Options $options,
    ) {
    }

    public function show(Request $request, array $params): Response
    {
        $slug = Filter::urlSlug($params['slug'] ?? '');
        $cat = $this->conn->builder('celena_categories')->where('slug', '=', $slug)->first();
        if ($cat === null) {
            return Response::notFound();
        }
        $page = Filter::int($request->query('page', 1), 1);
        $perPage = Filter::int($this->options->get('posts_per_page', 10), 10);
        $q = $this->conn->builder('celena_news')
            ->where('status', '=', 'published')
            ->where('category_id', '=', (int) $cat['id']);
        $total = (clone $q)->count();
        $p = new Pagination($page, $perPage, $total);
        $rows = $q->orderBy('published_at', 'desc')->limit($p->perPage)->offset($p->offset)->get();
        foreach ($rows as &$r) {
            $r['url'] = '/news/' . $r['slug'];
            $r['date'] = (string) ($r['published_at'] ?? '');
        }
        unset($r);

        $this->engine->setTheme((string) $this->options->get('theme', 'default'));
        $html = $this->engine->render('news_list', [
            'site' => ['name' => (string) $this->options->get('site_name', '')],
            'page' => [
                'title' => (string) $cat['title'],
                'seo_title' => (string) ($cat['seo_title'] ?? $cat['title']),
                'seo_description' => (string) ($cat['seo_description'] ?? $cat['description'] ?? ''),
                'og_image' => '',
            ],
            'news' => $rows,
            'pagination' => $p->toArray('/category/' . $slug . '?page=:page'),
            'category' => $cat,
        ]);
        return Response::html($html);
    }
}
