<?php

/**
 * This is the model class for table "pago_extra".
 *
 * The followings are the available columns in table 'pago_extra':
 * @property integer $id
 * @property integer $idtrabajador
 * @property integer $idaporte_extra
 * @property integer $idbanco_origen
 * @property string $monto
 * @property integer $idbanco_destino
 * @property string $cuenta_destino
 * @property integer $idtipo_transaccion
 * @property string $referencia
 * @property string $fechapago
 * @property boolean $blnborrado
 * @property string $fecharegistro
 * @property integer $usuario_registro
 */
class PagoExtra extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
         public $fechapago_range = array();
     public $fecharegistro_range = array();
     public $unidad;
	public function tableName()
	{
		return 'pago_extra';
	}

	/**
	 * @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('idtrabajador, idaporte_extra,  idbanco_destino, usuario_registro', 'numerical', 'integerOnly'=>true),
                    array('cuenta_destino', 'length', 'min'=>20),
                    array('monto,idtrabajador, idaporte_extra,  idbanco_destino, cuenta_destino, referencia, fechapago', 'required'),
			array('pago_patron,aprobado,monto,idtrabajador, idaporte_extra, idbanco_origen, idbanco_destino, cuenta_destino, referencia, fechapago, blnborrado, fecharegistro', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('pago_patron,unidad,aprobado,fecharegistro_range,fechapago_range,aprobado,id, idtrabajador, idaporte_extra, monto, idbanco_destino, cuenta_destino,  referencia, fechapago, blnborrado, fecharegistro, usuario_registro', '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(
                    'trabajador' => array(self::BELONGS_TO, 'Asociado', 'idtrabajador'),
                    'aporte' => array(self::BELONGS_TO, 'AporteExtra', 'idaporte_extra'),
                    'banco_ori' => array(self::BELONGS_TO, 'Banco', 'idbanco_origen'),
                    'banco_des' => array(self::BELONGS_TO, 'Banco', 'idbanco_destino'),
                    'transaccion' => array(self::BELONGS_TO, 'Transaccion', 'idtipo_transaccion'),
                    'aprobar' => array(self::BELONGS_TO, 'Estatus', 'aprobado'),
                    //'unidad' => array(self::BELONGS_TO, 'Unidad', 'aprobado'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'idtrabajador' => 'Trabajador',
			'idaporte_extra' => 'aporte extra',
			'idbanco_origen' => 'banco Origen',
			'monto' => 'Monto',
			'idbanco_destino' => 'banco Destino',
			'cuenta_destino' => 'Cuenta Destino',
			'idtipo_transaccion' => 'Tipo Transaccion',
			'referencia' => 'Referencia',
			'fechapago' => 'Fecha de pago',
			'blnborrado' => 'Blnborrado',
			'fecharegistro' => 'Fecha registro',
			'usuario_registro' => 'Usuario Registro',
                        'unidad'=>'Unidad',
		);
	}

	/**
	 * 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;
                $filtro="";
		if (Yii::app()->user->checkAccess('usuario_asociado')){
		 $user=Yii::app()->user->id;
        	$sql = "select * from cruge_user where iduser= $user and state= 1";
		$resp = Yii::app()->db->createCommand($sql)->queryAll();
        	$id= $resp[0]['cedula'];	
                $trabajador = Asociado::model()->findAll('"cedula"=:cedula and blnborrado=false', array(':cedula'=>$id)); 
                if($trabajador!=null){
                   $idtrabajador=$trabajador[0]["idasociado"];
                $filtro="and idtrabajador='$idtrabajador'";                   
                }
		}
		$filtro=" t.blnborrado=false $filtro";		
		
                $criteria->condition = $filtro;
		$criteria->compare('id',$this->id);
		//$criteria->compare('idtrabajador',$this->idtrabajador);
		$criteria->compare('idaporte_extra',$this->idaporte_extra);
		$criteria->compare('idbanco_origen',$this->idbanco_origen);
		$criteria->compare('monto',$this->monto,true);
		$criteria->compare('idbanco_destino',$this->idbanco_destino);
		$criteria->compare('cuenta_destino',$this->cuenta_destino,true);
		$criteria->compare('idtipo_transaccion',$this->idtipo_transaccion);
		$criteria->compare('referencia',$this->referencia,true);
		$criteria->compare('fechapago',$this->fechapago,true);
		$criteria->compare('blnborrado',$this->blnborrado);
		$criteria->compare('fecharegistro',$this->fecharegistro,true);
		$criteria->compare('usuario_registro',$this->usuario_registro);
                $criteria->compare('pago_patron',$this->pago_patron);
                $criteria->compare('aprobado',$this->aprobado);
                $criteria->addSearchCondition('trabajador.nombre || trabajador.apellidos || trabajador.cedula',  strtoupper($this->idtrabajador),true);
                $criteria->addSearchCondition('trabajador.idunidad::text',$this->unidad,false);
                $criteria->with = 'trabajador';

                          $from = $to = '';
          if (count($this->fecharegistro_range)>=1) {
              if (isset($this->fecharegistro_range['from'])) {
                  $from = $this->fecharegistro_range['from'];
              }
              if (isset($this->fecharegistro_range['to'])) {
                  $to= $this->fecharegistro_range['to'];
              }
          }
          if ($from!='' || $to !='') {
              if ($from!='' && $to!='') {
                  $from = date("d-m-Y", strtotime($from));
                  $to = date("d-m-Y", strtotime($to));
                  $criteria->compare('fecharegistro',">= $from",false);
                  $criteria->compare('fecharegistro',"<= $to",false);
              }
              else {
                  if ($from!='') $creation_time = $from;
                  if ($to != '') $creation_time = $to;
                  $creation_time = date("d-m-Y", strtotime($creation_time));
                  $criteria->compare('fecharegistro', "$creation_time" ,false);
              }
          }
          $from = $to = '';
          if (count($this->fechapago_range)>=1) {
              if (isset($this->fechapago_range['from'])) {
                  $from = $this->fechapago_range['from'];
              }
              if (isset($this->fechapago_range['to'])) {
                  $to= $this->fechapago_range['to'];
              }
          }
          if ($from!='' || $to !='') {
              if ($from!='' && $to!='') {
                  $from = date("d-m-Y", strtotime($from));
                  $to = date("d-m-Y", strtotime($to));
                  $criteria->compare('fechapago',">= $from",false);
                  $criteria->compare('fechapago',"<= $to",false);
              }
              else {
                  if ($from!='') $creation_time = $from;
                  if ($to != '') $creation_time = $to;
                  $creation_time = date("d-m-Y", strtotime($creation_time));
                  $criteria->compare('fechapago', "$creation_time" ,false);
              }
          }
              $_SESSION['datos_filtrados'] = new CActiveDataProvider($this, array(
                      'criteria'=>$criteria,
                      'pagination'=>false,
              ));
		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 PagoExtra the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}


       public function behaviors()
	{
	    return array(
		    // Classname => path to Class
		    'ActiveRecordLogableBehavior'=>
		    	'application.behaviors.ActiveRecordLogableBehavior',
	    );
	}
}
