<?php

/**
 * This is the model class for table "retenciones.aporte_ordinario".
 *
 * The followings are the available columns in table 'retenciones.aporte_ordinario':
 * @property integer $id
 * @property string $id_asociado
 * @property string $id_txt
 * @property string $aporte_patrono
 * @property string $aporte_asociado
 * @property string $sueldo_base
 * @property string $p_patrono
 * @property string $p_asociado
 * @property string $id_tipo_nomina
 * @property string $fecha_aporte
 * @property string $fecha_registro
 * @property string $id_unidad
 * @property string $id_usuario
 * @property boolean $blnborrado
 * @property boolean $aprobado
 * @property string $referencia
 * @property string $fecha_referencia
 *
 * The followings are the available model relations:
 * @property DatosTxtIntegrado $idTxt
 * @property Unidad $idUnidad
 * @property CrugeUser $idUsuario
 * @property TipoNomina $idTipoNomina
 * @property Asociado $idAsociado
 */
class AporteOrdinario extends CActiveRecord
{
    public $cedula;
    public $nombre;
    public $apellido;
    public $fecha_aporte_range=array();
    public $total_aporte, $aporte_pagado, $aporte_x_pagar, $estatus, $x_pagar_patrono, $x_pagar_socio;
    public $nombre_completo;
    public $aporte_total;
    public $deuda_actual_patrono;
    public $deuda_actual_socio;

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

	/**
	 * @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('aporte_patrono, aporte_asociado, sueldo_base, p_asociado', 'length', 'max'=>20),
			array('p_patrono', 'length', 'max'=>5),
			array('id_asociado, id_txt, id_tipo_nomina, fecha_aporte, fecha_registro, id_unidad, id_usuario, blnborrado', 'safe'),
			#####################################################################################################
                        array('cedula, id_unidad,sueldo_base,id_tipo_nomina,aporte_patrono,aporte_asociado', 'required','on'=>'carga_masiva'),//p_patrono,p_asociado
                        array('cedula,id_unidad', 'numerical','integerOnly'=>true,'on'=>'carga_masiva'),
                        array('id_tipo_nomina ', 'match',
					'pattern' => '/^(M|Q|D|V|R)$/',
					'message' => 'Formato de tipo de nomina Invalido: acepta M,Q,D,V o R',
					'on'=>'carga_masiva',
			),
                        /*array('p_asociado,p_patrono',
                                'numerical',
                                'min'=>0.00,
                                'max'=>100.00,
                                'tooSmall'=>'El porcentaje no puede ser menor que cero (0)',
                                'tooBig'=>'El porcentaje no puede ser mayor que cien (100)',
                                'on'=>'carga_masiva'),*/
                         array('aporte_asociado,aporte_patrono,sueldo_base', 'match',
					'pattern' => '/^(\d)*(\,\d{0,20})?$/',
					'message' => 'El {attribute} debe tener el siguiente formato 1000,00',
					'on'=>'carga_masiva',
			),
                         array( 'cedula','validaAsociado','on'=>(self::getConf('NO DEFINIDOS')=='SI')?'cm_guardado':'carga_masiva'),
                         //array( 'id_unidad','validaUnidad','on'=>(self::getConf('diferidos')=='si')?'cm_guardado':'carga_masiva'),
                         array( 'id_unidad','validaUnidad','on'=>('carga_masiva')),
                         #Guardado
                         array( 'id_tipo_nomina', 'numerical','integerOnly'=>true,'on'=>'cm_guardado'),


                        ######################################################################################################




