<?php

/**
 * This is the model class for table "retenciones.aporte_ordinario_diferido".
 *
 * The followings are the available columns in table 'retenciones.aporte_ordinario_diferido':
 * @property integer $id
 * @property string $id_txt
 * @property integer $cedula
 * @property integer $unidad
 * @property string $sueldo
 * @property string $tipo_nomina
 * @property string $p_asociado
 * @property string $aporte_asociado
 * @property string $p_patrono
 * @property string $aporte_patrono
 * @property string $observaciones
 * @property boolean $blnborrado
 *
 * The followings are the available model relations:
 * @property DatosTxtIntegrado $idTxt
 */
class AporteOrdinarioDiferido extends CActiveRecord
{
	public $ap_pat_diferido, $ap_aso_diferido;
    public $total_aporte;
    public $aporte_pendiente;

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

	/**
	 * @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('cedula, unidad', 'numerical', 'integerOnly'=>true),
			array('sueldo, aporte_asociado', 'length', 'max'=>20),
			array('tipo_nomina', 'length', 'max'=>3),
			array('p_asociado, p_patrono', 'length', 'max'=>5),

			array('id_estatus_aod', 'required', 'on'=>'asociado_cmao'),
			array('id_txt, aporte_patrono, observaciones, blnborrado,id_estatus_aod', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, id_txt, cedula, unidad, sueldo, tipo_nomina, p_asociado, aporte_asociado, p_patrono, aporte_patrono, observaciones, blnborrado', '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'),
            'idEstatusAod' => array(self::BELONGS_TO, 'EstatusAporteOrdinarioDiferido', 'id_estatus_aod'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'id_txt' => 'Id Txt',
			'cedula' => 'Cédula',
			'unidad' => 'Unidad',
			'sueldo' => 'Sueldo',
			'tipo_nomina' => 'Tipo de Nómina',
			'p_asociado' => '% Asociado',
			'aporte_asociado' => 'Aporte Asociado',
			'p_patrono' => '% Patrono',
			'aporte_patrono' => 'Aporte Patrono',
			'observaciones' => 'Observaciones',
			'blnborrado' => 'Blnborrado',
            'id_estatus_aod' => 'Estatus',
		);
	}

	/**
	 * 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($id)
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
        $criteria->select = 't.*, coalesce((har.reembolso_no_recibido_asociado + har.reembolso_no_recibido_patrono), 0) as aporte_pendiente';
        $criteria->alias = 't';
        $criteria->join = 'LEFT JOIN retenciones.historial_aporte_reembolso har on t.id=har.id_aporte and har.actual IS TRUE';
		$criteria->compare('t.id',$this->id);
		$criteria->compare('t.id_txt',$id);
		$criteria->compare('t.cedula::TEXT',$this->cedula,true);
		$criteria->compare('t.unidad',$this->unidad);
		$criteria->compare('t.sueldo::TEXT',$this->sueldo,true);
		$criteria->compare('t.tipo_nomina',$this->tipo_nomina,true);
		$criteria->compare('t.p_asociado::TEXT',$this->p_asociado,true);
		$criteria->compare('t.aporte_asociado::TEXT',$this->aporte_asociado,true);
		$criteria->compare('t.p_patrono::TEXT',$this->p_patrono,true);
		$criteria->compare('t.aporte_patrono::TEXT',$this->aporte_patrono,true);
		$criteria->compare('t.observaciones',$this->observaciones,true);
		$criteria->compare('t.id_estatus_aod',$this->id_estatus_aod);
		$criteria->addCondition('t.blnborrado=FALSE');
		$criteria->order = 'id_estatus_aod asc';

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

        /**
         * Obtener area del aporte
         * @return string
         */
        public function getArea()
        {
            if($this->unidad)
            {
                $modelArea=  Unidad::model()->findByPk($this->unidad);
                if($modelArea) return $modelArea->descripcion;
            }
          return 'Area Desconocida';
        }

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

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

            }
		return parent::beforeSave();
	}

    public function totalAportes()
    {
        return $this->aporte_patrono + $this->aporte_asociado;
    }

	/**
	 * 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 AporteOrdinarioDiferido 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 ao.cedula,
                a.descripcion,
                ao.sueldo,
                ao.aporte_patrono,
                ao.aporte_asociado,
                (ao.aporte_asociado + ao.aporte_patrono) as total_aporte,
                coalesce((har.reembolso_no_recibido_asociado + har.reembolso_no_recibido_patrono), 0) as aporte_pendiente,
                ao.fecha_registro,
                eaod.nombre_estatus
            FROM retenciones.aporte_ordinario_diferido ao
            INNER JOIN public.unidad a ON a.idunidad=ao.unidad
            INNER JOIN retenciones.estatus_aporte_ordinario_diferido eaod ON ao.id_estatus_aod=eaod.id
            LEFT JOIN retenciones.historial_aporte_reembolso har on ao.id=har.id_aporte and har.actual IS TRUE
            WHERE ao.id_txt=:id AND ao.blnborrado IS FALSE;
        ')->bindValue('id', $id)->queryAll();
    }

    public static function detalle($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.historial_aportes_diferidos had
            INNER JOIN retenciones.aporte_ordinario ao ON had.id_aporte=ao.id
            INNER JOIN public.asociado a ON a.idasociado=ao.id_asociado
            WHERE had.id_txt=:id and had.actual=true;
        ')->bindValue('id', $id)->queryAll();
    }
}
