<?php

/**
 * This is the model class for table "datos_txt".
 *
 * The followings are the available columns in table 'datos_txt':
 * @property integer $id
 * @property string $nmb_archivo
 * @property string $descripcion
 * @property boolean $aprobado
 * @property string $fecha_aprobacion
 * @property string $fecha_registro
 * @property integer $id_usuario
 * @property string $num_comprobante
 * @property string $total_aporte
 * @property integer $cant_aportantes
 * @property boolean $valido
 */
class DatosTxt extends CActiveRecord
{
    public $fecha_aporte_range = array();
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'datos_txt';
	}
     public $banco;
     public $referencia;
     public $observacion;
	/**
	 * @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('nmb_archivo, fecha_registro', 'required','on'=>'old'),
			array('id_usuario, cant_aportantes', 'numerical', 'integerOnly'=>true),
			array('nmb_archivo', 'length', 'max'=>20),
			array('descripcion', 'length', 'max'=>300),
			array('num_comprobante', 'length', 'max'=>30),
                        array('banco,referencia,fecha_pagado', 'required', 'on' => 'pagar_form'),
                        array('banco', 'required', 'on' => 'pago_lote'),
                        #Escenario de Carga Masiva
                        array('nmb_archivo','unique','criteria'=>array('condition'=>'valido=TRUE'),'on'=>'carga_masiva_form'),
                        array('nmb_archivo, descripcion', 'required','on'=>'carga_masiva_form'),
                        array('nmb_archivo', 'match',
					'pattern' => '/^(M|Q|D)(\d){12}.xlsx$/',
					//'pattern' => '/^[0-9]\d{0,20}(\.[0-9]{0,2})?$/',
					'message' => 'El nombre del archivo debe tener un formato M000101012016.xlsx',
					'on'=>'carga_masiva_form',
			),
                        array('nmb_archivo,cant_aportantes,total_aporte','required','on'=>'linea1'),
                        array('fecha_aporte','date', 'format'=>'dd/MM/yyyy','on'=>'linea1'),
                        array('cant_aportantes', 'numerical', 'integerOnly'=>true,'on'=>'linea1'),
                        //array('total_aporte', 'numerical','numberPattern'=>'/^(\d)*(\,\d{0,2})?$/','on'=>'linea1','message'=>'El total de aportes debe tener el formato 100,00'),
//                        array('total_aporte', 'match',
//					'pattern' => '/^(\d)*(\,\d{0,2})?$/',
//					'message' => 'El total de aportes debe tener el formato 100,00',
//					'on'=>'linea1',
//			),
                    
                        array('aprobado,idunidad,banco,referencia,observacion,fecha_aporte, fecha_aprobacion, total_aporte, valido', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id,idunidad,migrado,fecha_aporte,fecha_aporte_range,nmb_archivo, descripcion, aprobado, fecha_aprobacion, fecha_registro, id_usuario, num_comprobante, total_aporte, cant_aportantes, valido, pagado, fecha_pagado, observaciones', 'safe', 'on'=>'search'),
			array('id,idunidad,migrado,fecha_aporte,fecha_aporte_range,nmb_archivo, descripcion, aprobado, fecha_aprobacion, fecha_registro, id_usuario, num_comprobante, total_aporte, cant_aportantes, valido, pagado, fecha_pagado, observaciones', 'safe', 'on'=>'searchPagado'),
		);
	}

	/**
	 * @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(
                    'unidades' => array(self::BELONGS_TO, 'Unidad', 'idunidad'),
                    'aportesTotal' => array(self::HAS_MANY, 'AportesTotal', 'id_dato_txt'),

		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'nmb_archivo' => 'Nombre del Archivo',
			'descripcion' => 'Descripcion',
			'aprobado' => 'Aprobado',
			'fecha_aprobacion' => 'Fecha Aprobación',
			'fecha_registro' => 'Fecha Registro',
			'id_usuario' => 'Usuario',
                        'banco' => 'Cuenta banco',
			'referencia' => 'Referencia',
			'observacion' => 'Observación',
			'num_comprobante' => 'Num. Comprobante',
			'total_aporte' => 'Total Aporte',
			'idunidad'=>'Unidad',
			'cant_aportantes' => 'Cant. Aportantes',
			'valido' => 'Valido',
                        'pagado'=> 'Pagado',
                        'fecha_pagado'=> 'Fecha ref pago',
                        'observaciones'=> 'observaciones',
		);
	}

	/**
	 * 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')){
		$id=Yii::app()->user->id;
                $filtro="id_usuario='$id'";
		}
                if (Yii::app()->user->checkAccess('usuario_administrador')){
		$filtro="  valido= true";
		}
                $criteria->condition = $filtro;
		//$criteria->condition = 'valido= true';
		$criteria->compare('id',$this->id);
		$criteria->compare('nmb_archivo',$this->nmb_archivo,true);
		$criteria->compare('descripcion',$this->descripcion,true);
		$criteria->compare('aprobado',$this->aprobado);
		$criteria->compare('fecha_aprobacion',$this->fecha_aprobacion,true);
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('id_usuario',$this->id_usuario);
		$criteria->compare('num_comprobante',$this->num_comprobante,true);
		$criteria->compare('total_aporte',$this->total_aporte,true);
		$criteria->compare('cant_aportantes',$this->cant_aportantes);
                $criteria->compare('idunidad',$this->idunidad);
		$criteria->compare('valido',$this->valido);
                $criteria->compare('pagado',$this->pagado);
                $criteria->compare('fecha_pagado',$this->fecha_pagado);
                $criteria->compare('observaciones',$this->observaciones);

        //fecha_vigencia_range
          $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);
              }
          }


		$_SESSION['datos_filtrados'] = new CActiveDataProvider($this, array(
                      'criteria'=>$criteria,
                      'sort'=>array( 'defaultOrder'=>'id DESC', ),
                      'pagination'=>false,
              ));
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,'sort'=>array( 'defaultOrder'=>'aprobado ASC, id DESC', ),
		));

	}


        public function searchPagado()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
		$criteria->condition = 'aprobado= true and pagado=0';
		$criteria->compare('id',$this->id);
		$criteria->compare('nmb_archivo',$this->nmb_archivo,true);
		$criteria->compare('descripcion',$this->descripcion,true);
		$criteria->compare('aprobado',$this->aprobado);
		$criteria->compare('fecha_aprobacion',$this->fecha_aprobacion,true);
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('id_usuario',$this->id_usuario);
		$criteria->compare('num_comprobante',$this->num_comprobante,true);
		$criteria->compare('total_aporte',$this->total_aporte,true);
		$criteria->compare('cant_aportantes',$this->cant_aportantes);
                $criteria->compare('idunidad',$this->idunidad);
		$criteria->compare('valido',$this->valido);
                $criteria->compare('pagado',$this->pagado);
                $criteria->compare('fecha_pagado',$this->fecha_pagado);
                //$criteria->compare('fecha_aporte',$this->fecha_aporte);
                $criteria->compare('observaciones',$this->observaciones);
                $criteria->order = 'idunidad asc,fecha_aporte:: date desc';

        //fecha_vigencia_range
          $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);
              }
          }


		$_SESSION['datos_filtrados'] = new CActiveDataProvider($this, array(
                      'criteria'=>$criteria,
                      'sort'=>array( 'defaultOrder'=>'idunidad asc', ),
                      'pagination'=>false,
              ));
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,'sort'=>array( 'defaultOrder'=>'idunidad asc', ),
		));

	}
        public function searchPagado_migrar()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
		$criteria->condition = 'aprobado= true and pagado=1';
		$criteria->compare('id',$this->id);
		$criteria->compare('nmb_archivo',$this->nmb_archivo,true);
		$criteria->compare('descripcion',$this->descripcion,true);
		$criteria->compare('aprobado',$this->aprobado);
		$criteria->compare('fecha_aprobacion',$this->fecha_aprobacion,true);
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('id_usuario',$this->id_usuario);
		$criteria->compare('num_comprobante',$this->num_comprobante,true);
		$criteria->compare('total_aporte',$this->total_aporte,true);
		$criteria->compare('cant_aportantes',$this->cant_aportantes);
                $criteria->compare('idunidad',$this->idunidad);
		$criteria->compare('valido',$this->valido);
                $criteria->compare('pagado',$this->pagado);
                $criteria->compare('fecha_pagado',$this->fecha_pagado);
                $criteria->compare('observaciones',$this->observaciones);
                $criteria->order = 'idunidad asc,fecha_aporte:: date desc';

        //fecha_vigencia_range
          $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);
              }
          }


		$_SESSION['datos_filtrados'] = new CActiveDataProvider($this, array(
                      'criteria'=>$criteria,
                      'sort'=>array( 'defaultOrder'=>'idunidad asc', ),
                      'pagination'=>false,
              ));
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,'sort'=>array( 'defaultOrder'=>'idunidad asc', ),
		));

	}
        
                /**
         *  BeforeSafe
         *  Se ejecuta antes de guardar
         */
//        protected function beforeSave() {
//		
//            #Monto en Bs
//            if($this->scenario='linea1'){
//                $this->total_aporte=str_replace('.', '', $this->total_aporte);
//                $this->total_aporte=str_replace(',', '.', $this->total_aporte);
//                if($this->total_aporte=='')$this->total_aporte=NULL;
//            }
//		return parent::beforeSave();
//	}
        
        
        

	/**
	 * 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 DatosTxt 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',
	    );
	}
}
