<?php

use Illuminate\Support\Facades\Cache;

if (!empty($p) && $p instanceof Page) {
    // Resolve section id
    $top_parent = $p->get_top_parent_id($p->id);
    $section_id = ($p->id == $top_parent) ? $p->id : $p->sub_id;

    // Cache raw sidebar items (no 'active')
    $ttl = now()->addHours(24);
    $cacheKey = "section:menu:{$section_id}";

    $rawSidebar = Cache::remember($cacheKey, $ttl, function () use ($section_id) {
        $section = new Page($section_id);
        $subs = $section->get_subs();

        $used = [];
        $items = [];
        foreach ($subs as $s) {
            if (!in_array($s->url, $used, true)) {
                $items[] = [
                    'id' => $s->id ?? null,
                    'title' => $s->title ?? null,
                    'url' => $s->url,
                    'link' => $s->url,
                ];
                $used[] = $s->url;
            }
        }
        return $items;
    });

    // Add 'active' per request
    $current = request()->getRequestUri();
    $sidebar_navigation = array_map(static function ($item) use ($current) {
        $item['active'] = ($current === $item['url']) ? 1 : 0;
        return $item;
    }, $rawSidebar);

    // Provide section (object or light array)
    // If Twig needs Page methods, keep constructing the object (cheap relative to fetching children)
    $section = new Page($section_id);
    $twig->addGlobal('section', $section);

    // Expose sidebar
    $twig->addGlobal('section_menu', $sidebar_navigation);
}
