<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Core\Configure;
use Cake\Event\EventInterface;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\View\Exception\MissingTemplateException;

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

    public function beforeFilter(EventInterface $event): void
    {
        parent::beforeFilter($event);

        $action = $this->request->getParam('action');
        $page   = $this->request->getParam('pass.0');

        if ($action === 'display' && $page === 'index') {
            $result = $this->Authentication->getResult();
            if (!$result || !$result->isValid()) {
                $this->Flash->error('Please login to continue.');
                $this->redirect([
                    'controller' => 'Login',
                    'action'     => 'index',
                    '?'          => ['redirect' => $this->request->getRequestTarget()],
                ]);
                return;
            }
        }
    }

    /**
     * Restore Cake's default display() for rendering templates/Pages/* static pages
     */
    public function display(string ...$path): ?Response
    {
        $count = count($path);
        if ($count === 0) {
            return $this->redirect('/');
        }

        if (in_array('..', $path, true) || in_array('.', $path, true)) {
            throw new ForbiddenException('Directory traversal not allowed.');
        }

        $page    = $path[0] ?? null;
        $subpage = $path[1] ?? null;
        $this->set(compact('page', 'subpage'));

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