<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Core\Configure;
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 home(): void
    {
        $benefits = $this->fetchTable('Benefits')->find()
            ->orderByAsc('sort_order')
            ->all();

        $journeySteps = $this->fetchTable('JourneySteps')->find()
            ->orderByAsc('sort_order')
            ->all();

        $programs = $this->fetchTable('Programs')->find()
            ->orderByAsc('sort_order')
            ->all();

        $testimonials = $this->fetchTable('Testimonials')->find()
            ->orderByAsc('sort_order')
            ->all();

        $stats = $this->fetchTable('LandingStats')->find()
            ->orderByAsc('sort_order')
            ->all();

        $teachers = $this->fetchTable('Teachers')->find()
            ->where(['is_active' => true])
            ->orderByAsc('sort_order')
            ->all();

        $this->set(compact('benefits', 'journeySteps', 'programs', 'testimonials', 'stats', 'teachers'));
    }

    public function routeHelp(): void
    {
        $requestedPath = trim((string)$this->request->getQuery('from', '/'));
        if ($requestedPath === '') {
            $requestedPath = '/';
        }

        $primaryUrl = '/';
        $primaryLabel = 'Return home';
        if (str_starts_with($requestedPath, '/admin')) {
            $primaryUrl = '/admin/login';
            $primaryLabel = 'Admin sign in';
        }

        $this->set(compact('requestedPath', 'primaryUrl', 'primaryLabel'));
    }

    public function display(string ...$path): ?Response
    {
        if (!$path) {
            return $this->redirect('/');
        }
        if (in_array('..', $path, true) || in_array('.', $path, true)) {
            throw new ForbiddenException();
        }
        $page = $subpage = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        $this->set(compact('page', 'subpage'));

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