<?php
namespace front\factory;

class Menu
{
  public static function submenu_details( $page_id, $lang_id )
  {
    return self::subpages( $page_id, $lang_id );
  }

  static public function subpages( $page_id, $lang_id )
  {
    global $mdb;

    if ( !$pages = \Cache::fetch( "subpages:$page_id:$lang_id" ) )
    {
      $results = $mdb -> select( 'pp_pages', [ 'id' ], [ 'AND' => [ 'status' => 1, 'parent_id' => $page_id ], 'ORDER' => [ 'o' => 'ASC' ] ] );
      if ( is_array( $results ) ) foreach ( $results as $row )
      {
        $page = \front\factory\Pages::page_details( $row['id'] );
        $page['pages'] = self::subpages( $row['id'], $lang_id );

        $pages[] = $page;
      }

      \Cache::store( "subpages:$page_id", $pages );
    }
    return $pages;
  }

  public static function menu_details( $menu_id )
  {
    global $mdb, $lang_id;

    if ( !$menu = \Cache::fetch( "menu_details:$menu_id:$lang_id" ) )
    {
      $menu = $mdb -> get( 'pp_menus', '*', [ 'id' => (int)$menu_id ] );
      $menu['pages'] = self::menu_pages( $menu_id );

      \Cache::store( "menu_details:$menu_id:$lang_id", $menu );
    }
    return $menu;
  }

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

    if ( !$pages = \Cache::fetch( "menu_pages:$menu_id:$parent_id:$lang_id" ) )
    {
      $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;
      }

      \Cache::store( "menu_pages:$menu_id:$parent_id:$lang_id", $pages );
    }
    return $pages;
  }
}
