<?php

declare(strict_types=1);

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Http\Exception\NotFoundException;
use Cake\Utility\Inflector;
use Cake\Core\Configure;
use Cake\View\Exception\MissingViewException;

class PagesController extends Controller
{
    public function initialize(): void
    {
        parent::initialize();
        $this->viewBuilder()->setLayout('default');
    }

    public function display(...$path): void
    {
        if (empty($path)) {
            return $this->redirect('/');
        }

        $page = $path[0] ?? null;
        $subpage = $path[1] ?? null;
        $titleForLayout = !empty($path) ? Inflector::humanize(end($path)) : null;

        $this->set(compact('page', 'subpage', 'titleForLayout'));

        try {
            $this->render(implode('/', $path));
        } catch (MissingViewException $e) {
            if (Configure::read('debug')) {
                throw $e;
            }
            throw new NotFoundException();
        }
    }
}