<?
namespace admin\factory;
class Authors
{
  // prosta lista autorów
  static public function get_simple_list()
  {
    global $mdb;
    return $mdb -> select( 'pp_authors', '*', [ 'ORDER' => [ 'author' => 'ASC' ] ] );
  }

  // usunięcie autora
  static public function delete_author( $id_author )
  {
    global $mdb;

    $result = $mdb -> delete( 'pp_authors', [ 'id' => (int)$id_author ] );
    \S::delete_cache();

    return $result;
  }

  // zapis autora
  static public function save_author( $id_author, $author, $image, $description )
  {
    global $mdb;

    if ( !$id_author )
    {
      $mdb -> insert( 'pp_authors', [
        'author' => $author,
        'image' => $image
      ] );

      $id = $mdb -> id();

      if ( $id )
      {
        $i = 0;

        $results = $mdb -> select( 'pp_langs', [ 'id' ], [ 'status' => 1, 'ORDER' => [ 'o' => 'ASC' ] ] );
        if ( is_array( $results ) and count( $results ) > 1 ) foreach ( $results as $row )
        {
          $mdb -> insert( 'pp_authors_langs', [
            'id_author' => (int)$id,
            'id_lang' => $row['id'],
            'description' => $description[ $i ]
          ] );
          $i++;
        }
        else if ( is_array( $results ) and count( $results ) == 1 ) foreach ( $results as $row )
        {
          $mdb -> insert( 'pp_authors_langs', [
            'id_author' => (int)$id,
            'id_lang' => $row['id'],
            'description' => $description
          ] );
        }

        \S::delete_cache();

        return $id;
      }
    }
    else
    {
      $mdb -> update( 'pp_authors', [
        'author' => $author,
        'image' => $image
        ], [
        'id' => (int)$id_author
      ] );

      $mdb -> delete( 'pp_authors_langs', [ 'id_author' => (int)$id_author ] );

      $i = 0;

      $results = $mdb -> select( 'pp_langs', [ 'id' ], [ 'status' => 1, 'ORDER' => [ 'o' => 'ASC' ] ] );
      if ( is_array( $results ) and count( $results ) > 1 ) foreach ( $results as $row )
      {
        $mdb -> insert( 'pp_authors_langs', [
          'id_author' => (int)$id_author,
          'id_lang' => $row['id'],
          'description' => $description[ $i ]
        ] );
        $i++;
      }
      else if ( is_array( $results ) and count( $results ) == 1 ) foreach ( $results as $row )
      {
        $mdb -> insert( 'pp_authors_langs', [
          'id_author' => (int)$id_author,
          'id_lang' => $row['id'],
          'description' => $description
        ] );
      }

      \S::delete_cache();

      return $id_author;
    }
    return false;
  }

  // szczególy autora
  static public function get_single_author( $id_author )
  {
    global $mdb;

    $author = $mdb -> get( 'pp_authors', '*', [ 'id' => (int)$id_author ] );

    $results = $mdb -> select( 'pp_authors_langs', '*', [ 'id_author' => (int)$id_author ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
      $author['languages'][$row['id_lang']] = $row;

    return $author;
  }
}