<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Models\AgendaModel;
use App\Models\BeritaModel;
use App\Models\FooterModel;
use App\Models\IdentitasModel;
use App\Models\MenuModel;
use App\Models\WidgetModel;

class BeritaController extends Controller
{
    private const PER_PAGE = 9;

    public function index(): void
    {
        $beritaModel = new BeritaModel();

        $page = max(1, (int) ($_GET['page'] ?? 1));
        $totalBerita = $beritaModel->countTerbit();
        $totalPage = (int) ceil($totalBerita / self::PER_PAGE);

        $this->view('berita/index', array_merge($this->layoutData(), [
            'daftarBerita' => $beritaModel->getPaginated($page, self::PER_PAGE),
            'page'         => $page,
            'totalPage'    => max(1, $totalPage),
        ]));
    }

    public function show(string $slug): void
    {
        $beritaModel = new BeritaModel();
        $berita = $beritaModel->getBySlug($slug);

        if (!$berita) {
            http_response_code(404);
            $this->view('errors/404');
            return;
        }

        $beritaModel->tambahDilihat((int) $berita['id']);

        $this->view('berita/show', array_merge($this->layoutData(), [
            'berita'       => $berita,
            'beritaLain'   => $beritaModel->getTerbaru(4),
        ]));
    }

    /**
     * Data yang selalu dibutuhkan layout publik (navbar, footer, sidebar).
     */
    private function layoutData(): array
    {
        return [
            'identitas'     => (new IdentitasModel())->getIdentitas(),
            'menus'         => (new MenuModel())->getMenuUtama(),
            'footerKolom'   => (new FooterModel())->getKolom(),
            'widgetSidebar' => (new WidgetModel())->getByPosisi('sidebar'),
        ];
    }
}
