<?php

/**
 * This is the model class for table "pagos.datos_nomina_orden_pago".
 *
 * The followings are the available columns in table 'pagos.datos_nomina_orden_pago':
 * @property integer $id
 * @property integer $cant_pago
 * @property double $total_pago
 * @property string $nombre_archivo
 * @property string $fecha_pago
 */
class DatosNominaOrdenPago extends CActiveRecord
{
	public $id_estatus, $nombre_estatus, $fecha_estatus, $fecha_estatus_range =[];
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'pagos.datos_nomina_orden_pago';
	}

	/**
	 * @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('nombre_archivo,descripcion, id_concepto','required','on'=>array('RegistroMasivo')),
			array('nombre_archivo', 'match',
                'pattern' => '/^(OP)\d{8}.xlsx|xls$/',
                'message' => 'El nombre del archivo debe tener un formato OPDDMMAAAA.xls o OPDDMMAAAA.xlsx',
                'on'=>'RegistroMasivo',
            ),
			array('nombre_archivo','ValidarNombreArchivo','on'=>'RegistroMasivo'),
				array('nombre_archivo,cant_pago,total_pago','required','on'=>'carga_ajuste'),
			// array('nombre_archivo','ValidarNombreArchivo','on'=>'carga_ajuste'),
            array('fecha_pago','date', 'format'=>'dd-MM-yyyy','on'=>'carga_ajusxte'),
            array('cant_pago', 'numerical', 'integerOnly'=>true,'on'=>'carga_ajuste'),

			array('cant_pago', 'numerical', 'integerOnly'=>true),
			array('total_pago', 'numerical'),
			array('nombre_archivo, fecha_pago', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, cant_pago, total_pago, nombre_archivo, fecha_pago,fecha_estatus_range, id_estatus', '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(
			'idOrdenPago' => array(self::HAS_MANY, 'OrdenPago', 'id_datos_nomina_orden_pago'),
            'concepto' => array(self::BELONGS_TO, 'Operacion', 'id_concepto'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'cant_pago' => 'Cantantidad pago',
			'total_pago' => 'Monto del pago',
			'nombre_archivo' => 'Nombre del archivo',
			'fecha_pago' => 'Fecha de pago',
            'id_estatus' => 'Estatus',
			'id_concepto' => 'Concepto de la operación',
		);
	}

	/**
	 * 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 ValidarNombreArchivo(){
		if(!$this->hasErrors('nombre_archivo')){
			$model = DatosNominaOrdenPagoSeguimiento::model()->with('idDatosNominaOrdenPago')->find('nombre_archivo=:nombre_archivo AND actual = TRUE AND id_estatus_orden_pago !=4',
																										[':nombre_archivo'=>$this->nombre_archivo]	);
			if($model){
				$this->addError('nombre_archivo','El nombre del archivo ya se encuentra en uso');
			}
		}
	}
	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('cant_pago',$this->cant_pago);
		$criteria->compare('total_pago',$this->total_pago);
		$criteria->compare('LOWER(nombre_archivo)', strtolower($this->nombre_archivo), true);
		$criteria->compare('fecha_pago',$this->fecha_pago,true);

		if(isset($this->id_estatus) && $this->id_estatus !=''){
            $criteria->join = 'INNER JOIN pagos.datos_nomina_orden_pago_seguimiento AS c on c.id_datos_nomina_orden_pago = t.id';
            $criteria->addCondition('c.id_estatus_orden_pago ='.$this->id_estatus.' AND c.actual = true');
        }

        //Filtro para fecha de estatus
            $from = $to = '';
            if (count($this->fecha_estatus_range)>=1) {
                if (isset($this->fecha_estatus_range['from'])) {
                    $from = $this->fecha_estatus_range['from'];
                }
                if (isset($this->fecha_estatus_range['to'])) {
                    $to= $this->fecha_estatus_range['to'];
                }
            }
            if ($from!='' || $to !='') {
                if ($from!='' && $to!='') {
                    $from = date("d-m-Y", strtotime($from));
                    $to = date("d-m-Y", strtotime($to));
                    
                    if(isset($this->id_estatus) && $this->id_estatus !=''){
                        $criteria->addCondition('c.fecha_registro::DATE >=\''.$from.'\' AND c.fecha_registro::DATE <=\''.$to.'\'');
                    }else{
                        $criteria->join = 'INNER JOIN pagos.datos_nomina_orden_pago_seguimiento AS c on c.id_datos_nomina_orden_pago = t.id';
                        $criteria->addCondition('c.actual = true AND c.fecha_registro::DATE >=\''.$from.'\' AND c.fecha_registro::DATE <=\''.$to.'\'');
                    }
                }
                else {
                    if ($from!='') $creation_time = $from;
                    if ($to != '') $creation_time = $to;
                    $creation_time = date("d-m-Y", strtotime($creation_time));

                    if(isset($this->id_estatus) && $this->id_estatus !=''){
                        $criteria->addCondition('c.fecha_registro::DATE =\''.$creation_time.'\'');
                    }else{
                        $criteria->join = 'INNER JOIN pagos.datos_nomina_orden_pago_seguimiento AS c on c.id_datos_nomina_orden_pago = t.id';
                        $criteria->addCondition('c.actual = true AND c.fecha_registro::DATE =\''.$creation_time.'\'');
                    }
                    /*$criteria->addCondition('(SELECT count(*) FROM prestamos.credito_seguimiento WHERE id_credito=t.id '.(($this->id_estatus !='')?'AND id_estatus_credito='.$this->id_estatus:'').' AND '
                            . '(fecha_registro::DATE=\''.$creation_time.'\'))>0');*/
                }
            }

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

	public function afterFind(){
            $model = DatosNominaOrdenPagoSeguimiento::model()->find('id_datos_nomina_orden_pago=:id AND actual =  TRUE',array(':id'=>  $this->id));
            if($model){
                $this->id_estatus = $model->id_estatus_orden_pago;
                $this->fecha_estatus = $model->fecha_registro;


                 if($this->id_estatus==1)$color='#0040FF';
                 else if($this->id_estatus==2)$color='#DF7401';
                 else if($this->id_estatus==3)$color='#088A85';
                 else if($this->id_estatus==4)$color='#8A0808';
                 else if($this->id_estatus==5)$color='#088A08';
                 else $color='#000000';
                 $this->nombre_estatus =  '<span style="color:'.$color.'">'. $model->idEstatusOrdenPago->descripcion.'</span>';



            }

            return parent::afterFind();
        }



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