<?php

/**
 * UserRecoveryForm class.
 * UserRecoveryForm is the data structure for keeping
 * user recovery form data. It is used by the 'recovery' action of 'UserController'.
 */
class FormularioRecuperarUsuario extends CFormModel {

    public $login_or_email, $user_id;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
            // username and password are required
            array('login_or_email', 'required'),
            array('login_or_email', 'match', 'pattern' => '/^[A-Za-z0-9@.-\s,]+$/u', 'message' => UsuarioModule::t("Incorrect symbols (A-z0-9).")),
            // password needs to be authenticated
            array('login_or_email', 'existeUsuario'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
            'login_or_email' => UserModule::t("username or email"),
        );
    }

    public function existeUsuario($attribute, $params) {
        if (!$this->hasErrors()) {  // we only want to authenticate when no input errors
            if (strpos($this->login_or_email, "@")) {
                $usuario = Usuario::model()->findByAttributes(array('email' => $this->login_or_email));
                if ($usuario)
                    $this->user_id = $usuario->id;
            } else {
                $usuario = User::model()->findByAttributes(array('username' => $this->login_or_email));
                if ($usuario)
                    $this->user_id = $usuario->id;
            }

            if ($usuario === null) {
                if (strpos($this->login_or_email, "@")) {
                    $this->addError("login_or_email", UsuarioModule::t("Email is incorrect."));
                } else {
                    $this->addError("login_or_email", UsuarioModule::t("Username is incorrect."));
                }
            }
        }
    }

}