<?php
class LoginModel{
    const ID_TYPE_CUSTOMER = 2;

  /**
   * generatates a new password for the user given
   * @param  String $mail email of the user
   * @return String       confirtmation message
   */
  public static function forgotPassword($mail) {
      global $database;
      $mail = $database->escapeValue($mail);
      $now = new DateTime();
      $now = $now->format('Y-m-d H:i:s');

      $sql = "SELECT
                  u.username,
                  u.mail,
                  rut.idType AS idUserType,
                  ut.type AS type,
                  IF(
                      ADDTIME(u.tokenTS, '00:05') > '".$now."',
                      0,
                      1
                    ) AS allowPasswordGeneration
                  FROM ".TABLES['users']." u
                  INNER JOIN ".TABLES['rel_user_type']." rut
                  ON rut.idUser=u.id
                  INNER JOIN ".TABLES['user_types']." ut
                  ON ut.id=rut.idType
              WHERE mail = '".$mail."'";

      $userInfo = $database->fetchResultArray($sql);

      if(count($userInfo) == 0) {
          $data['messages'][] = [
              'code' => 'danger',
              'message' => 'NO_USER'
          ];

          return $data;
      }

      foreach ($userInfo as $info) {
          if($info['allowPasswordGeneration'] == 1) {
              $messageData = self::generateTokenForUserPassword(json_encode($info));
              $data['messages'][] = [
                  'code' => 'success',
                  'message' => 'GENERATED_SUCCESSFULLY'
              ];
          } else {
              $data['messages'][] = [
                  'code' => 'warning',
                  'message' => 'CHANGE_LATER'
              ];
          }
      }

      return $data;
  }

  /**
   * generates a new random password for the user provided
   * @param  Array $userInfo  contains username and password for the user of the password to change
   * @return Array            confirmation message
   */
  public static function generateTokenForUserPassword($userInfo) {
      global $database, $user;
      $userInfo = (array) json_decode($userInfo);

      $token = bin2hex(random_bytes(16));
      $tokenTimestamp = new DateTime();
      $sql = "UPDATE
                  ".TABLES['users']." u
              SET
                  u.token='".$token."',
                  u.tokenTS='".$tokenTimestamp->format('Y-m-d H:i:s')."'
              WHERE u.username='".$database->escapeValue($userInfo['username'])."'";

      $result = $database->query($sql);
      if($database->affectedRows() == 1) {
          $data['messages'][] = [
              'code' => 'success',
              'message' => 'PASSWORD_GENERATED'
          ];
      } else {
          $data['messages'][] = [
              'code' => 'error',
              'message' => 'ERROR_PASSWORD_GENERATED'
          ];
      }

      $data['messages'][] = UtilsModel::sendUserConfirmationMail($userInfo, $userInfo['mail'], 'generate', $token);

      return $data;
  }

  /**
   * change password for a user based on token
   * @param  String $token          token required to change the password
   * @param  HashArray $passwords   new password and confirm password array
   * @return HashArray              update message
   */
  public function changePassword($token, $passwords){
      global $user;
      $data = [];

      $confirmTokenMessage = $user->checkPasswordToken($token);
      if($confirmTokenMessage !== 'success') {

          $data['messages'][] = [
              'code' => 'error',
              'message' => 'INVALID_CHANGE_TOKEN'
          ];

          return $data;
      }

      $data = $user->resetPassword(json_encode($passwords));

      return $data;
  }
}
