<?php
namespace front\factory;

class Pages
{
  public static function page_sort( $page_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Pages::page_sort:$page_id";

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

    if ( !$objectData )
    {
      $sort = $mdb -> get( 'pp_pages', 'sort_type', [ 'id' => $page_id ] );

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

    return $sort;
  }

  public static function lang_url( $page_id, $lang_id )
  {
    $page = self::page_details( $page_id, $lang_id );

    $page['language']['seo_link'] ? $url = '/' . $page['language']['seo_link'] : $url = '/s-' . $page['id'] . '-' . \S::seo( $page['language']['title'] );

    if ( $lang_id != \front\factory\Languages::default_language() and $url != '#' )
      $url = '/' . $lang_id . $url;

    return $url;
  }

  public static function page_details( $id = '', $lang_tmp = '' )
  {
    global $mdb, $lang_id;

    if ( !$id )
      $id = self::main_page_id();

    if ( $lang_tmp )
      $lang_id = $lang_tmp;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Pages::page_details:$id:$lang_id";

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

    if ( !$objectData ) {
      $page = $mdb->get('pp_pages', '*', ['id' => (int)$id]);
      $page['language'] = $mdb->get('pp_pages_langs', '*', ['AND' => ['page_id' => (int)$id, 'lang_id' => $lang_id]]);

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

    return $page;
  }

  public static function main_page_id()
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Pages::main_page_id";

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

    if ( !$objectData )
    {
      $id = $mdb -> get( 'pp_pages', 'id', [ 'AND' => [ 'status' => 1, 'start' => 1 ] ] );
      if ( !$id )
        $id = $mdb -> get( 'pp_pages', 'id', [ 'status' => 1, 'ORDER' => [ 'menu_id' => 'ASC', 'o' => 'ASC' ], 'LIMIT' => 1 ] );

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

    return $id;
  }
}
