<?php

/**
 * This is the model class for table "retenciones.historial_diferidos_totalizados".
 *
 * The followings are the available columns in table 'retenciones.historial_diferidos_totalizados':
 * @property integer $id
 * @property string $id_txt
 * @property integer $tipo_aporte
 * @property string $monto_inicial
 * @property string $monto_pagado
 * @property string $monto_restante
 * @property string $fecha_transaccion
 * @property string $fecha_registro
 * @property boolean $actual
 * @property integer $nro_pago
 * @property integer $id_proceso_pago
 *
 * The followings are the available model relations:
 * @property DatosTxtIntegrado $idTxt
 * @property TipoAporteDiferido $tipoAporte
 */
class HistorialDiferidosTotalizados extends CActiveRecord
{
	public $pay_details = array('banco', 'cuenta', 'referencia', 'observacion'), $total_monto_archivo, $montos_iniciales, $total_pagado, $result;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'retenciones.historial_diferidos_totalizados';
	}

	/**
	 * @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_txt', 'required'),
			array('tipo_aporte, nro_pago', 'numerical', 'integerOnly'=>true),
			array('monto_inicial, monto_pagado, monto_restante', 'length', 'max'=>20),
			array('fecha_transaccion, fecha_registro, actual', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, id_txt, tipo_aporte, monto_inicial, monto_pagado, monto_restante, fecha_transaccion, fecha_registro, actual, nro_pago, pay_details["banco"], pay_details["cuenta"], pay_details["referencia"], pay_details["observacion"], total_monto_archivo', '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(
			'idTxt' => array(self::BELONGS_TO, 'DatosTxtIntegrado', 'id_txt'),
			'tipoAporte' => array(self::BELONGS_TO, 'TipoAporteDiferido', 'tipo_aporte'),
			'procesoPago' => array(self::BELONGS_TO, 'ProcesoPago', 'id_proceso_pago'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'id_txt' => 'Id Txt',
			'tipo_aporte' => 'Tipo de aporte',
			'monto_inicial' => 'Monto aportantes activos',
			'monto_pagado' => 'Monto pagado',
			'monto_restante' => 'Monto restante',
			'fecha_transaccion' => 'Fecha de transacción',
			'fecha_registro' => 'Fecha Registro',
			'actual' => 'Actual',
			'nro_pago' => 'N°',
			'id_proceso_pago' => 'Código del pago',
			'pay_details["banco"]' => 'Banco',
			'pay_details["cuenta"]' => 'Cuenta',
			'pay_details["referencia"]' => 'Referencia',
			'pay_details["observacion"]' => 'Observacion',
			'total_monto_archivo' => 'Monto según archivo',
		);
	}

	/**
	 * 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_txt',$this->id_txt,true);
		$criteria->compare('tipo_aporte',$this->tipo_aporte);
		$criteria->compare('monto_inicial',$this->monto_inicial,true);
		$criteria->compare('monto_pagado',$this->monto_pagado,true);
		$criteria->compare('monto_restante',$this->monto_restante,true);
		$criteria->compare('fecha_transaccion',$this->fecha_transaccion,true);
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('actual',$this->actual);
		$criteria->compare('nro_pago',$this->nro_pago);
		$criteria->compare('id_proceso_pago',$this->id_proceso_pago);

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

	public function searchDiferidosArchivo($id)
	{
		$criteria=new CDbCriteria;
		$criteria->compare('id',$this->id);
		$criteria->compare('id_txt',$id);
		$criteria->compare('tipo_aporte',$this->tipo_aporte);
		$criteria->compare('monto_inicial',$this->monto_inicial);
		$criteria->compare('monto_pagado',$this->monto_pagado);
		$criteria->compare('monto_restante',$this->monto_restante);
		$criteria->compare('fecha_transaccion',$this->fecha_transaccion);
		$criteria->compare('fecha_registro',$this->fecha_registro);
		$criteria->compare('actual',$this->actual);
		$criteria->compare('nro_pago',$this->nro_pago);
		$criteria->compare('id_proceso_pago',$this->id_proceso_pago);
		$criteria->order = 't.nro_pago asc';

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

	/*public function afterFind(){

		$this->montos_iniciales = DatosTxtIntegrado::model()->datosAporte($this->id_txt);

		echo "<pre>";print_r($this->montos_iniciales);exit;
	}*/

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

    public static function eliminarAnteriores($id)
    {
        return self::model()->updateAll(array('actual' => false), 'id_txt=:id AND actual=true', array(':id' => $id));
    }

    public static function detalle($id)
    {
        return Yii::app()->getDb()->createCommand('
            SELECT dti.total_aportes,
                   hdt.monto_inicial,
                   hdt.monto_pagado,
                   hdt.monto_restante,
                   pb.banco,
                   pb.num_cuenta AS numero_cuenta,
                   pp.referencia,
                   hdt.fecha_transaccion
            FROM retenciones.historial_diferidos_totalizados hdt
            INNER JOIN retenciones.datos_txt_integrado dti ON dti.id=hdt.id_txt
            INNER JOIN contable.proceso_pago pp ON pp.id=hdt.id_proceso_pago
            INNER JOIN configuracion.param_bancos pb ON pp.id_banco=pb.id
            WHERE hdt.id_txt=:id
        ')->bindValue('id', $id)->queryAll();
    }

    public static function crear($nomina, $totalDeuda, $restante)
    {
        self::eliminarAnteriores($nomina->id);
        $modelHDT = new HistorialDiferidosTotalizados;
        $modelHDT->id_txt = $nomina->id;
        $modelHDT->tipo_aporte = 1;
        $modelHDT->monto_inicial = $totalDeuda;
        $modelHDT->monto_pagado = $nomina->getMontoPagado();
        $modelHDT->monto_restante = $restante;
        $modelHDT->fecha_transaccion = $nomina->getFechaOperacion();
        $modelHDT->nro_pago = 1;
        $modelHDT->id_proceso_pago = $nomina->getIdComprobantePago();
        if (! $modelHDT->validate()) {
            throw new Exception('Error al registrar historial diferido totalizado.');
        }
        return $modelHDT->save();
    }
}
