<?php
namespace factory;

class Wiki
{
  static public function category_delete( int $category_id ) {
    global $mdb;
    return $mdb -> delete( 'wiki', [ 'id' => $category_id ] );
  }

  public static function category_save( $category_id, $name, $text, $text_admin = '', $users )
  {
    global $mdb;

    if ( !$category_id )
    {
      $mdb -> insert( 'wiki', [
        'name' => $name,
        'text' => $text,
        'text_admin' => $text_admin ? $text_admin : null
      ] );
      $category_id = $mdb -> id();
    }
    else
    {
      $mdb -> update( 'wiki', [
        'text' => $text,
        'name' => $name,
        'text_admin' => $text_admin ? $text_admin : null
      ], [
        'id' => $category_id
      ] );
      $mdb -> delete( 'wiki_users', [ 'wiki_id' => $category_id ] );
    }

    if ( is_array( $users ) ) foreach ( $users as $key => $val ) {
      $mdb -> insert( 'wiki_users', [
        'wiki_id' => $category_id,
        'user_id' => $val
      ] );
    }
    return $category_id;
  }

  public static function category_details( $category_id ) {
    global $mdb;
    $category = $mdb -> get('wiki', '*', [ 'id' => $category_id ]);
    $category['users'] = $mdb -> select( 'wiki_users', 'user_id', [ 'wiki_id' => $category_id ] );
    return $category;
  }

  static public function category_users( $category_id )
  {
    global $mdb;
    return $mdb -> select( 'wiki_users', 'user_id', [ 'wiki_id' => $category_id ] );
  }

  static public function get_categories()
  {
    global $mdb, $user;

    if ( $user['id'] == 1 or $user['id'] == 3 )
      return $mdb -> select( 'wiki', '*', [ 'ORDER' => [ 'name' => 'ASC' ] ] );
    else
      return $mdb -> query( 'SELECT w.* FROM wiki AS w INNER JOIN wiki_users AS wu ON wu.wiki_id = w.id WHERE user_id = ' . $user['id'] ) -> fetchAll( \PDO::FETCH_ASSOC );
  }
}
