<?php
namespace front\factory;

class Menu
{
  public static function menu_details( $menu_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Menu::menu_details:$menu_id";

    $objectData = $cacheHandler -> get( $cacheKey );

    if ( !$objectData )
    {
      $menu = $mdb -> get( 'pp_menus', '*', [ 'id' => (int)$menu_id ] );
      $menu['pages'] = self::menu_pages( $menu_id );

      $cacheHandler -> set( $cacheKey, $menu );
    }
    else
    {
      return unserialize( $objectData );
    }

    return $menu;
  }

  public static function menu_pages( $menu_id, $parent_id = null )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Menu::menu_pages:$menu_id:$parent_id";

    $objectData = $cacheHandler->get($cacheKey);

    if ( !$objectData )
    {
      $results = $mdb -> select( 'pp_pages', [ 'id' ], [ 'AND' => [ 'status' => 1, 'menu_id' => (int)$menu_id, 'parent_id' => $parent_id ], 'ORDER' => [ 'o' => 'ASC' ] ] );
      if ( is_array( $results ) ) foreach ( $results as $row )
      {
        $page = \front\factory\Pages::page_details( $row['id'] );
        $page['pages'] = self::menu_pages( $menu_id, $row['id'] );

        $pages[] = $page;
      }

      $cacheHandler -> set( $cacheKey, $pages );
    }
    else
    {
      return unserialize($objectData);
    }

    return $pages;
  }
}
