<?php

class ReintegroController 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', // we only allow deletion via POST request
                        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','admin','CargarCuotas','aprobarReintegro','denegarReintegro'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('delete'),
				'users'=>array('admin'),
			),
			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),
		));*/
		return array(array('CrugeAccessControlFilter'));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Reintegro;
                $user=Yii::app()->user->id;
        	$sql = "select * from cruge_user where iduser= $user and state= 1";
		$resp = Yii::app()->db->createCommand($sql)->queryAll();
        	$cedula= $resp[0]['cedula'];
        	
                $dato_aportante= Asociado::model()->findByAttributes(array('cedula'=>$cedula));
                
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Reintegro']))
		{
		    
                     $error=false;  
                      if($_POST['idcredito'] == '')
                      {
                          Yii::app()->user->setFlash('error', "<b>Seleccione el Tipo de Crédito.</b>");
                          $error=true;
                      }
                      
                      if(!(isset($_POST['selec'])))
                      {
                          Yii::app()->user->setFlash('error', "<b>Debe de Seleccionar una cuota para su reintegro.</b>");
                          $error=true;
                      }
                      if($_POST['mvm_cuota'] == '')
                      {
                          Yii::app()->user->setFlash('error', "<b>Seleccione el tipo de movimiento para el reintegro.</b>");
                          $error=true;
                      }
                      
                    if($error == FALSE)
                    {
                        $id_trabajador= $_POST ['Reintegro']['id_trabajador'];
                        $id_credito = $_POST['idcredito'];
                        $id_CPago = $_POST['selec'];
                        $mvm_cuota = $_POST['mvm_cuota'];
                        $c_mnt= CreditoPagos::model()->findByAttributes(array('id'=>$id_CPago));
                        $mnt= $c_mnt->cuota;
                        $validacion= Reintegro::model()->findByAttributes(array('idtrabajador'=>$id_trabajador, 'idcredito_pago'=>$id_CPago[0] ));
                        if(count($validacion) > 0)
                        {
                            Yii::app()->user->setFlash('error', "<b>USTED YA POSEE UNA SOLICITUD DE REINTEGRO, PARA LA CUOTA Nº ".$validacion->credito_pago->numero_cuota." DEL CREDITO ". strtoupper($validacion->credito->tipocredito->descripcion) ." REALIZADA EL DIA $validacion->fecha_solicitud.</b>");
                            $this->redirect(array('view','id'=>$validacion->idreintegro)); 
                        }

                        $campos="idtrabajador, idcredito, idcredito_pago, mvm_cuota, monto_reintegro, aprobado";
                        $values="$id_trabajador, $id_credito,$id_CPago[0],$mvm_cuota,$mnt,3 ";
                        $sql="insert into contable.reintegro ($campos) values ($values) RETURNING idreintegro;";
                        //echo $sql; die();
                        $connection=Yii::app()->db;
                        $command=$connection->createCommand($sql); 
                        if ($row=$command->queryAll())
                             $this->redirect(array('view','id'=>$row[0]['idreintegro'])); 
                          else
                              Yii::app()->user->setFlash('error', "<b>NO SE PUDO GUARDAR LA SOLICITUD DE REINTEGRO. CONTACTE AL ADMINISTRADOR DEL SISTEMA.</b>");
                       }
		}
                //Yii::app()->clientScript->scriptMap['jquery.js'] = false;
		//Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
		$this->render('create',array(
			'model'=>$model, 'datos'=>$dato_aportante,
		));
	}
        public function actionCargarCuotas()
        {
            $model=new Reintegro;
            $id= $_POST['idcredito'];
            $inf= CreditoPagos::model()->findAll("idcredito =$id and pagada='1' order by numero_cuota");
            $this->renderPartial('_formcuotas', array('model'=>$model, 'inf'=>$inf));
        }
        
        public function actionAprobarReintegro($id)
	{
            
            $model=$this->loadModel($id);
            $id_trabajador= $model->idtrabajador;
            if(isset($_POST['Reintegro']))
            {
                $sql= "update contable.reintegro set aprobado=1, fecha_aprobacion= now() where idreintegro= $model->idreintegro";
                $connection=Yii::app()->db;
                $command=$connection->createCommand($sql); 
                if ($row=$command->queryAll())
                {
                    $sql1= "update prestamos.credito_pagos set pagada='0', blnborrado= true where id= $model->idcredito_pago";
                    $connection=Yii::app()->db;
                    $command=$connection->createCommand($sql1);
                    $row=$command->queryAll();
                
                    Yii::app()->user->setFlash('success', "<b>La solicitud ha sido APROBADA exitosamente.</b>");
                    $this->redirect(array('admin')); 
                }
            }
            $this->render('_aprobacion',array('model'=>$model,));

            
            
        }
        
        public function actionDenegarReintegro($id)
        {

                $model=$this->loadModel($id);
                $sql= "update contable.reintegro set aprobado= 2 where  idreintegro = $model->idreintegro";
                $connection=Yii::app()->db;
                $command=$connection->createCommand($sql); 
                if ($row=$command->queryAll())
                {
                    Yii::app()->user->setFlash('success', "<b style='color: red;'>La solicitud ha sido DENEGADA.</b>");
                    $this->redirect(array('admin')); 
                }
        }

	/**
	 * 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['Reintegro']))
		{
			$model->attributes=$_POST['Reintegro'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idreintegro));
		}

		$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)
	{
		$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'));
	}

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

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

		$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 $id the ID of the model to be loaded
	 * @return Reintegro the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Reintegro::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

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