<?php
namespace language;

class FLanguage {
  
  public static function getLangs()
  {
    global $db, $cache, $config, $lang;

    $key = 'getLangs';

    if ( !$langs = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT id , name FROM pp_langs WHERE enabled=:enabled' );
      $query -> bindValue( ':enabled', 1, \PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      {
        $lg['id']   = $row['id'];
        $lg['name'] = $lang -> getTrans( $row['name'] );
        $langs[]    = $lg;
      }
      $query -> closeCursor();
      $cache -> store( $key , $langs , $config['cache_expire_long' ] );
    }
    return $langs;
  }

  public static function loadLang( $language_tmp = 'pl', $admin = false )
  {
    global $cache, $db, $config;

    $language_tmp = \language\Flanguage::checkLangCorrection( $language_tmp );

    $key = 'loadLang:' . $language_tmp;

    if ( !$translation = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT text, ' . $language_tmp . ' FROM pp_langs_text' );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $translation[ $row['text'] ] = $row[ $language_tmp ];
      $query -> closeCursor();
      $cache -> store( $key , $translation , $config['cache_expire_long' ] );
    }
    \System::setSessionVar( 'current_lang' , $language_tmp , $admin );

    $language = new \language\Language( $language_tmp );
    $language -> set_translation( $translation );

    return $language;
  }

  private static function checkLangCorrection( $lang_check )
  {
    switch ( $lang_check )
    {
      case 'pl':
        return 'pl';
      break;
      case 'en':
        return 'en';
      break;
      case 'ru':
        return 'ru';
      break;
      case 'de':
        return 'de';
      break;
      case 'uk':
        return 'uk';
      break;
      default:
        return 'pl';
      break;
    }
  }
}
?>
