<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * News Controller
 *
 * Handles the branch news listing page with pagination and
 * individual news article display by slug.
 */
class NewsController extends Controller
{
    /**
     * Display active branch news with pagination.
     *
     * @return void
     */
    public function index(): void
    {
        $branchNewsModel = $this->model('BranchNews');

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

        // Get all active branch news with pagination
        $offset = ($page - 1) * $perPage;

        $sql = 'SELECT bn.*, b.name AS branch_name
                FROM `branch_news` bn
                LEFT JOIN `branches` b ON bn.branch_id = b.id
                WHERE bn.active = :active
                ORDER BY bn.created_at DESC
                LIMIT :limit OFFSET :offset';

        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':active', 1, \PDO::PARAM_INT);
        $stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();

        $news = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        // Get total count for pagination
        $countSql = 'SELECT COUNT(*) AS total FROM `branch_news` WHERE `active` = :active';
        $countStmt = $this->db->prepare($countSql);
        $countStmt->execute([':active' => 1]);
        $totalResult = $countStmt->fetch(\PDO::FETCH_ASSOC);
        $totalNews = (int) ($totalResult['total'] ?? 0);
        $totalPages = (int) ceil($totalNews / $perPage);

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

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

        $article = $branchNewsModel->getBySlug($slug);

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

        // Get latest news for sidebar
        $latestNews = $branchNewsModel->getLatest(5);

        $this->view('news/show', [
            'title'      => $article['title'] . ' - Gmind Institute',
            'article'    => $article,
            'latestNews' => $latestNews,
            'currentNav' => 'news',
        ]);
    }
}
