<?php
/// file: app/Controllers/JournalController.php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\Seo;
use App\Models\JournalPost;

final class JournalController extends Controller
{
    public function index(Request $request): Response
    {
        $posts = JournalPost::published();
        $featured = $posts[0] ?? null;
        $list = $featured ? array_slice($posts, 1) : $posts;
        $html = $this->view('journal/index', [
            'meta' => Seo::page('journal'),
            'page' => 'journal',
            'featured' => $featured,
            'posts' => $list,
        ], 'layouts/base');
        return Response::html($html);
    }

    public function show(Request $request): Response
    {
        $slug = $request->param('slug') ?? '';
        $post = JournalPost::findBySlug($slug);
        if ($post === null) {
            return $this->app->make(\App\Controllers\ErrorController::class)->notFound($request);
        }
        $related = JournalPost::related((string) ($post['category'] ?? ''), (int) $post['id']);
        $title = (string) $post['title'] . ' — ' . $this->app->config('app.name');
        $html = $this->view('journal/show', [
            'meta' => Seo::page('journal', [
                'title' => $title,
                'description' => (string) ($post['excerpt'] ?? ''),
                'og_title' => (string) $post['title'],
                'og_description' => (string) ($post['excerpt'] ?? ''),
                'og_image' => (string) ($post['cover_path'] ?? ''),
            ]),
            'page' => 'journal',
            'post' => $post,
            'related' => $related,
        ], 'layouts/base');
        return Response::html($html);
    }
}
