<?php
namespace controls;

class Users
{

  public static function permissions( $user_id, $module = '', $action = '' )
  {
    // Pyziak Jacek
    $permissions[ 1 ][ 'projects' ] = true;
    $permissions[ 1 ][ 'finances' ] = true;
    $permissions[ 1 ][ 'wiki' ] = true;
    $permissions[ 1 ][ 'crm' ] = true;
    // Pyziak Grzegorz
    $permissions[ 3 ][ 'projects' ] = true;
    $permissions[ 3 ][ 'finances' ] = true;
    $permissions[ 3 ][ 'wiki' ] = true;
    $permissions[ 3 ][ 'crm' ] = true;
    // Roman Pyrih
    $permissions[ 5 ][ 'projects' ] = true;
    $permissions[ 5 ][ 'finances' ] = false;
    $permissions[ 5 ][ 'wiki' ] = true;
    $permissions[ 5 ][ 'crm' ] = false;

    if ( $action and isset( $permissions[ $user_id ][ $module ][ $action ] ) )
    {
      return $permissions[ $user_id ][ $module ][ $action ];
    }

    if ( isset( $permissions[ $user_id ][ $module ] ) )
    {
      return $permissions[ $user_id ][ $module ];
    }

    return true;
  }

  public static function logout()
  {
    $domain = preg_replace( '#^(http(s)?://)?w{3}\.#', '$1', $_SERVER['SERVER_NAME'] );
    $cookie_name = str_replace( '.', '-', $domain );

    setcookie( $cookie_name, "", strtotime( "-1 year" ), "/", $domain );
    session_destroy();
    header( 'Location: /' );
    exit;
  }

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

    if ( \factory\Users::settings_save( $user[ 'id' ], \S::get( 'pushover_api' ), \S::get( 'pushover_user' ) ) )
    {
      $user = $mdb -> get( 'users', '*', [ 'id' => $user[ 'id' ] ] );
      \S::set_session( 'user', $user );
      \S::alert( 'Ustawienia zostały zapisane.' );
    }
    header( 'Location: /users/settings/' );
    exit;
  }

  public static function settings()
  {
    global $user;

    if ( !$user )
    {
      return \Tpl::view( 'users/login-form' );
    }

    return \view\Users::settings(
        $user
    );
  }

  public static function login()
  {
    if ( $user = \factory\Users::login(
        \S::get( 'email' ),
        md5( \S::get( 'password' ) )
      ) )
    {
      // zapamiętaj logowanie
      if ( \S::get( 'remember' ) )
      {
        $domain = preg_replace( '#^(http(s)?://)?w{3}\.#', '$1', $_SERVER['SERVER_NAME'] );
        $cookie_name = str_replace( '.', '-', $domain );

        $value = [ 'email' => \S::get( 'email' ), 'hash' => md5( \S::get( 'password' ) ) ];
        $value = json_encode( $value );

        setcookie( $cookie_name, $value, strtotime( "+1 year" ), "/", $domain );
      }

      \S::set_session( 'user', $user );
      echo json_encode( [ 'result' => 'true', 'msg' => 'Właśnie zostałeś zalogowany. Za chwilę nastąpi przekierowanie.', 'default_project' => $user[ 'default_project' ] ] );
    }
    else
    {
      echo json_encode( [ 'result' => 'false', 'msg' => 'Podany login i hasło są nieprawidłowe.' ] );
    }
    exit;
  }

  public static function login_form()
  {
    return \Tpl::view( 'users/login-form' );
  }

}