<?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, $user;

    $users = $mdb -> select( 'users', '*' );

    if ( $user['id'] === 1 )
    {
      return $users;
    }
    else
    {
      $users_list = [];
      foreach ( $users as $user_tmp )
      {
        if ( $user_tmp['id'] != 6 )
          $users_list[] = $user_tmp;
      }

      return $users_list;
    }
  }


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

    $result = $mdb -> get( 'users', '*', [ 'email' => strtolower( $email ) ] );

    if ( !$result )
      return false;

    if ( strtolower( $email ) !== strtolower( $result['email'] ) )
      return false;

    // bcrypt hash (migrated passwords)
    if ( password_verify( $plain_password, $result['password'] ) )
      return $result;

    // MD5 fallback (legacy passwords) — rehash to bcrypt on success
    if ( md5( $plain_password ) === $result['password'] )
    {
      $mdb -> update( 'users', [
        'password' => password_hash( $plain_password, PASSWORD_BCRYPT )
      ], [ 'id' => $result['id'] ] );

      return $result;
    }

    return false;
  }
}
