<?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
{
    /**
     * Custom Home action
     * GET /home → renders templates/Pages/home.php
     */
    public function home(): ?Response
    {
        $Products = $this->fetchTable('Products');

        // Base query: only seasonal (show even if not available), include allergens
        $query = $Products->find()
            ->select(['id', 'name', 'price', 'description', 'product_image_url', 'is_available'])
            ->where(['is_seasonal' => 1])
            ->contain(['Allergens']) // ✅ include allergens
            ->limit(3);

        // If you have a created/modified column, order by newest first
        $schema = $Products->getSchema();
        if ($schema->getColumn('created')) {
            $query->order(['created' => 'DESC']);
        } elseif ($schema->getColumn('id')) {
            $query->order(['id' => 'DESC']);
        }

        $seasonal = $query->all();

        $this->set(compact('seasonal'));
        return $this->render('home');
    }

    /**
     * Generic static page renderer
     * /pages/<view> (e.g. /pages/about → templates/Pages/about.php)
     */
    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();
        }
    }
}