                        // 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, aporte_patrono, aporte_asociado, sueldo_base, p_patrono, p_asociado, id_tipo_nomina, fecha_aporte, fecha_registro, id_unidad, id_usuario, blnborrado, total_aporte, aporte_x_cobrar, deuda_actual_socio, deuda_actual_patrono', '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'),
			'idUnidad' => array(self::BELONGS_TO, 'Unidad', 'id_unidad'),
			'idUsuario' => array(self::BELONGS_TO, 'CrugeUser', 'id_usuario'),
			'idTipoNomina' => array(self::BELONGS_TO, 'TipoNomina', 'id_tipo_nomina'),
            'idAsociado' => array(self::BELONGS_TO, 'Asociado', 'id_asociado'),
            'idEstatusAporte' => array(self::BELONGS_TO, 'EstatusAporte', 'id_estatus_aporte'),
            'historial' => array(self::HAS_ONE, 'HistorialAportesDiferidos', 'id_aporte', 'condition' => 'actual IS TRUE'),

		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'id_asociado' => 'Id Asociado',
			'id_txt' => 'Id Txt',
			'aporte_patrono' => 'Aporte patrono',
			'aporte_asociado' => 'Aporte asociado',
			'sueldo_base' => 'Sueldo Base',
			'p_patrono' => '% Patrono',
			'p_asociado' => '% Asociado',
			'id_tipo_nomina' => 'Tipo de Nómina',
			'fecha_aporte' => 'Fecha aporte',
			'fecha_registro' => 'Fecha Registro',
			'id_unidad' => 'Id Unidad',
			'id_usuario' => 'Id Usuario',
			'blnborrado' => 'Blnborrado',
                        'aprobado' => 'Aprobado',
			'referencia' => 'Referencia',
			'fecha_referencia' => 'Fecha de Referencia',
			'total_aporte'=> 'Aporte total',
			'aporte_pagado'=>'Aporte pagado',
            'aporte_x_pagar'=>'Aporte pendiente',
            'deuda_actual_patrono'=>'Deuda patrono',
			'deuda_actual_socio'=>'Deuda asociado',
		);
	}

	/**
	 * 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('aporte_patrono',$this->aporte_patrono,true);
		$criteria->compare('aporte_asociado',$this->aporte_asociado,true);
		$criteria->compare('sueldo_base',$this->sueldo_base,true);
		$criteria->compare('p_patrono',$this->p_patrono,true);
		$criteria->compare('p_asociado',$this->p_asociado,true);
		$criteria->compare('id_tipo_nomina',$this->id_tipo_nomina,true);
		$criteria->compare('fecha_aporte',$this->fecha_aporte,true);
		$criteria->compare('fecha_registro',$this->fecha_registro,true);
		$criteria->compare('id_unidad',$this->id_unidad,true);
		$criteria->compare('id_usuario',$this->id_usuario,true);
		$criteria->compare('blnborrado',$this->blnborrado);

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

    public function criteriaAporteOrdinario($id)
    {
        if ($id == '') {
            $id = 0;
        }
        if (isset($_GET['cedula'])) {
            if (is_numeric($_GET['cedula'])) {
                $id = 0;
                $model = Asociado::model()->find('cedula=:cedula AND blnborrado= FALSE AND id_estatus in(1,2,4) ORDER BY idasociado desc', [':cedula' => $_GET['cedula']]);
                if ($model) {
                    $id = $model->idasociado;
                }
            } else {
                $id = 0;
            }
        }

        $criteria = new CDbCriteria();
        $criteria->compare('id', $this->id);
        $criteria->compare('id_asociado', $id);
        $criteria->compare('id_txt', $this->id_txt, true);
        $criteria->compare('aporte_patrono', $this->aporte_patrono, true);
        $criteria->compare('aporte_asociado', $this->aporte_asociado, true);
        $criteria->compare('sueldo_base', $this->sueldo_base, true);
        $criteria->compare('p_patrono', $this->p_patrono, true);
        $criteria->compare('p_asociado', $this->p_asociado, true);
        $criteria->compare('id_tipo_nomina', $this->id_tipo_nomina, true);
        $criteria->compare('t.fecha_aporte', $this->fecha_aporte, true);
        $criteria->compare('t.fecha_registro', $this->fecha_registro, true);
        $criteria->compare('t.id_unidad', $this->id_unidad, true);
        $criteria->compare('t.id_usuario', $this->id_usuario, true);
        $criteria->compare('t.blnborrado', false);
        $criteria->compare('t.aprobado', true);
        $criteria->order = 't.fecha_aporte desc';
        $criteria->join = 'JOIN retenciones.estatus_txt_integrado as a on a.id_datos_txt_integrado=t.id_txt';
        $criteria->addCondition('a.actual =true AND a.id_estatus_txt in (3,5,6)');

        return $criteria;
    }

    public function searchAporteAsociado($id)
    {
        $criteria = $this->criteriaAporteOrdinario($id);

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

    public function searchAporteOrdinarioFichaLiquidacion($id, $params)
    {
        $criteria = $this->criteriaAporteOrdinario($id);
        $criteria->with = ['idTipoNomina', 'idTxt'];

        return new CActiveDataProvider($this, [
            'criteria' => $criteria,
            'pagination' => [
                'pageSize' => 10,
                'params'  => $params,
            ],
        ]);
    }

    public function aporteOrdinarioFichaLiquidacion($id)
    {
        $criteria = $this->criteriaAporteOrdinario($id);
        $criteria->with = ['idTipoNomina', 'idTxt'];

        $datos = self::model()->findAll($criteria);

        return (new Warp($datos))->map(function ($aporte) {
            return [
                'id' => $aporte->id,
                'nombre_archivo' => $aporte->idTxt ? $aporte->idTxt->nombre_archivo : '',
                'fecha_aporte' => $aporte->fecha_aporte,
                'sueldo_base' => $aporte->sueldo_base,
                'aporte_patrono' => $aporte->aporte_patrono,
                'aporte_asociado' => $aporte->aporte_asociado,
                'total_aporte' => $aporte->total_aporte,
                'aporte_pagado' => $aporte->aporte_pagado,
                'aporte_x_pagar' => $aporte->aporte_x_pagar,
                'tipo_nomina' => $aporte->idTipoNomina ? $aporte->idTipoNomina->nombre_nomina : '',
                'estatus_aporte' => $aporte->idTxt ? $aporte->idTxt->getEstatus() : '',
            ];
        });
    }

       	/**
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function searchV($id)
    {
        $criteria = new CDbCriteria();
        $criteria->alias = 't';
        $criteria->join = 'inner join asociado a on a.idasociado=t.id_asociado';
        $criteria->compare('t.id_txt', $id);
        $criteria->compare('"a".cedula::TEXT', $this->cedula, true);
        $criteria->compare('lower(concat(a.nombre, \' \', (a.apellidos)))', $this->nombre_completo, true);
        $criteria->compare('aporte_patrono::TEXT', $this->aporte_patrono, true);
        $criteria->compare('aporte_asociado::TEXT', $this->aporte_asociado, true);
        $criteria->compare('id_tipo_nomina', $this->id_tipo_nomina, true);
        $criteria->compare('fecha_aporte', $this->fecha_aporte, true);
        $criteria->compare('deuda_actual_socio::varchar', $this->deuda_actual_socio, true);
        $criteria->compare('deuda_actual_patrono::varchar', $this->deuda_actual_patrono, 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_usuario', $this->id_usuario, true);
        $criteria->compare('blnborrado', $this->blnborrado);
        $criteria->addCondition('id_estatus_aporte !=4 OR  id_estatus_aporte IS NULL and t.blnborrado IS FALSE');
        $criteria->order = 'lower(concat(a.nombre, \' \', (a.apellidos))) ASC';

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

    public function searchV2($id)
    {
        $criteria = new CDbCriteria();
        $criteria->with = 'historial';
        $criteria->alias = 't';
        $criteria->join = 'inner join asociado a on a.idasociado=t.id_asociado';
        $criteria->compare('t.id_txt', $id);
        $criteria->compare('"a".cedula::TEXT', $this->cedula, true);
        $criteria->compare('lower(concat(a.nombre, \' \', (a.apellidos)))', $this->nombre_completo, true);
        $criteria->compare('aporte_patrono::TEXT', $this->aporte_patrono, true);
        $criteria->compare('aporte_asociado::TEXT', $this->aporte_asociado, true);
        $criteria->compare('id_tipo_nomina', $this->id_tipo_nomina, true);
        $criteria->compare('fecha_aporte', $this->fecha_aporte, true);
        $criteria->compare('deuda_actual_socio::varchar', $this->deuda_actual_socio, true);
        $criteria->compare('deuda_actual_patrono::varchar', $this->deuda_actual_patrono, 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_usuario', $this->id_usuario, true);
        $criteria->compare('blnborrado', $this->blnborrado);
        $criteria->addCondition('id_estatus_aporte !=4 OR  id_estatus_aporte IS NULL');
        $criteria->order = 'lower(concat(a.nombre, \' \', (a.apellidos))) ASC';

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

	public function searchF($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_patrono::TEXT',$this->aporte_patrono,true);
		$criteria->compare('aporte_asociado::TEXT',$this->aporte_asociado,true);
		$criteria->compare('sueldo_base::TEXT',$this->sueldo_base,true);
		$criteria->compare('p_patrono::TEXT',$this->p_patrono,true);
		$criteria->compare('p_asociado::TEXT',$this->p_asociado,true);
		$criteria->compare('id_tipo_nomina',$this->id_tipo_nomina,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_usuario',$this->id_usuario,true);
		$criteria->compare('blnborrado',$this->blnborrado);
		$criteria->compare('id_estatus_aporte',4);

		$_SESSION['datos_filtrados'] = new CActiveDataProvider($this, array(
                      'criteria'=>$criteria,
                      'pagination'=>false,
              ));
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
                        'pagination'=>array(
                            'pageSize'=>20,
                            ),
		));
	}

        /**
         * Consulta un valor especifico en la configuracion de retenciones
         * @param type $att
         * @return type
         */
        public function getConf($att)
        {
           $conf=ConfRetenciones::model()->find('atributo=:att',array(':att'=>$att));
           if($conf)return $conf->valor;
           else return NULL;
        }

        /**
         * validaAsociado valida que la cedula esta registrada en la caja de ahorro
         * @param type $attributes
         */
        public function validaAsociado($attributes)
        {
           if($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');
                }
               }
        }

        public function aportePatrono(){
            $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_patrono;
            return 0;
        }

        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_asociado;
            return 0;
        }

       /**
        * validaUnidad valida que el ID de la unidad exista
        * @param type $attributes
        */

        public function validaUnidad($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');
                }
               }
        }

    public function afterFind()
    {
        $this->total_aporte = number_format(($this->aporte_asociado + $this->aporte_patrono), 2, ',', '.');

        $historial_diferidos = HistorialAportesDiferidos::model()->find('id_aporte=:aporte AND actual=true', array(':aporte' => $this->id));

        if (!empty($historial_diferidos)) {
            $this->aporte_pagado = number_format(
                ($this->aporte_asociado - $historial_diferidos->deuda_actual_socio) + ($this->aporte_patrono - $historial_diferidos->deuda_actual_patrono),
                2,
                ',',
                '.'
            );
            $this->aporte_x_pagar = number_format(
                ($historial_diferidos->deuda_actual_socio + $historial_diferidos->deuda_actual_patrono),
                2,
                ',',
                '.'
            );

            $this->x_pagar_socio = $historial_diferidos->deuda_actual_socio;
            $this->x_pagar_patrono = $historial_diferidos->deuda_actual_patrono;
        } else {
            $this->aporte_pagado = number_format(($this->aporte_asociado + $this->aporte_patrono), 2, ',', '.');
            $this->aporte_x_pagar = number_format(0, 2, ',', '.');
        }

        return parent::afterFind();
    }

        /**
         *  BeforeSafe
         *  Se ejecuta antes de guardar
         */
        protected function beforeSave() {

            #Monto en Bs
            if($this->scenario=='carga_masiva'){
                $this->sueldo_base=str_replace(',', '.', $this->sueldo_base);
                $this->aporte_asociado=str_replace(',', '.', $this->aporte_asociado);
                $this->aporte_patrono=str_replace(',', '.', $this->aporte_patrono);

            }

            if($this->aporte_asociado==''){
                $this->aporte_asociado=NULL;
            }
            if($this->sueldo_base==''){
                $this->sueldo_base=NULL;
            }
            if($this->p_patrono==''){
                $this->p_patrono=NULL;
            }
            if($this->p_asociado==''){
                $this->p_asociado=NULL;
            }


		return parent::beforeSave();
	}

    public function getNombreCompleto()
    {
        $asociado = $this->idAsociado;

        return $asociado->nombre.' '.$asociado->apellidos;
    }

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

    public static function getReporte($id)
    {
        return Yii::app()->getDb()->createCommand('
            SELECT
                a.cedula,
                concat(a.nombre, \' \', a.apellidos) nombres,
                ao.aporte_patrono,
                ao.aporte_asociado,
                (ao.aporte_patrono + ao.aporte_asociado) as aporte_total,
                CASE
                    WHEN ao.id_estatus_aporte=3 and coalesce(had.id::boolean, false) is false
                        THEN ao.aporte_patrono
                    WHEN coalesce(had.id::boolean, false) is true
                        THEN ao.aporte_patrono - had.deuda_actual_patrono
                    else
                        0
                END AS aporte_pagado_patrono,
                CASE
                    WHEN ao.id_estatus_aporte=3 and coalesce(had.id::boolean, false) is false
                        THEN ao.aporte_asociado
                    WHEN coalesce(had.id::boolean, false) is true
                        THEN ao.aporte_asociado - had.deuda_actual_socio
                    else
                        0
                END AS aporte_pagado_asociado,
                CASE
                    WHEN coalesce(had.id::boolean, false) is true
                        THEN had.deuda_actual_patrono
                    ELSE
                    0
                END AS aporte_por_pagar_patrono,
                CASE
                    WHEN coalesce(had.id::boolean, false) is true
                        THEN had.deuda_actual_socio
                    ELSE
                    0
                END AS aporte_por_pagar_asociado,
                ao.fecha_aporte
            FROM retenciones.aporte_ordinario ao
            INNER JOIN public.asociado a ON a.idasociado=ao.id_asociado
            LEFT JOIN retenciones.historial_aportes_diferidos had on had.id_aporte=ao.id and actual is true and ao.id_txt=had.id_txt
            WHERE ao.id_txt=:id
            ORDER BY concat(a.nombre, \' \', a.apellidos) ASC;
        ')->bindValue('id', $id)->queryAll();
    }

    public static function aportesFaltantes($id)
    {
        return Yii::app()->getDb()->createCommand('
            SELECT
                a.cedula,
                concat(a.nombre, \' \', a.apellidos) nombres,
                had.deuda_actual_patrono,
                had.deuda_actual_socio,
                CASE WHEN coalesce(had.id::boolean, false) is true
                    THEN (had.deuda_actual_socio + had.deuda_actual_patrono)
                ELSE
                    0
                END AS aporte_por_pagar,
                ao.fecha_aporte
            FROM retenciones.aporte_ordinario ao
            INNER JOIN public.asociado a ON a.idasociado=ao.id_asociado
            LEFT JOIN retenciones.historial_aportes_diferidos had on had.id_aporte=ao.id and actual is true and ao.id_txt=had.id_txt
            WHERE ao.id_txt=:id
            ORDER BY concat(a.nombre, \' \', a.apellidos) ASC;
        ')->bindValue('id', $id)->queryAll();
    }

    public static function pagar($id)
    {
        return self::model()->updateAll(array(
            'pagado' => true,
            'id_estatus_aporte' => 3,
        ), 'id_txt=:idtxt AND blnborrado IS FALSE AND metodo_pago IS FALSE', array(':idtxt' => $id));
    }
}
