<?php
namespace controls;

class Wiki
{

  static public function category_delete() {
    global $user;

    if ( !$user or!\controls\Users::permissions( $user[ 'id' ], 'wiki' ) )
      return false;
    if ( (int)$user['id'] !== 1 and (int)$user['id'] !== 3 )
      return false;

    if ( \factory\Wiki::category_delete( \S::get( 'id' ) ) )
      \S::alert( 'Kategoria została usunięta.' );

    header( 'Location: /wiki/main_view/' );
    exit;
  }

  public static function categories_delete_bulk()
  {
    global $user;

    if ( !$user or!\controls\Users::permissions( $user[ 'id' ], 'wiki' ) )
      return false;
    if ( (int)$user['id'] !== 1 and (int)$user['id'] !== 3 )
      return false;

    $ids = \S::get( 'ids' );
    if ( !is_array( $ids ) )
      $ids = [];

    $deleted_count = \factory\Wiki::categories_delete_bulk( $ids );

    if ( $deleted_count > 0 )
      \S::alert( 'UsuniÄ™to wpisy: ' . $deleted_count . '.' );
    else
      \S::alert( 'Nie wybrano poprawnych wpisĂłw do usuniÄ™cia.' );

    header( 'Location: /wiki/main_view/' );
    exit;
  }

  public static function category_save()
  {
    global $user;

    if ( !$user or!\controls\Users::permissions( $user[ 'id' ], 'wiki' ) )
      return false;

    if ( $id = \factory\Wiki::category_save( \S::get( 'id' ), \S::get( 'name' ), \S::get( 'text' ), \S::get( 'text_admin' ), \S::get( 'users' ) ) )
      \S::alert( 'Kategoria została zapisana.' );

    header( 'Location: /wiki/category_preview/id=' . $id );
    exit;
  }

  public static function category_edit()
  {
    global $user;

    if ( !$user or!\controls\Users::permissions( $user[ 'id' ], 'wiki' ) )
      return false;

    return \Tpl::view( 'wiki/category-edit', [
          'category' => \factory\Wiki::category_details( \S::get( 'id' ) ),
          'users' => \factory\Users::users_list()
      ] );
  }

  public static function category_preview()
  {
    global $user;

    if ( !$user or!\controls\Users::permissions( $user[ 'id' ], 'wiki' ) )
      return false;

    return \Tpl::view( 'wiki/category-preview', [
          'category' => \factory\Wiki::category_details( \S::get( 'id' ) ),
      ] );
  }

  public static function main_view()
  {
    global $user;

    if ( !$user or!\controls\Users::permissions( $user[ 'id' ], 'wiki' ) )
      return false;

    return \Tpl::view( 'wiki/main-view', [
      'user' => $user,
      'categories' => \factory\Wiki::get_categories()
    ] );
  }

}
