<?php

class PagosMasivosController 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',
                        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','pagoLiquidaciones','pagoRetiros','pagoCreditos','generarTxt'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','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)
	{
            $modelDetalle= new DetallePagos('search');
            
		$this->render('view',array(
			'model'=>$this->loadModel($id),
                        'modelDetalle'=>$modelDetalle,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new PagosMasivos;

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

		if(isset($_POST['PagosMasivos']))
		{
			$model->attributes=$_POST['PagosMasivos'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
        
        /**
         * 
         */
        public function actionPagoLiquidaciones()
        {
            $model=new PagosMasivos('liquidaciones');
            $modelLiquidacion=new Liquidacion('search');
            $modelLiquidacion->unsetAttributes();
            if(isset($_GET['Liquidacion']))
			$modelLiquidacion->attributes=$_GET['Liquidacion'];
            
            if(isset($_POST['PagosMasivos']))
                {
                    $model->attributes=$_POST['PagosMasivos'];
                    if($model->asociar){
                       $model->scenario='asociar';
                       if($model->validate()){
                           
                          $modelPagos=$this->loadModel($model->id);
                          if($modelPagos){
                           $liquidaciones= split(',',$_POST['PagosMasivos']['seleccion']);
                            foreach ($liquidaciones as $key=>$liquidacion)
                            {
                              $detalle=  new DetallePagos;
                              $detalle->id_liquidacion=$liquidacion;
                              $detalle->id_pagos=$modelPagos->id;
                              $detalle->comprobado=FALSE;
                              $detalle->save();
                            }   
                            $modelPagos->totalesIntegrado(); 
                            $modelPagos->id_tipo_pago=4;
                            $modelPagos->descripcion='ID:'.$modelPagos->id.' Pagos:'.$modelPagos->total_pagos.' Monto:'.$modelPagos->monto_total.' '.$modelPagos->idBanco->banco;
                            if($modelPagos->save()){
                                $this->redirect(array('admin'));
                            }
                              
                          }
                       }
                    }
                   else  
                   { 
                    $model->id_estatus=1;
                    $model->id_tipo_pago=1;
                    $model->id=NULL;
                    if($model->save())
                    {
                      $liquidaciones= split(',',$_POST['PagosMasivos']['seleccion']);
                      foreach ($liquidaciones as $key=>$liquidacion)
                          {
                            $detalle=  new DetallePagos;
                            $detalle->id_liquidacion=$liquidacion;
                            $detalle->id_pagos=$model->id;
                            $detalle->comprobado=FALSE;
                            
                            $detalle->save();
                          }
                    $model->totalesLiquidacion();
                    $model->descripcion='ID:'.$model->id.' Pagos:'.$model->total_pagos.' Monto:'.$model->monto_total.' '.$model->idBanco->banco;
                    if($model->save()){
                        $this->redirect(array('admin'));
                        
                    }
                   }
                }
                }
                $this->render('liquidaciones',array(
			'model'=>$model,
                        'modelLiquidacion'=>$modelLiquidacion,
		)); 
        }
        
        /**
         * Pago masivo de Retiros Parciales
         */
        public function actionPagoRetiros()
        {
            $model=new PagosMasivos('liquidaciones');
            $modelRetiro=new RetiroParcial('search');
            $modelRetiro->unsetAttributes();
            if(isset($_GET['RetiroParcial']))
			$modelRetiro->attributes=$_GET['RetiroParcial'];
            
            if(isset($_POST['PagosMasivos']))
                {
                    $model->attributes=$_POST['PagosMasivos'];
                    if($model->asociar){
                       $model->scenario='asociar';
                       if($model->validate()){
                           
                          $modelPagos=$this->loadModel($model->id);
                          if($modelPagos){
                           $retiros= split(',',$_POST['PagosMasivos']['seleccion']);
                            foreach ($retiros as $key=>$retiro)
                                {
                                  $detalle=  new DetallePagos;
                                  $detalle->id_retiro=$retiro;
                                  $detalle->id_pagos=$model->id;
                                  $detalle->comprobado=FALSE;
                                  $detalle->save();
                                }   
                            $modelPagos->totalesIntegrado(); 
                            $modelPagos->id_tipo_pago=4;
                            $modelPagos->descripcion='ID:'.$modelPagos->id.' Pagos:'.$modelPagos->total_pagos.' Monto:'.$modelPagos->monto_total.' '.$modelPagos->idBanco->banco;
                            if($modelPagos->save()){
                                $this->redirect(array('admin'));
                            }
                              
                          }
                       }
                    }
                    else 
                    {
                    $model->id=NULL;
                    $model->id_estatus=1;
                    $model->id_tipo_pago=2;
                    if($model->save())
                    {
                        
                      $retiros= split(',',$_POST['PagosMasivos']['seleccion']);
                      foreach ($retiros as $key=>$retiro)
                          {
                            $detalle=  new DetallePagos;
                            $detalle->id_retiro=$retiro;
                            $detalle->id_pagos=$model->id;
                            $detalle->comprobado=FALSE;
                            $detalle->save();
                          }
                    $model->totalesRetiro();
                    if($model->save()){
                        $this->redirect(array('admin'));
                        
                    }
                   }
                }
                }
                $this->render('retiros',array(
			'model'=>$model,
                        'modelRetiro'=>$modelRetiro,
		)); 
        }
        
        
        
        public function actionPagoCreditos()
        {
            $model=new PagosMasivos('liquidaciones');
            $modelCredito=new Credito('search');
            $modelCredito->unsetAttributes();
            if(isset($_GET['Credito']))
			$modelCredito->attributes=$_GET['Credito'];
            
            if(isset($_POST['PagosMasivos']))
                {
                    $model->attributes=$_POST['PagosMasivos'];
                    $model->id_estatus=1;
                    $model->id_tipo_pago=2;
                    if($model->save())
                    {
                        
                      $credito= split(',',$_POST['PagosMasivos']['seleccion']);
                      foreach ($retiros as $key=>$retiro)
                          {
                            $detalle=  new DetallePagos;
                            $detalle->id_credito=$credito;
                            $detalle->id_pagos=$model->id;
                            $detalle->comprobado=FALSE;
                            $detalle->save();
                          }
                    $model->totalesCredito();
                    if($model->save()){
                        $this->redirect(array('admin'));
                        
                    }
                   }
                }
                $this->render('creditos',array(
			'model'=>$model,
                        'modelCredito'=>$modelCredito,
		)); 
        }
        
       public function actionGenerarTxt($id)
        {
          $model=$this->loadModel($id);
          $model->id_estatus=2;
          if($model->save()){
          $generarTxt= new ModelosTxtBancos();
          $nombre_archivo='Pagos_'.$model->id_tipo_pago.'_'.$model->id.'.txt';
          return Yii::app()->getRequest()->sendFile($nombre_archivo.'.txt', @file_get_contents($generarTxt->generarTxt($id))); 
          }
          
          } 
        

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

		$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
			$model=$this->loadModel($id);
                        $model->id_estatus=5;
                        
                        if($model->save()){
                            $pagos=  DetallePagos::model()->findAll('id_pagos=:idp',array(':idp'=>$id));
                            if($pagos){
                                foreach ($pagos as $key=>$pago)
                                {
                                  $pago->blnborrado=true;
                                  $pago->save(false);
                                 }
                            }
                        }
			// 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('PagosMasivos');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

		$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=PagosMasivos::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']==='pagos-masivos-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
