<?php
namespace front\factory;

class Languages
{
  public static function default_domain()
  {
    global $mdb;
    $results = $mdb -> query( 'SELECT domain FROM pp_langs WHERE status = 1 AND domain IS NOT NULL AND main_domain = 1' ) -> fetchAll();
    return $default_domain = $results[0][0];
  }
  
  public static function default_language( $domain = '' )
  {
    global $mdb;    
    if ( !$default_language = \Cache::fetch( "default_language:$domain" ) )
    {
      if ( $domain )
        $results = $mdb -> query( 'SELECT id FROM pp_langs WHERE status = 1 AND domain = \'' . $domain . '\' ORDER BY start DESC, o ASC LIMIT 1' ) -> fetchAll();
      if ( !$domain or !\front\factory\Languages::default_domain() )
        $results = $mdb -> query( 'SELECT id FROM pp_langs WHERE status = 1 AND domain IS NULL ORDER BY start DESC, o ASC LIMIT 1' ) -> fetchAll();
      $default_language = $results[0][0];
              
      \Cache::store( "default_language:$domain", $default_language );
    }
    return $default_language;
  }
  
  public static function active_languages()
  {
    global $mdb;
    
    if ( !$active_languages = \Cache::fetch( 'active_languages' ) )
    {
      $active_languages = $mdb -> select( 'pp_langs', [ 'id', 'name', 'domain' ], [ 'status' => 1, 'ORDER' => [ 'o' => 'ASC' ] ] );              
      \Cache::store( 'active_languages', $active_languages );
    }
    return $active_languages;
  }
  
  public static function lang_translations( $language = 'pl' )
  {
    global $mdb;
    
    if ( !$translations = \Cache::fetch( "lang_translations:$language" ) )
    {
      $translations[ '0' ] = $language;  
      
      $results = $mdb -> select( 'pp_langs_translations', [ 'text', $language ] );
      if ( is_array( $results ) ) foreach ( $results as $row )
        $translations[ $row['text'] ] = $row[ $language ];
      
      \Cache::store( "lang_translations:$language", $translations );
    }
    
    return $translations;
  }
}
