<?
namespace admin\factory;
class Dictionaries
{
  static public function all_units()
  {
    global $mdb;

    $results = $mdb -> select( 'pp_units', '*' );
    foreach ( $results as $row )
    {
      $resutls2 = $mdb -> query( 'SELECT text FROM pp_units_langs AS psl, pp_langs AS pl WHERE unit_id = ' . $row['id'] . ' AND lang_id = pl.id AND text != \'\' ORDER BY o ASC LIMIT 1' ) -> fetchAll( \PDO::FETCH_ASSOC );
      $row['text'] = $resutls2[0]['text'];
      $units[ $row['id'] ] = $row;
    }
    return $units;
  }

  static public function unit_details( $unit_id )
  {
    global $mdb;

    $unit = $mdb -> get( 'pp_units', '*', [ 'id' => (int)$unit_id ] );

    $results = $mdb -> select( 'pp_units_langs', '*', [ 'unit_id' => (int)$unit_id ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
      $unit['languages'][ $row['lang_id'] ] = $row;

    return $unit;

  }

  static public function unit_save( $unit_id, $text )
  {
    global $mdb;

    if ( !$unit_id )
    {
      $mdb -> insert( 'pp_units', array());

      $id = $mdb -> id();

      if ( $id )
      {
        foreach ( $text as $key => $val )
        {
          $mdb -> insert( 'pp_units_langs', [
            'unit_id' => (int)$id,
            'lang_id' => $key,
            'text' => $text[$key]
          ] );
        }

        \S::delete_dir( '../temp/' );

        return $id;
      }
    }
    else
    {
      foreach ( $text as $key => $val )
      {
        if ( $translation_id = $mdb -> get( 'pp_units_langs', 'id', [ 'AND' => [ 'unit_id' => $unit_id, 'lang_id' => $key ] ] ) )
          $mdb -> update( 'pp_units_langs', [
            'lang_id' => $key,
            'text' => $text[$key]
          ], [
            'id' => $translation_id
          ] );
        else
          $mdb -> insert( 'pp_units_langs', [
            'unit_id' => (int)$unit_id,
            'lang_id' => $key,
            'text' => $text[$key]
          ] );
      }

      \S::delete_dir( '../temp/dictionaries' );

      return $unit_id;
    }
  }

  static public function unit_delete( $unit_id )
  {
    global $mdb;
    return $mdb -> delete( 'pp_units', [ 'id' => (int)$unit_id ] );
  }
}