<?php

/**
 * This is the model class for table "cruge_user".
 *
 * The followings are the available columns in table 'cruge_user':
 * @property integer $iduser
 * @property string $regdate
 * @property string $actdate
 * @property string $logondate
 * @property string $username
 * @property string $email
 * @property string $password
 * @property string $authkey
 * @property integer $state
 * @property integer $totalsessioncounter
 * @property integer $currentsessioncounter
 *
 * The followings are the available model relations:
 * @property CrugeFieldvalue[] $crugeFieldvalues
 * @property CrugeAuthitem[] $crugeAuthitems
 */
class CrugeUserI extends CActiveRecord
{
	public $passwordActual, $repetirPassword;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'cruge_user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(

			array('password,repetirPassword', 'required', 'on'=>'actualizacion'),
			array('state, totalsessioncounter, currentsessioncounter', 'numerical', 'integerOnly'=>true),
			array('password, passwordActual, repetirPassword', 'required', 'on'=>'cambio'),
			array('password, repetirPassword','length', 'min'=>8, 'on'=>array('cambio','actualizacion')),

			array('username, password', 'length', 'max'=>64),
			array('email', 'length', 'max'=>45),
			array('authkey', 'length', 'max'=>100),
			array('regdate, actdate, logondate, passwordActual, repetirPassword', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('iduser, regdate, actdate, logondate, username, email, password, authkey, state, totalsessioncounter, currentsessioncounter,cedula,nombres,apellidos', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'crugeFieldvalues' => array(self::HAS_MANY, 'CrugeFieldvalue', 'iduser'),
                        'usu' => array(self::HAS_MANY, 'ActiveRecordLog', 'userid'),
                        'asociado' => array(self::HAS_MANY, 'Asociado', 'cedula', 'condition'=>'blnborrado= TRUE'),
			'crugeAuthitems' => array(self::MANY_MANY, 'CrugeAuthitem', 'cruge_authassignment(userid, itemname)'),
                        'idAsociado' => array(self::HAS_ONE, 'Asociado', 'id_usuario'),  
                        'unidadUsuarios' => array(self::HAS_MANY, 'UnidadUsuario', 'idusuario'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'iduser' => 'Iduser',
			'regdate' => 'Regdate',
			'actdate' => 'Actdate',
			'logondate' => 'Logondate',
			'username' => 'Username',
			'email' => 'Email',
			'password' => 'Password',
			'authkey' => 'Authkey',
			'state' => 'State',
			'totalsessioncounter' => 'Totalsessioncounter',
			'currentsessioncounter' => 'Currentsessioncounter',
			'cedula' => 'Cédula',
			'nombres'=>'Nombres',
			'apellidos'=>'Apellidos',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('iduser',$this->iduser);
		$criteria->compare('regdate',$this->regdate,true);
		$criteria->compare('actdate',$this->actdate,true);
		$criteria->compare('logondate',$this->logondate,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('authkey',$this->authkey,true);
		$criteria->compare('state',$this->state);
		$criteria->compare('totalsessioncounter',$this->totalsessioncounter);
		$criteria->compare('currentsessioncounter',$this->currentsessioncounter);
		$criteria->compare('cedula',$this->logondate);
		$criteria->compare('nombres',$this->logondate,true);
		$criteria->compare('apellidos',$this->logondate,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return CrugeUser the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function check_Userinfo($user_info){

		$user_o_email = strpos($user_info, '@');
		//echo "<pre>user o email";print_r($user_o_email);echo "\n";print_r($user_info);exit;

		if (empty($user_o_email)) { //Recuperacion de clave por username ó cedula

			$user_inf = array('cruge_model'=>'', 
									'asociado_model'=>'', 
									'user_role'=>'', 
									'asoc'=>true,
									'asoc_activo'=>true,
									'acc_activa'=>true,
									'asoc_admin'=>true,
									'error'=>'');

			$a = intval($user_info);
			//echo "<pre>";print_r($a);exit;
			if (!empty($a)) { //Si username es entero
				
				$usuario = Asociado::model()->findAll('cedula=:ci', array(':ci'=>$user_info));
				$cruge = self::model()->find('username=:user', array(':user'=>$user_info));

				if (!empty($usuario)) { //Si existe el asociado

					if (count($usuario) == 1) {

						foreach ($usuario as $key => $value) {
							
							if ($value->id_estatus == 1 || $value->id_estatus == 4) {

								$cruge_user = self::model()->find('username=:user and state = 1', array(':user'=>$value->cedula));

								if (!empty($cruge_user)) { //Cuenta cruge con estatus activa

									$rol = Roles::model()->find('userid=:id', array(':id'=>$cruge_user->iduser));

									if (!empty($rol)) {

										$user_inf['cruge_model'] = $cruge_user;
										$user_inf['asociado_model'] = $value;
										$user_inf['user_role'] = $rol->itemname;

										return $user_inf;
									}

								}else{ //Cuenta cruge con otros estatus

									$user_inf['acc_activa'] = false;
									$user_inf['error'] = 'Su cuenta se encuentra inactiva o suspendida, verifique.';

									return $user_inf;
								}
							
							}elseif ($value->id_estatus == 2 || $value->id_estatus == 3){

								$user_inf['asoc_activo'] = false;
								$user_inf['error'] = 'Este asociado se encuentra con estatus liquidado o fallecido.';

								return $user_inf;
							}
						}

					}elseif (count($usuario) > 1) {
						
						foreach ($usuario as $key => $value) {
							
							if ($value->id_estatus != 2) {
								
								if ($value->id_estatus == 1 || $value->id_estatus == 4) {

									$cruge_user = self::model()->find('username=:user and state = 1', array(':user'=>$value->cedula));

									if (!empty($cruge_user)) { //Cuenta cruge con estatus activa

										$rol = Roles::model()->find('userid=:id', array(':id'=>$cruge_user->iduser));

										if (!empty($rol)) {

											$user_inf['cruge_model'] = $cruge_user;
											$user_inf['asociado_model'] = $value;
											$user_inf['user_role'] = $rol->itemname;

											return $user_inf;
										}

									}else{ //Cuenta cruge con otros estatus

										$user_inf['acc_activa'] = false;
										$user_inf['error'] = 'Su cuenta se encuentra inactiva o suspendida, verifique.';

										return $user_inf;
									}
								
								}elseif ($value->id_estatus == 2 || $value->id_estatus == 3){

									$user_inf['asoc_activo'] = false;
									$user_inf['error'] = 'Este asociado se encuentra con estatus liquidado o fallecido.';

									return $user_inf;
								}
							}
						}
					}

				}else{ //Si no existe el asociado

					if (!empty($cruge)) {

						$cruge_user = self::model()->find('username=:user and state = 1', array(':user'=>$user_info));

						if (!empty($cruge_user)) { //Cuenta cruge con estatus activa

							$rol = Roles::model()->find('userid=:id', array(':id'=>$cruge_user->iduser));

							if (!empty($rol)) {

								$user_inf['cruge_model'] = $cruge_user;
								$user_inf['user_role'] = $rol->itemname;

								return $user_inf;
							}

						}else{ //Cuenta cruge con otros estatus

							$user_inf['asoc'] = false;
							$user_inf['error'] = 'Su cuenta se encuentra inactiva o suspendida.';

							return $user_inf;
						}
					
					}else{

						$user_inf['asoc_admin'] = false;
						$user_inf['error'] = 'El username suministrado no se encuentra registrado';

						return $user_inf;
					}
				}			
			
			}else{ //Si username es cadena

				$cruge_user = self::model()->find('username=:user and state = 1', array(':user'=>$user_info));

				if (!empty($cruge_user)) { //Cuenta cruge con estatus activa

					$rol = Roles::model()->find('userid=:id', array(':id'=>$cruge_user->iduser));

					if (!empty($rol)) {

						$user_inf['cruge_model'] = $cruge_user;
						$user_inf['user_role'] = $rol->itemname;
//echo "<pre>es cadena";print_r($user_inf);exit;
						return $user_inf;
					}

				}else{ //Cuenta cruge con otros estatus

					$user_inf['asoc'] = false;
					$user_inf['error'] = 'Su cuenta se encuentra inactiva o suspendida.';

					return $user_inf;
				}	
			}
		
		}else{ //Recuperacion de clave por correo

			return false;
		}
	}

    public function getFullName()
    {
        return $this->nombres .' '. $this->apellidos;
    }
}
