<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Blog Controller
 *
 * Handles the blog listing page with pagination and
 * individual blog post display by slug.
 */
class BlogController extends Controller
{
    /**
     * Display published blog posts with pagination.
     *
     * @return void
     */
    public function index(): void
    {
        $blogModel = $this->model('BlogPost');

        $page = max(1, (int) ($_GET['page'] ?? 1));
        $perPage = 9;

        $posts = $blogModel->getPublished($page, $perPage);
        $totalPosts = $blogModel->getPublishedCount();
        $totalPages = (int) ceil($totalPosts / $perPage);

        $this->view('blog/index', [
            'title'      => 'Blog - Gmind Institute',
            'posts'      => $posts,
            'currentPage' => $page,
            'totalPages'  => $totalPages,
            'currentNav'  => 'blog',
        ]);
    }

    /**
     * Display a single blog post by its slug.
     *
     * @param string $slug The URL-friendly slug of the blog post
     * @return void
     */
    public function show(string $slug): void
    {
        $blogModel = $this->model('BlogPost');

        $post = $blogModel->getBySlug($slug);

        if ($post === null) {
            http_response_code(404);
            $this->view('blog/index', [
                'title'      => 'Post Not Found - Gmind Institute',
                'posts'      => [],
                'currentPage' => 1,
                'totalPages'  => 1,
                'currentNav'  => 'blog',
            ]);
            return;
        }

        // Get recent posts for sidebar
        $recentPosts = $blogModel->getRecent(5);

        $this->view('blog/show', [
            'title'       => $post['title'] . ' - Gmind Institute',
            'post'        => $post,
            'recentPosts' => $recentPosts,
            'currentNav'  => 'blog',
        ]);
    }
}
