<?php

class ConfPorcentajeController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
			return array(
			'accessControl', // perform access control for CRUD operations
                        'postOnly + delete',
                        'postOnly + haberesSocio',
                        array('CrugeAccessControlFilter')
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','createPatrono'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new ConfPorcentaje('RegistroAsociado');
                $model->fechaActualizacion= array(array('fechaInicio','fechaFin'));
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ConfPorcentaje']))
		{
                   // echo "<pre>";print_r($_POST);exit;
			$model->attributes=$_POST['ConfPorcentaje'];
                        //$model->trabajador= TRUE;
			if($model->validate()){                            
                            $transaction = Yii::app()->db->beginTransaction();
                            try {                            
                                    $model->fecha_actualizar_porcentaje = json_encode($model->fechaActualizacion);
                                    if($model->save()){
                                        $criteria=new CDbCriteria;
                                        $criteria->with='idAsociado';
                                        $criteria->compare('idunidad',$model->idunidad);
                                        $criteria->compare('idtipotrabajador',$model->idtipotrabajador);
//                                        $criteria->compare('trabajador',$model->trabajador);
//                                        $criteria->compare('tipo_aporte',$model->tipo_aporte);
                                        $criteria->compare('"idAsociado".blnborrado',false); 
                
                                        $modelPorcentaje = PorcentajeDescuentoAsociadoPatrono::model()->findAll($criteria);
                                        ///no h
                                        if(count($modelPorcentaje)==0){                                            
                                            $sql = '';
                                            if($model->idunidad !='')
                                                $sql.=' AND idunidad='.$model->idunidad;
                                            if($model->idtipotrabajador !='')
                                                $sql.=' AND idtipotrabajador='.$model->idtipotrabajador;
                                        
                                            foreach (Asociado::model()->findAll('blnborrado= false '.$sql) AS $key =>$value){
                                                $modelPorcentaje = new PorcentajeDescuentoAsociadoPatrono();
                                                $modelPorcentaje ->id_porcentaje_asociado= $model->idporcentaje;
                                                $modelPorcentaje->idasociado = $value->idasociado;
                                                $modelPorcentaje ->actual= true;
                                                $modelPorcentaje->save();
                                            }
                                        }
                                        else{
                                            foreach ($modelPorcentaje as $key => $value) {
                                                if($value->id_porcentaje_asociado==''){
                                                    $value ->id_porcentaje_asociado=  $model->idporcentaje;
                                                    $value->save();
                                                }
                                                else{                                                    
                                                    $value->actual= false;
                                                    $value->save();
                                                    $modelPorcentajeAsociado = new PorcentajeDescuentoAsociadoPatrono();                                                    
                                                    $modelPorcentajeAsociado ->idasociado= $value->idasociado;
                                                    $modelPorcentajeAsociado ->id_porcentaje_asociado= $model->idporcentaje;
                                                    $modelPorcentajeAsociado ->id_porcentaje_patrono= $value->id_porcentaje_patrono;
                                                    $modelPorcentajeAsociado ->actual= true;
                                                    $modelPorcentajeAsociado->save();
                                                }                                                
                                            }
                                        }
                                        
                                        $transaction->commit();
                                        //RetiroParcialController::EnviarCorreo(($model->idAsociado->nombre.' '.$model->idAsociado->apellidos), $model->idAsociado->correoelectronico, $text_correo, $asunto);
                                        // CorreoElectronico::enviarCorreo(array('nombre'=>$model->trabajador->nombre.' '.$model->trabajador->apellidos,
                                        //                                       'correo'=>$model->trabajador->correoelectronico,
                                        //                                       'asunto'=>$asunto,
                                        //                                       'mensaje'=>$text_correo));


                                        $this->redirect(array('admin'));
                                    }

                                }
                                catch (Exception $e){
                                        throw new CHttpException(400,$e->getMessage());
                                        $transaction->rollBack();
                                }
                        }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	public function actionCreatePatrono()
	{
		$model=new ConfPorcentaje('RegistroPatrono');
                $model->fechaActualizacion= array(array('fechaInicio','fechaFin'));
                $model->trabajador= false;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ConfPorcentaje']))
		{
 			$model->attributes=$_POST['ConfPorcentaje'];
                        $model->trabajador= false;
                        //echo "<pre>";print_r($_POST);exit;
			if($model->validate()){                            
                            $transaction = Yii::app()->db->beginTransaction();
                            try {                            
                                    $model->fecha_actualizar_porcentaje = json_encode($model->fechaActualizacion);
                                    if($model->save()){
                                        $criteria=new CDbCriteria;
                                        $criteria->with='idAsociado';
                                        $criteria->compare('idunidad',$model->idunidad);
                                        $criteria->compare('idtipotrabajador',$model->idtipotrabajador);
//                                        $criteria->compare('trabajador',$model->trabajador);
//                                        $criteria->compare('tipo_aporte',$model->tipo_aporte);
                                        $criteria->compare('"idAsociado".blnborrado',false); 
                
                                        $modelPorcentaje = PorcentajeDescuentoAsociadoPatrono::model()->findAll($criteria);
                                        ///no h
                                        
                                        if(count($modelPorcentaje)==0){                                            
                                            $sql = '';
                                            if($model->idunidad !='')
                                                $sql.=' AND idunidad='.$model->idunidad;
                                            if($model->idtipotrabajador !='')
                                                $sql.=' AND idtipotrabajador='.$model->idtipotrabajador;
                                        
                                            foreach (Asociado::model()->findAll('blnborrado= false '.$sql) AS $key =>$value){
                                                $modelPorcentaje = new PorcentajeDescuentoAsociadoPatrono();
                                                $modelPorcentaje ->id_porcentaje_patrono= $model->idporcentaje;
                                                $modelPorcentaje ->idasociado= $value->idasociado;
                                                $modelPorcentaje ->actual= true;
                                                $modelPorcentaje->save();
                                            }
                                        }
                                        else{
                                            foreach ($modelPorcentaje as $key => $value) {
                                                if($value->id_porcentaje_patrono==''){
                                                    $value ->id_porcentaje_patrono= $model->idporcentaje;
                                                    $value->save();
                                                }
                                                else{ 
                                                    $id_aporte_patrono= $model->idporcentaje;
                                                    $value->actual= false;
                                                    $value->save();
                                                    
                                                    $modelPorcentajePatrono = new PorcentajeDescuentoAsociadoPatrono();
                                                    $modelPorcentajePatrono ->idasociado= $value->idasociado;
                                                    $modelPorcentajePatrono ->id_porcentaje_asociado= $value->id_porcentaje_patrono;
                                                    $modelPorcentajePatrono ->id_porcentaje_patrono= ($model->tipo_aporte==2)?$value->id_porcentaje_asociado:$model->idporcentaje ;
                                                    $modelPorcentajePatrono ->actual= true;
                                                    $modelPorcentajePatrono->save();
                                                }
                                                
                                            }
                                        }
                                        
                                        $transaction->commit();
                                        //RetiroParcialController::EnviarCorreo(($model->idAsociado->nombre.' '.$model->idAsociado->apellidos), $model->idAsociado->correoelectronico, $text_correo, $asunto);
                                        // CorreoElectronico::enviarCorreo(array('nombre'=>$model->trabajador->nombre.' '.$model->trabajador->apellidos,
                                        //                                       'correo'=>$model->trabajador->correoelectronico,
                                        //                                       'asunto'=>$asunto,
                                        //                                       'mensaje'=>$text_correo));


                                        $this->redirect(array('admin'));
                                    }

                                }
                                catch (Exception $e){
                                        throw new CHttpException(400,$e->getMessage());
                                        $transaction->rollBack();
                                }
                        }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ConfPorcentaje']))
		{
			$model->attributes=$_POST['ConfPorcentaje'];
			if($model->validate()){
                            $model->fecha_actualizar_porcentaje = json_encode($model->fechaActualizacion);
                            $model->save();
				$this->redirect(array('admin'));
                        }
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('ConfPorcentaje');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new ConfPorcentaje('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ConfPorcentaje']))
			$model->attributes=$_GET['ConfPorcentaje'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=ConfPorcentaje::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='conf-porcentaje-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
}
