<?php

if (!empty($p) && $p instanceof Page) {

    // Work out if need to traverse to section header or if this is a section

    $top_parent = $p->get_top_parent_id($p->id);

    if ($p->id == $top_parent) {
        $section_id = $p->id;
    } else {
        $section_id = $p->sub_id;
    }

    // Create section page object
    $section = new Page($section_id);

    // Expose Section page object to twig
    $twig->addGlobal('section', $section);

    //$sidebar_navigation = CMSNav::tree($section_id, 9994);
 
    $page_subs = $section->get_subs();
    
    $used = [];
    $sidebar_navigation = [];
    foreach($page_subs as $s) {
        
        if( !in_array($s->url, $used) ) {
            
            if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] == $s->url) {
                $s->active = 1;
            }else{
                $s->active = 0;
            }
            $s->link = $s->url;
            $sidebar_navigation[] = $s;
        }

        $used[] = $s->url;
    }

    
    // Expose Section Menu array to twig
    $twig->addGlobal('section_menu', $sidebar_navigation);

}
