<?php
namespace menu;

class FMenu {
  
  public static function loadMenu( $id )
  {
    global $db;
    
    $query = $db -> prepare( 'SELECT * FROM pp_menu WHERE id = :id AND enabled = "1"' );
    $query -> bindValue( ':id', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {    
      $menu = new \menu\Menu;
      $menu -> set_id( $id );
      $menu -> set_sites( self::loadMenuPages( $id ) );
      $menu -> set_type( $row['type'] );
    }
    $query -> closeCursor();
    
    return $menu;
  }

  public static function loadMenuPages( $id, $parent_id = 0 )
  {
    global $db , $cache , $config;
    

    $current_lang = \System::getSessionVar( 'current_lang' );
    $key = 'loadMenu:' . $id . ':' . $current_lang . ':' . $parent_id;

    if ( !$sites = $cache -> fetch( $key . 'a' ) )
    {
      $query = $db -> prepare( 'SELECT id FROM pp_pages WHERE id_menu = :id_menu AND enabled = :enabled AND parent_id = :parent_id ORDER BY o' );
      $query -> bindValue( ':id_menu',    $id,        \PDO::PARAM_INT );
      $query -> bindValue( ':enabled',    1,          \PDO::PARAM_INT );
      $query -> bindValue( ':parent_id',  $parent_id, \PDO::PARAM_INT );
      $query -> execute();
      if ( $query -> rowCount() ) while( $row = $query -> fetch() )
      {
        $site = new \site\Site( $row['id'] );
        $site -> _values['subpages'] = self::loadMenuPages( $id, $row['id'] );
        $sites[] = $site;
      }
      $query -> closeCursor();
      $cache -> store( $key , $sites , $config['cache_expire'] );
    }

    return $sites;
  }
}
?>
