<?php
namespace front\factory;

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

    if ( !$sort = \Cache::fetch( "page_sort:$page_id" ) )
    {
      $sort = $mdb -> get( 'pp_pages', 'sort_type', [ 'id' => $page_id ] );

      \Cache::store( "page_sort:$page_id", $sort );
    }
    return $sort;
  }

  public static function lang_url( $page_id, $lang_id_t, $domain = '', $default_domain = '' )
  {
    $page = self::page_details( $page_id, $lang_id_t );

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

    if ( $lang_id_t == \S::get_session( 'current-lang' ) and !$default_domain and $lang_id_t == \front\factory\Languages::default_language( $domain ) )
      return $url;

    if ( $domain and $lang_id_t != \S::get_session( 'current-lang' ) )
      return 'http://' . $domain . $url;

    if ( !$domain && $default_domain )
    {
      if ( $lang_id_t != \front\factory\Languages::default_language( $default_domain ) and $url != '#' )
        $url = '/' . $lang_id_t . $url;

      return 'http://' . $default_domain . $url;
    }

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

    return $url;
  }

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

    $page_lang = $lang_id;

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

    if ( $lang_tmp )
      $page_lang = $lang_tmp;

    if ( !$page = \Cache::fetch( "page_details:$page_lang:$id" ) )
    {
      $page = $mdb -> get( 'pp_pages', '*', [ 'id' => (int)$id ] );
      $page['language'] = $mdb -> get( 'pp_pages_langs', '*', [ 'AND' => [ 'page_id' => (int)$id, 'lang_id' => $page_lang ] ] );

      \Cache::store( "page_details:$page_lang:$id", $page );
    }

    return $page;
  }

  public static function main_page_id()
  {
    global $mdb;

    if ( !$id = \Cache::fetch( 'main_page_id' ) )
    {
      $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 ] );
      \Cache::store( 'main_page_id', $id );
    }
    return $id;
  }
}
