<?php

/**
 * This is the model class for table "retenciones.solicitud_mp".
 *
 * The followings are the available columns in table 'retenciones.solicitud_mp':
 * @property integer $id
 * @property string $id_asociado
 * @property integer $cedula_solicitante
 * @property string $nombre_solicitante
 * @property string $apellido_solicitante
 * @property string $id_parentesco
 * @property string $fecha_defuncion
 * @property string $id_tipo_carga
 * @property boolean $blnborrado
 *
 * The followings are the available model relations:
 * @property RecaudosMp[] $recaudosMps
 * @property TipoCarga $idTipoCarga
 * @property TxtPrenominaMp[] $txtPrenominaMps
 */
class SolicitudMp extends CActiveRecord
{
    
    public $cedula_asociado;
    public $nombre_asociado;
    public $apellido_asociado;
    public $archivo;
    public $valido;
    public $seleccion;
    public $descripcion_nomina;
    public $fecha_nomina;
    public $fecha_defuncion_range=array();
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'retenciones.solicitud_mp';
	}

	/**
	 * @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_asociado,nombre_asociado,apellido_asociado,fecha_defuncion,cedula_solicitante, nombre_solicitante, apellido_solicitante,id_parentesco', 'required','on'=>'monte_pio'),
			array('fecha_defuncion,cedula_solicitante, nombre_solicitante, apellido_solicitante,id_parentesco', 'required','on'=>'mutuo_auxilio'),
			array('cedula_solicitante,cedula_asociado', 'numerical', 'integerOnly'=>true),
                        array('cedula_asociado','validaCedula','on'=>'monte_pio'),
                        array('descripcion_nomina,fecha_nomina,seleccion','required','on'=>'monte_pio_nm'),
			array('fecha_nomina,descripcion_nomina,cedula_asociado,nombre_asociado,apellido_asociado,id_asociado, nombre_solicitante, apellido_solicitante, id_parentesco, fecha_defuncion, id_tipo_carga,archivo,valido,seleccion', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id,id_estatus,fecha_defuncion_range, id_asociado, cedula_solicitante, nombre_solicitante, apellido_solicitante, id_parentesco, fecha_defuncion, id_tipo_carga, blnborrado,cedula_asociado, nombre_asociado, apellido_asociado', '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(
			'recaudosMps' => array(self::HAS_MANY, 'RecaudosMp', 'id_solicitud'),
                        'idAsociado' => array(self::BELONGS_TO, 'Asociado', 'id_asociado'),
			'idTipoCarga' => array(self::BELONGS_TO, 'TipoCarga', 'id_tipo_carga'),
                        'idParentesco' => array(self::BELONGS_TO, 'Parentesco', 'id_parentesco'),
			'txtPrenominaMps' => array(self::HAS_MANY, 'TxtPrenominaMp', 'id_solicitud'),
                        'idEstatus' => array(self::BELONGS_TO, 'EstatusSolicitudMp', 'id_estatus'),
		);
	}
        
        /**
         * 
         */
        public function validaCedula($attribute){
            if($this->cedula_asociado)
            {
                $asociado=  Asociado::model()->find('cedula=:ci',array(':ci'=>$this->cedula_asociado));
                if($asociado){
                    $model=  self::model()->find('id_asociado=:ida',array(':ida'=>$asociado->idasociado));
                    if($model) $this->addError('cedula_asociado','Ya existe una solicitud de Monte Pío');
                    return 0;
                }
            }
       }
        

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'id_asociado' => 'Id Asociado',
			'cedula_solicitante' => 'Cedula ',
			'nombre_solicitante' => 'Nombre ',
			'apellido_solicitante' => 'Apellido ',
			'id_parentesco' => 'Parentesco',
			'fecha_defuncion' => 'Fecha de Defunción',
			'id_tipo_carga' => 'Tipo de Solicitud',
			'blnborrado' => 'Blnborrado',
			'cedula_asociado' => 'Cédula',
			'nombre_asociado' => 'Nombre',
			'apellido_asociado' => 'Apellido',
			'archivo[]' => '',
			'valido[]' => '',
			'id_estatus' => '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()
	{
		// @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('cedula_solicitante',$this->cedula_solicitante);
		$criteria->compare('nombre_solicitante',$this->nombre_solicitante,true);
		$criteria->compare('apellido_solicitante',$this->apellido_solicitante,true);
		$criteria->compare('id_parentesco',$this->id_parentesco,true);
		$criteria->compare('fecha_defuncion',$this->fecha_defuncion,true);
		$criteria->compare('id_tipo_carga',$this->id_tipo_carga,true);
		$criteria->compare('blnborrado',$this->blnborrado);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
	public function searchMp()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
                $criteria->with='idAsociado';
		$criteria->compare('id',$this->id);
                $criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('"idAsociado".cedula',$this->cedula_asociado);
		$criteria->compare('"idAsociado".nombre',$this->nombre_asociado,true);
		$criteria->compare('"idAsociado".apellidos',$this->apellido_asociado,true);
		$criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('cedula_solicitante',$this->cedula_solicitante);
		$criteria->compare('nombre_solicitante',$this->nombre_solicitante,true);
		$criteria->compare('apellido_solicitante',$this->apellido_solicitante,true);
		$criteria->compare('id_parentesco',$this->id_parentesco,true);
		$criteria->compare('fecha_defuncion',$this->fecha_defuncion,true);
		$criteria->compare('id_tipo_carga',$this->id_tipo_carga);
		$criteria->addCondition('id_tipo_carga=3 OR id_tipo_carga=4');
		$criteria->compare('t.id_estatus',$this->id_estatus);
		$criteria->compare('blnborrado',$this->blnborrado);
                #
                 $from = $to = '';
		if (count($this->fecha_defuncion_range)>=1) {
			if (isset($this->fecha_defuncion_range['from'])) {
				$from = $this->fecha_defuncion_range['from'];
			}
			if (isset($this->fecha_defuncion_range['to'])) {
				$to= $this->fecha_defuncion_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_defuncion',">= $from",false);
				$criteria->compare('fecha_defuncion',"<= $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_defuncion', "$creation_time" ,false);
			}
		}
                #
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
        public function searchPNMp()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
                $criteria->with='idAsociado';
		$criteria->compare('id',$this->id);
                $criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('"idAsociado".cedula',$this->cedula_asociado);
		$criteria->compare('"idAsociado".nombre',$this->nombre_asociado,true);
		$criteria->compare('"idAsociado".apellidos',$this->apellido_asociado,true);
		$criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('cedula_solicitante',$this->cedula_solicitante);
		$criteria->compare('nombre_solicitante',$this->nombre_solicitante,true);
		$criteria->compare('apellido_solicitante',$this->apellido_solicitante,true);
		$criteria->compare('id_parentesco',$this->id_parentesco,true);
		$criteria->compare('fecha_defuncion',$this->fecha_defuncion,true);
		$criteria->compare('id_tipo_carga',3);
		$criteria->compare('t.id_estatus',3);
                $criteria->addCondition('id_tipo_carga=3 AND t.id_estatus=3');
                $criteria->addCondition('id NOT IN (SELECT a.id from retenciones.solicitud_mp AS a
                                            JOIN retenciones.txt_prenomina_mp AS b ON a.id=b.id_solicitud
                                            WHERE b.id_txt_nomina is NOT NULL)');
		$criteria->compare('blnborrado',$this->blnborrado);
                #
                 $from = $to = '';
		if (count($this->fecha_defuncion_range)>=1) {
			if (isset($this->fecha_defuncion_range['from'])) {
				$from = $this->fecha_defuncion_range['from'];
			}
			if (isset($this->fecha_defuncion_range['to'])) {
				$to= $this->fecha_defuncion_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_defuncion',">= $from",false);
				$criteria->compare('fecha_defuncion',"<= $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_defuncion', "$creation_time" ,false);
			}
		}
                #
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        public function searchPNMa()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
                $criteria->with='idAsociado';
		$criteria->compare('id',$this->id);
                $criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('"idAsociado".cedula',$this->cedula_asociado);
		$criteria->compare('"idAsociado".nombre',$this->nombre_asociado,true);
		$criteria->compare('"idAsociado".apellidos',$this->apellido_asociado,true);
		$criteria->compare('id_asociado',$this->id_asociado,true);
		$criteria->compare('cedula_solicitante',$this->cedula_solicitante);
		$criteria->compare('nombre_solicitante',$this->nombre_solicitante,true);
		$criteria->compare('apellido_solicitante',$this->apellido_solicitante,true);
		$criteria->compare('id_parentesco',$this->id_parentesco,true);
		$criteria->compare('fecha_defuncion',$this->fecha_defuncion,true);
                $criteria->addCondition('id_tipo_carga=4 AND t.id_estatus=3');
                $criteria->addCondition('id NOT IN (SELECT a.id from retenciones.solicitud_mp AS a
                                            JOIN retenciones.txt_prenomina_mp AS b ON a.id=b.id_solicitud
                                            WHERE b.id_txt_nomina is NOT NULL)');
		$criteria->compare('blnborrado',$this->blnborrado);
                #
                 $from = $to = '';
		if (count($this->fecha_defuncion_range)>=1) {
			if (isset($this->fecha_defuncion_range['from'])) {
				$from = $this->fecha_defuncion_range['from'];
			}
			if (isset($this->fecha_defuncion_range['to'])) {
				$to= $this->fecha_defuncion_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_defuncion',">= $from",false);
				$criteria->compare('fecha_defuncion',"<= $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_defuncion', "$creation_time" ,false);
			}
		}
                #
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
        
        public function integrarPreNominas($solicitudes){
                  
        $sql='select b.id_asociado,sum(b.monto) as monto from retenciones.txt_prenomina_mp as a
                                            join retenciones.prenomina_mp as b on a.id=b.id_txt_prenomina
                                            join retenciones.solicitud_mp as c on a.id_solicitud=c.id
                                            where a.id_solicitud in ('.$solicitudes.')
                                            group by b.id_asociado';
        $connection=Yii::app()->db;
        $command=$connection->createCommand($sql);
        $rowCount=$command->execute(); // execute the non-query SQL
        $descuentos=$command->queryAll(); // execute a query SQL
        if($descuentos)return $descuentos;
          else return NULL;  
      }
      
        public function totalesPreNominas($solicitudes){
                  
        $sql='select count(DISTINCT b.id_asociado) as aportantes,sum(b.monto) as monto_total from retenciones.txt_prenomina_mp as a
	join retenciones.prenomina_mp as b on a.id=b.id_txt_prenomina
	join retenciones.solicitud_mp as c on a.id_solicitud=c.id
        where a.id_solicitud in ('.$solicitudes.')';
        $connection=Yii::app()->db;
        $command=$connection->createCommand($sql);
        $rowCount=$command->execute(); // execute the non-query SQL
        $totales=$command->queryAll(); // execute a query SQL
        return $totales;  
      }

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