<?php

/**
 * This is the model class for table "montepio.aporte_fondo".
 *
 * The followings are the available columns in table 'montepio.aporte_fondo':
 * @property integer $id
 * @property string $id_asociado
 * @property string $id_txt
 * @property integer $id_taporte
 * @property string $aporte
 * @property string $fecha_aporte
 * @property string $fecha_registro
 * @property integer $id_unidad
 * @property integer $id_user
 * @property boolean $blnborrado
 * @property boolean $aprobado
 * @property string $referencia
 * @property string $fecha_referencia
 * @property boolean $pagado
 * @property string $id_banco_destino
 * @property string $cuenta_destino
 * @property string $observaciones
 * @property integer $id_aporte_status
 * @property integer $id_tnomina
 *
 * The followings are the available model relations:
 * @property Asociado $idAsociado
 * @property DatosTxtIntegrado $idTxt
 * @property Unidad $idUnidad
 * @property CrugeUser $idUser
 * @property TipoNomina $idTnomina
 * @property TipoSolicitud $idTaporte
 */
class AporteFondo extends CActiveRecord
{

	public $cedula;
    public $nombre;
    public $apellido;
    public $fecha_aporte_range=array();

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'montepio.aporte_fondo';
	}

	/**
	 * @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('id_taporte, id_unidad, id_user, id_aporte_status', 'numerical', 'integerOnly'=>true),
			array('aporte', 'length', 'max'=>20),
			array('id_asociado, id_txt, fecha_aporte, fecha_registro, blnborrado, aprobado, referencia, fecha_referencia, pagado, id_banco_destino, cuenta_destino, observaciones', 'safe'),

			####################################CARGA MASIVA DE APORTES FONDO#######################################

            array('cedula, id_unidad, id_tnomina, aporte', 'required','on'=>'cmasiva'),
            array('cedula, id_unidad', 'numerical','integerOnly'=>true,'on'=>'cmasiva'),
            array('id_tnomina ', 'match',
					'pattern' => '/^(MP|MA)$/',
					'message' => 'Formato de tipo de nomina Invalido: acepta MP o MA',
					'on'=>'cmasiva',
			),
            array('aporte', 'match',
					'pattern' => '/^(\d)*(\,\d{0,20})?$/',
					'message' => 'El {attribute} debe tener el siguiente formato 1000,00',
					'on'=>'cmasiva',
			),      
            array( 'cedula','validarAsociado','on'=>(self::getConf('NO DEFINIDOS')=='SI')?'cm_guardar':'cmasiva'), 
            array( 'id_unidad','validarUnidad','on'=>('cmasiva')),
            
            #Guardado
            array( 'id_tnomina', 'numerical','integerOnly'=>true,'on'=>'cm_guardar'),
                       
                    
                        ######################################################################################################

			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, cedula, nombre, apellido,fecha_aporte_range, id_asociado, id_txt, id_taporte, aporte, fecha_aporte, fecha_registro, id_unidad, id_user, blnborrado, aprobado, referencia, fecha_referencia, pagado, observaciones, id_aporte_status, id_tnomina', '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(
			'idAsociado' => array(self::BELONGS_TO, 'Asociado', 'id_asociado'),
			'idTxt' => array(self::BELONGS_TO, 'DatosTxtIntegrado', 'id_txt'),
			'idUnidad' => array(self::BELONGS_TO, 'Unidad', 'id_unidad'),
			'idUser' => array(self::BELONGS_TO, 'CrugeUser', 'id_user'),
			'idTnomina' => array(self::BELONGS_TO, 'TipoNomina', 'id_tnomina'),
			'idTaporte' => array(self::BELONGS_TO, 'TipoSolicitud', 'id_taporte'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'id_asociado' => 'Asociado',
			'id_txt' => 'Id Txt',
			'id_taporte' => 'Tipo de aporte',
			'aporte' => 'Aporte',
			'fecha_aporte' => 'Fecha Aporte',
			'fecha_registro' => 'Fecha Registro',
			'id_unidad' => 'Unidad',
			'id_user' => 'Usuario',
			'blnborrado' => 'Blnborrado',
			'aprobado' => 'Aprobado',
			'referencia' => 'Referencia',
			'fecha_referencia' => 'Fecha Referencia',
			'pagado' => 'Pagado',
			'id_banco_destino' => 'Banco Destino',
			'cuenta_destino' => 'Cuenta Destino',
			'observaciones' => 'Observaciones',
			'id_aporte_status' => 'Estatus del Aporte',
			'id_tnomina' => 'Tipo de nomina',
		);
	}

	/**
	 * 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('id',$this->id);
		$criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('id_txt',$this->id_txt,true);
		$criteria->compare('id_taporte',$this->id_taporte);
		$criteria->compare('aporte',$this->aporte,true);
		$criteria->compare('fecha_aporte',$this->fecha_aporte,true);
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('id_unidad',$this->id_unidad);
		$criteria->compare('id_user',$this->id_user);
		$criteria->compare('blnborrado',$this->blnborrado);
		$criteria->compare('aprobado',$this->aprobado);
		$criteria->compare('referencia',$this->referencia,true);
		$criteria->compare('fecha_referencia',$this->fecha_referencia,true);
		$criteria->compare('pagado',$this->pagado);
		$criteria->compare('id_banco_destino',$this->id_banco_destino,true);
		$criteria->compare('cuenta_destino',$this->cuenta_destino,true);
		$criteria->compare('observaciones',$this->observaciones,true);
		$criteria->compare('id_aporte_status',$this->id_aporte_status);
		$criteria->compare('id_tnomina',$this->id_tnomina);

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

	public function searchV($id)
	{
		// @todo Please modify the following code to remove attributes that should not be searched.
                
		$criteria=new CDbCriteria;
                $criteria->with='idAsociado';
		$criteria->compare('"idAsociado".cedula::TEXT',$this->cedula,true);
		$criteria->compare('LOWER("idAsociado".nombre::TEXT)',  strtolower($this->nombre),true);
		$criteria->compare('LOWER("idAsociado".apellidos::TEXT)',strtolower($this->apellido),true);
		$criteria->compare('id',$this->id);
		$criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('id_txt',$id);
		$criteria->compare('aporte::TEXT',$this->aporte,true);
		$criteria->compare('id_taporte',$this->id_taporte,true);
		$criteria->compare('id_tnomina',$this->id_tnomina,true);
		$criteria->compare('fecha_aporte',$this->fecha_aporte,true);
                //fecha_aporte
                $from = $to = '';
                if (count($this->fecha_aporte_range)>=1) {
                    if (isset($this->fecha_aporte_range['from'])) {
                        $from = $this->fecha_aporte_range['from'];
                    }
                    if (isset($this->fecha_aporte_range['to'])) {
                        $to= $this->fecha_aporte_range['to'];
                    }
                }
                if ($from!='' || $to !='') 
                {
                    if ($from!='' && $to!='') {
                        $from = date("d-m-Y", strtotime($from));
                        $to = date("d-m-Y", strtotime($to));
                        $criteria->compare('fecha_aporte',">= $from",false);
                        $criteria->compare('fecha_aporte',"<= $to",false);
                    }
                    else {
                        if ($from!='') $creation_time = $from;
                        if ($to != '') $creation_time = $to;
                        $creation_time = date("d-m-Y", strtotime($creation_time));
                        $criteria->compare('fecha_aporte', "$creation_time" ,false);
                    }
                }
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('id_unidad',$this->id_unidad,true);
		$criteria->compare('id_user',$this->id_user,true);
		$criteria->compare('blnborrado',$this->blnborrado);
		$criteria->addCondition('id_aporte_status !=4 OR  id_aporte_status IS NULL');

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

	public function getConf($att){
        
        $conf=ConfRetenciones::model()->find('atributo=:att',array(':att'=>$att));

        if($conf)return $conf->valor;
        else return NULL;
    }

    public function aporteAsociado(){
        
        $model = self::model()->find('id_txt=:id_txt AND id_asociado=:id_asociado ORDER BY id_asociado ASC, id asc',array(':id_txt'=>  $this->id_txt, ':id_asociado'=>$this->id_asociado));
        
        if($model)
            return $model->aporte;
        
        return 0;
    }

	public function validarUnidad($attributes){

        if($this->id_unidad){
            
            if(is_numeric($this->id_unidad)){
                
                $modelUnidad=Unidad::model()->find('idunidad=:id and blnborrado=FALSE',array(':id'=>$this->id_unidad));

                if(!$modelUnidad)
                    $this->addError('id_unidad','ID de Unidad inválido');
            }
        }
    }

    /**
    * validarAsociado valida que la cedula esta registrada en la caja de ahorro
    * @param type $attributes
    */
    public function validarAsociado($attributes){        

        if($this->cedula){
            
            if(is_numeric($this->cedula)){
            
            	if(is_numeric($this->cedula)){

	                $modelAsociado=Asociado::model()->find('cedula=:ci and blnborrado=FALSE and id_estatus=1',array(':ci'=>$this->cedula));

	                if(!$modelAsociado)
	                    $this->addError('cedula','La cédula no pertenece a ningún asociado activo '.$this->cedula);
                }
            }
        }
    }

    /*public function aporteAsociado(){

        $model = self::model()->find('id_txt=:id_txt AND id_asociado=:id_asociado ORDER BY id_asociado ASC, id asc',array(':id_txt'=>  $this->id_txt, ':id_asociado'=>$this->id_asociado));

        if($model)
            return $model->aporte;
        return 0;
    }*/

	/**
	 * 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 AporteFondo the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}
