<?php
namespace front\factory;

class Languages
{
  public static function default_language()
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Languages::default_language";

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

    if ( !$objectData )
    {
      $results = $mdb -> query( 'SELECT id FROM pp_langs WHERE status = 1 ORDER BY start DESC, o ASC LIMIT 1' ) -> fetchAll();
      $default_language = $results[0][0];

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

  public static function active_languages()
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Languages::active_languages";

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

    if ( !$objectData )
    {
      $active_languages = $mdb -> select( 'pp_langs', [ 'id', 'name' ], [ 'status' => 1, 'ORDER' => [ 'o' => 'ASC' ] ] );

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

    return $active_languages;
  }

  public static function lang_translations( $language = 'pl' )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Languages::lang_translations:$language";

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

    if ( !$objectData )
    {
      $translations[ '0' ] = $language;

      $results = $mdb -> select( 'pp_langs_translations', [ 'text', $language ] );
      if ( is_array( $results ) ) foreach ( $results as $row )
        $translations[ $row['text'] ] = $row[ $language ];

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

    return $translations;
  }
}
