<?php

class CreditoAbonoController 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
                        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','Aprobar','createAdministrador','Reporte'),
				'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)
    {
        $model = $this->loadModel($id);

        if (Yii::app()->user->checkAccess('usuario_asociado') && !Yii::app()->user->checkAccess('usuario_administrador')) {
            $modelAsociado = Asociado::model()->find(
                'cedula=:cedula AND blnborrado = false AND id_estatus in(1,4) ORDER BY idasociado desc',
                array(':cedula' => CrugeUserI::model()->findByPk(Yii::app()->user->id)->cedula)
            );
            if ($model->idCredito->idasociado != $modelAsociado->idasociado) {
                Yii::app()->user->setFlash('error', 'No se encontraron registro para mostrar, intente mas tarde');
                $this->redirect(array('admin'));
            }
        }

        $modelCreditoSeleccionado = [];
        if ($model->prestamos_seleccionados != '') {
            $modelCreditoSeleccionado = json_decode($model->prestamos_seleccionados, true);
        }

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

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$modelAsociados = Asociado::model()->find('cedula=:cedula AND blnborrado = false AND id_estatus=1 ORDER BY idasociado desc', array(':cedula' => CrugeUserI::model()->findByPk(Yii::app()->user->id)->cedula));
        if(!$modelAsociados){
             Yii::app()->user->setFlash('error','No esta habilitado para realizar soliciutdes de abonos a prestamos');
             $this->redirect( array('admin'));
        }
        $solicitud = Liquidacion::checkSolicitud($modelAsociados->idasociado);
        if (empty($solicitud)) {
			$model=new CreditoAbono('RegistrarAbono');
            $modelAsociado = Asociado::model()->find('cedula=:cedula AND blnborrado = false AND id_estatus=1 ORDER BY idasociado desc', array(':cedula' => CrugeUserI::model()->findByPk(Yii::app()->user->id)->cedula));
            $modelReporteCredito=new ReporteCreditos('search');

            if(!$modelAsociado){
                Yii::app()->user->setFlash('error','Lo sentimos, no está habilitado para realizar solicitud de retiro parcial ');
                $this->redirect( array('admin'));
            }

            $model->idasociado = $modelAsociado->idasociado;

	        // $modelConfDiasPago=ConfCreditoAbono::model()->find('id_tipo_nomina=:id_tipo_nomina AND blnborrado= false',
         //        [':id_tipo_nomina'=>$modelAsociado->getIdTipoNomina()]);
	        // if($modelConfDiasPago){
	        //     if($modelConfDiasPago->diasHabilesPago() !=0){
	        //         Yii::app()->user->setFlash('error','No hay disponibilidad para reportar el abono a préstamo.');
	        //         $this->redirect( array('admin'));
	        //     }

	        // }
	        // else{
	        // 	Yii::app()->user->setFlash('error','no se ha configurado los dias limites para el registro de abonos a los préstamos.');
	        //         $this->redirect( array('admin'));
	        // }

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

            $modelConfGeneralCreditoAbono= ConfGeneralCreditoAbono::model()->find();

			$modelReporteCredito->unsetAttributes();  // clear any default values
			if(isset($_GET['ReporteCreditos']))
				$modelReporteCredito->attributes=$_GET['ReporteCreditos'];


			if(isset($_POST['CreditoAbono']))
			{
				$prestamos_seleccionado = [];

				$model->attributes=$_POST['CreditoAbono'];
	            
    			$totalDeuda = 0;

				$montos = [];

				if(isset($_POST['seleccion'])){

					foreach ($_POST['seleccion'] as $key => $value) {

						$model->idcredito .=$value.',';

						$modelPrestamos = ReporteCreditos::model()->find('idcredito=:idcredito',[':idcredito' =>$value]);

						if($modelPrestamos){

							$monto_deuda = $modelPrestamos->getMontoDeudaActualConfigurado($value);

							$totalDeuda += $monto_deuda;

							$montos[$key]  = $monto_deuda;

							array_push($prestamos_seleccionado,[
								'id_credito' => $value,
								'id_tipo_credito' => $modelPrestamos->id_tipo_credito,
								'cuotas_pagadas' => $modelPrestamos->cuotas_pagadas,
								'monto_deuda' => $monto_deuda,
								'monto_abonar' => 0,
							]);
							
						}
					}
					
				}
	// echo "<pre>";print_r($prestamos_seleccionado);Exit;
				$model->idcredito =trim($model->idcredito,',');

				if($model->validate()){
	                            $transaction = Yii::app()->db->beginTransaction();
	                                try {

	                                	$monto_abonar = str_replace(',', '.', str_replace('.', '', $model->monto_abonar));
	                    
										// Si el monto pagado cubre o sobre pasa el monto de las deudas
										if($monto_abonar >= $totalDeuda ){

											foreach ($prestamos_seleccionado as $key => $value) {

												$prestamos_seleccionado[$key]['monto_abonar']  = $value['monto_deuda'];

											}

										}
										else{

				                            if ($modelConfGeneralCreditoAbono->metodo_abono_credito == 1 || $modelConfGeneralCreditoAbono->metodo_abono_credito == 2) {
												
												array_multisort($montos, (($modelConfGeneralCreditoAbono->metodo_abono_credito == 1)?SORT_DESC:SORT_ASC), $prestamos_seleccionado);

												foreach ($prestamos_seleccionado as $key => $value) {

													if($monto_abonar > 0){

										            	if($monto_abonar >= $value['monto_deuda']){

										            		$prestamos_seleccionado[$key]['monto_abonar']  = $value['monto_deuda'];
										            		
										            		$monto_abonar -=$value['monto_deuda'];

										            	}
										            	else{

										            		$prestamos_seleccionado[$key]['monto_abonar']  = $monto_abonar;

										            		$monto_abonar =0;

										            	}
										            	
										            }

												}

				                            }
				                            else{
												
												$factor = $monto_abonar / $totalDeuda ;

												$montoRestante = 0;
												$sum_deuda_actual = $monto_abonar - $totalDeuda;

													foreach ($prestamos_seleccionado as $key => $value) {

														$montoPagado = $factor * $value['monto_deuda'];

														$prestamos_seleccionado[$key]['monto_abonar']  = round($montoPagado, 2);
														
														$montoRestante += $prestamos_seleccionado[$key]['monto_abonar'];

														if((count($prestamos_seleccionado) -1) == $key){

															if($monto_abonar != $montoRestante){

																$prestamos_seleccionado[$key]['monto_abonar']  = $prestamos_seleccionado[$key]['monto_abonar'] +($monto_abonar - $montoRestante);

															}

														}

													}

				                            }

										}
										$model->prestamos_seleccionados =  json_encode($prestamos_seleccionado);


                                		$ids_creditos_seleccionados = $model->idcredito;

	                                    if($model->save()){
	                                        $modelSeguimiento = new CreditoAbonoSeguimiento();
	                                        $modelSeguimiento->id_credito_abono = $model->id;
	                                        $modelSeguimiento->id_estatus_abono = 1;
	                                        $modelSeguimiento->saldo_deudor = ReporteCreditos::model()->getMontoDeudaActual($model->idcredito);;
                                        	$modelSeguimiento->saldo_para_abono = ReporteCreditos::model()->getMontoDeudaActualConfigurado($model->idcredito);
	                                        $modelSeguimiento->save();
	                                        if($modelSeguimiento->save()){   //exit;
	                                            $transaction->commit();
	                                            Yii::app()->user->setFlash('success', 'Los datos han sido registrado exitosamente');
	//                                            CorreoElectronico::enviarCorreo(array('nombre'=>$model->nombre.' '.$model->apellidos,
	//                                                                                    'correo'=>$model->correoelectronico,
	//                                                                                    'asunto'=>'Registo de los Datos de la Planilla',
	//                                                                                    'mensaje'=>$this->renderPartial('correoRegistroAsociado',array(
	//                                                                                            'model'=>$model,
	//                                                                                            'empresa' =>  Empresa::model()->find(),
	//                                                                                    ), true)
	//                                                                            ));
	                                            $this->redirect(array('view','id'=>$model->id));
	                                        }
	                                        else{
	                                            $transaction->rollBack();
	                                            Yii::app()->user->setFlash('error', 'Los datos no han sido registrado');
	                                            $this->redirect(array('admin'));
	                                        }
	                                    }
	                                } catch (Exception $ex) {
	                                     Yii::app()->user->setFlash('error', 'Los datos no han sido registrado');
	                                            $this->redirect(array('admin'));
	                                }

	                        }

			}

			$this->render('create',array(
				'model'=>$model,
				'modelReporteCredito'=>$modelReporteCredito,
				'modelAsociado'=>$modelAsociado,
				'modelConfGeneralCreditoAbono'=>$modelConfGeneralCreditoAbono,

			));

		}else{ //Si hay una solicitud de liquidacion registrada que no este denegada redirige

            Yii::app()->user->setFlash('error', "<b>Ud. posee una solicitud de liquidación registrada.</b>");
            $this->redirect(array('/retiro/liquidacion/admin'));
        }
	}

	public function actionCreateAdministrador()
    {
        $model = new CreditoAbono('RegistrarAbonoAdministrador');
        $modelReporteCredito = new ReporteCreditos('search');
        $modelConfGeneralCreditoAbono = ConfGeneralCreditoAbono::model()->find();
        $postDatos = false;

        $modelReporteCredito->unsetAttributes(); // clear any default values
        if (isset($_GET['ReporteCreditos'])) {
            $modelReporteCredito->attributes = $_GET['ReporteCreditos'];
        }

        if (isset($_POST['CreditoAbono'])) {
            $prestamos_seleccionado = [];
            $postDatos = true;
            $model->attributes = $_POST['CreditoAbono'];
            $totalDeuda = 0;
            $montos = [];

            if (isset($_POST['seleccion'])) {
                foreach ($_POST['seleccion'] as $key => $value) {
                    $model->idcredito .= $value . ',';
                    $modelPrestamos = ReporteCreditos::model()->find('idcredito=:idcredito', [':idcredito' => $value]);

                    if ($modelPrestamos) {
                        $monto_deuda = $modelPrestamos->getMontoDeudaActualConfigurado($value);
                        $totalDeuda += $monto_deuda;
                        $montos[$key] = $monto_deuda;

                        array_push($prestamos_seleccionado, [
                            'id_credito' => $value,
                            'id_tipo_credito' => $modelPrestamos->id_tipo_credito,
                            'cuotas_pagadas' => $modelPrestamos->cuotas_pagadas,
                            'monto_deuda' => $monto_deuda,
                            'monto_abonar' => 0
                        ]);
                    }
                }
            }
            $model->idcredito = trim($model->idcredito, ',');

            if ($model->validate()) {
                $transaction = Yii::app()->db->beginTransaction();
                try {
                    $monto_abonar = str_replace(',', '.', str_replace('.', '', $model->monto_abonar));

                    // Si el monto pagado cubre o sobre pasa el monto de las deudas
                    if ($monto_abonar >= $totalDeuda) {
                        foreach ($prestamos_seleccionado as $key => $value) {
                            $prestamos_seleccionado[$key]['monto_abonar'] = $value['monto_deuda'];
                        }
                    } else {
                        if (in_array($modelConfGeneralCreditoAbono->metodo_abono_credito, [1, 2])) {
                            array_multisort(
                                $montos,
                                $modelConfGeneralCreditoAbono->metodo_abono_credito == 1 ? SORT_DESC : SORT_ASC,
                                $prestamos_seleccionado
                            );

                            foreach ($prestamos_seleccionado as $key => $value) {
                                if ($monto_abonar > 0) {
                                    if ($monto_abonar >= $value['monto_deuda']) {
                                        $prestamos_seleccionado[$key]['monto_abonar'] = $value['monto_deuda'];
                                        $monto_abonar -= $value['monto_deuda'];
                                    } else {
                                        $prestamos_seleccionado[$key]['monto_abonar'] = $monto_abonar;
                                        $monto_abonar = 0;
                                    }
                                }
                            }
                        } else {
                            $factor = $monto_abonar / $totalDeuda;
                            $montoRestante = 0;
                            $sum_deuda_actual = $monto_abonar - $totalDeuda;

                            foreach ($prestamos_seleccionado as $key => $value) {
                                $montoPagado = $factor * $value['monto_deuda'];
                                $prestamos_seleccionado[$key]['monto_abonar'] = round($montoPagado, 2);
                                $montoRestante += $prestamos_seleccionado[$key]['monto_abonar'];

                                if (count($prestamos_seleccionado) - 1 == $key) {
                                    if ($monto_abonar != $montoRestante) {
                                        $prestamos_seleccionado[$key]['monto_abonar'] =
                                            $prestamos_seleccionado[$key]['monto_abonar'] +
                                            ($monto_abonar - $montoRestante);
                                    }
                                }
                            }
                        }
                    }

                    $model->prestamos_seleccionados = json_encode($prestamos_seleccionado);
                    $ids_creditos_seleccionados = $model->idcredito;

                    if ($model->save()) {
                        $modelSeguimiento = new CreditoAbonoSeguimiento();
                        $modelSeguimiento->id_credito_abono = $model->id;
                        $modelSeguimiento->id_estatus_abono = 1;
                        $modelSeguimiento->saldo_deudor = ReporteCreditos::model()->getMontoDeudaActual(
                            null,
                            $ids_creditos_seleccionados
                        );
                        $modelSeguimiento->saldo_para_abono = ReporteCreditos::model()->getMontoDeudaActualConfigurado(
                            $ids_creditos_seleccionados
                        );
                        if ($modelSeguimiento->save()) {
                            $transaction->commit();
                            Yii::app()->user->setFlash('success', 'Los datos han sido registrado exitosamente');
                            // CorreoElectronico::enviarCorreo([
                            //     'nombre' => $model->nombre.' '.$model->apellidos,
                            //     'correo' => $model->correoelectronico,
                            //     'asunto' => 'Registo de los Datos de la Planilla',
                            //     'mensaje' => $this->renderPartial('correoRegistroAsociado', [
                            //         'model' => $model,
                            //         'empresa' => Empresa::model()->find(),
                            //     ], true),
                            // ]);
                            $this->redirect(['view', 'id' => $model->id]);
                        } else {
                            $transaction->rollBack();
                            Yii::app()->user->setFlash('error', 'Los datos no han sido registrado');
                            $this->redirect(['admin']);
                        }
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                    Yii::app()->user->setFlash('error', 'Los datos no han sido registrado');
                    $this->redirect(['admin']);
                }
            }
        }

        $this->render('createAdministrador', [
            'model' => $model,
            'modelReporteCredito' => $modelReporteCredito,
            'postDatos' => $postDatos,
            'modelConfGeneralCreditoAbono' => $modelConfGeneralCreditoAbono
        ]);
    }

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

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

    public function actionAprobar($id)
    {
        $model = $this->loadModel($id);
        $model->fecha_comprobante = date('d-m-Y');
        $tipo_nomina = $model->idAsociado;
        $modelCreditoSeleccionado = [];

        if ($model->prestamos_seleccionados != '') {
            $modelCreditoSeleccionado = json_decode($model->prestamos_seleccionados, true);
        }

        $modelSeguimiento = CreditoAbonoSeguimiento::model()->find('id_credito_abono=:id and actual= true', [':id' => $id]);
        if ($modelSeguimiento->id_estatus_abono != 1) {
            $this->redirect(['view', 'id' => $id]);
        }

        $modelCreditoSeguimiento = new CreditoAbonoSeguimiento();
        $modelCreditoSeguimiento->id_credito_abono = $id;

        if (isset($_POST['CreditoAbonoSeguimiento'])) {
            $valido = true;
            $modelCreditoSeguimiento->attributes = $_POST['CreditoAbonoSeguimiento'];
            $empresa = Empresa::model()->find();

            if (isset($_POST['yt0'])) {
                $modelCreditoSeguimiento->id_estatus_abono = 2;
                $model->scenario = 'aprobacionSolicitud';
            }

            if (isset($_POST['yt1'])) {
                $modelCreditoSeguimiento->id_estatus_abono = 3;
                $modelCreditoSeguimiento->scenario = 'denegacionSolicitud';
            }

            if (isset($_POST['CreditoAbono']['destino_remanente'])) {
                $model->destino_remanente = $_POST['CreditoAbono']['destino_remanente'];
            }

            Yii::import('application.modules.contable.models.*', true);
            if (ParamEscenarios::fechaComprobante(['abono' => 5])) {
                $model->fecha_comprobante = $_POST['CreditoAbono']['fecha_comprobante'];
            }

            if (! $model->validate() && $model->remanenteAbono()) {
                return $this->render('aprobar', [
                    'model' => $model,
                    'modelCreditoSeguimiento' => $modelCreditoSeguimiento,
                    'modelCreditoSeleccionado' => $modelCreditoSeleccionado,
                ]);
            }

            if ($modelCreditoSeguimiento->validate()) {
                $transaction = Yii::app()->db->beginTransaction();
                try {
                    $valido = true;
                    CreditoAbonoSeguimiento::model()->updateAll(['actual' => false], 'id_credito_abono=:id', [':id' => $modelCreditoSeguimiento->id_credito_abono]);
                    if ($modelCreditoSeguimiento->save()) {
                        if ($modelCreditoSeguimiento->id_estatus_abono == 2) {
                            $monto_abonar = str_replace(',', '.', str_replace('.', '', $model->monto_abonar));
                            $modelConfGeneralCreditoAbono = ConfGeneralCreditoAbono::model()->find();
                            $montos = [];

                            $totalDeuda = 0;
                            foreach ($modelCreditoSeleccionado as $keyCs => $valueCs) {
                                $montoTotal = ReporteCreditos::model()->getMontoDeudaActualConfigurado($valueCs['id_credito']);
                                $montos[$keyCs] = $montoTotal; // columna de animales
                                $totalDeuda += $montoTotal;
                                $valueCs['monto_deuda'] = $montoTotal;
                            }

                            //ordenamos ascendente por la columna elegida
                            $valido = true;

                            // Si el monto pagado cubre o sobre pasa el monto de las deudas
                            $monto_abonar = trim($monto_abonar);
                            $totalDeuda = trim($totalDeuda);

                            if ($monto_abonar >= $totalDeuda) {
                                foreach ($modelCreditoSeleccionado as $key => $value) {
                                    $modelCreditoSeleccionado[$key]['monto_abonar'] = $value['monto_deuda'];
                                    $value['monto_nuevo_credito'] = 0;
                                    $valido = $valido && $this->setAbonoCredito($value, $model->mantener_cuota);
                                }

                                $monto_abonar -= $totalDeuda;
                            } else {
                                if ($modelConfGeneralCreditoAbono->metodo_abono_credito == 1 || $modelConfGeneralCreditoAbono->metodo_abono_credito == 2) {
                                    array_multisort($montos, (($modelConfGeneralCreditoAbono->metodo_abono_credito == 1) ? SORT_DESC : SORT_ASC), $modelCreditoSeleccionado);

                                    foreach ($modelCreditoSeleccionado as $key => $value) {
                                        if ($monto_abonar > 0) {
                                            if ($monto_abonar >= $value['monto_deuda']) {
                                                $value['monto_nuevo_credito'] = 0;
                                                $monto_abonar -= $value['monto_deuda'];
                                                $value['monto_abonar'] = $value['monto_deuda'];
                                            } else {
                                                $value['monto_nuevo_credito'] = $value['monto_deuda'] - $monto_abonar;
                                                $value['monto_abonar'] = $monto_abonar;
                                                $monto_abonar = 0;
                                            }

                                            $valido = $valido && $this->setAbonoCredito($value, $model->mantener_cuota);
                                        }
                                    }
                                } else {
                                    $factor = $monto_abonar / $totalDeuda;
                                    $montoRestante = 0;
                                    $sum_deuda_actual = $totalDeuda - $monto_abonar;

                                    foreach ($modelCreditoSeleccionado as $key => $value) {
                                        if ($value['monto_deuda'] > 0) {
                                            $montoPagado = $factor * $value['monto_deuda'];
                                            $value['monto_nuevo_credito'] = round($value['monto_deuda'] - $montoPagado, 2);
                                            $montoRestante += $value['monto_nuevo_credito'];

                                            if ((count($modelCreditoSeleccionado) - 1) == $key) {
                                                if ($sum_deuda_actual != $montoRestante) {
                                                    $value['monto_nuevo_credito'] = $value['monto_nuevo_credito'] + ($sum_deuda_actual - $montoRestante);
                                                }
                                            }

                                            $value['monto_abonar'] = $value['monto_deuda'] - $value['monto_nuevo_credito'];
                                        } else {
                                            $value['monto_nuevo_credito'] = 0;
                                        }

                                        $valido = $valido && $this->setAbonoCredito($value, $model->mantener_cuota);
                                    }
                                }

                                $monto_abonar = 0;
                            }

                            $model->remanente_abono = $monto_abonar;

                            if ($valido) {
                                $model->prestamos_seleccionados = json_encode($modelCreditoSeleccionado);

                                $model->save();
                                $model->procesarRemanenteAbono();

                                //////////////////////////// Contabilización comprobante inicio ////////////////////////////
                                Yii::import('application.modules.contable.models.comprobantes.abono.*', true);
                                Yii::import('application.modules.contable.models.comprobantes.*', true);
                                (new AbonoPrestamo($model))->contabilizar();
                                //////////////////////////// Contabilización comprobante fin ///////////////////////////////

                                $transaction->commit();
                                Yii::app()->user->setFlash('success', '<b>El abono a préstamo se registro con exito</b></b>');
                                $this->redirect(['admin']);
                            } else {
                                $transaction->rollBack();
                                Yii::app()->user->setFlash('error', 'Los datos no han sido registrado');
                                $this->redirect(['admin']);
                            }
                        } else {
                            $transaction->commit();
                            Yii::app()->user->setFlash('success', '<b>El abono a préstamo se registro con exito</b></b>');
                            $this->redirect(['admin']);
                        }
                    } else {
                        $transaction->rollBack();
                        Yii::app()->user->setFlash('error', '<b>Error ocurrido al momento de aprobar la solicitud</b></b>');
                    }

                    $this->redirect(['admin']);
                } catch (Exception $e) {
                    Yii::app()->user->setFlash('error', $e->getMessage());
                    $this->redirect(['admin']);
                }
            }
        }

        $this->render('aprobar', ['model' => $model,
            'modelCreditoSeguimiento' => $modelCreditoSeguimiento,
            'modelCreditoSeleccionado' => $modelCreditoSeleccionado,
        ]);
    }

	/**
	 * 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.');
	}
        public function actionReporte()
        {
            yii::app()->request->sendFile("Reporte de abono a prestamos.xlsx",
            $this->renderPartial('reportExcelAbono',array(
            ), true)
            );
        }

	
	protected function setAbonoCredito ($array_credito, $mantener_cuota){

		$modelCredito = Credito::model()->findByPk($array_credito['id_credito']);

		$valido = TRUE;
							
		//cancelar las cuotas del prestamo que id_estaus_cuota sea null
		$sql = ConfCreditoAbono::model()->getCondicionCuotasCredito($modelCredito->id_tipo_nomina);

		if($array_credito['monto_nuevo_credito'] > 0){

			$cuotasTotales = CreditoTablaAmortizacion::model()->find( array('select'=>'min(fecha_vencimiento) as fecha_vencimiento, count(*) as numero_cuota',
																			'condition'=> 'idcredito=:id '.$sql.' AND blnborrado = false',
																		'params'=>array(':id'=>$modelCredito->id)));
										
			$generar_cuotas_especiales = CreditoTablaAmortizacion::model()->find('idcredito=:id '.$sql.' AND blnborrado = false AND tipo_cuota = \'A\'',
																		[':id'=>$modelCredito->id]);
			
			$tipo_cuota ='O';

			###################################EL CREDITO POSEE CUOTAS ORDINARIAS ACTIVAS ############################################333
			$montoCuota = CreditoTablaAmortizacion::model()->find("idcredito=:idcredito AND tipo_cuota='O' AND blnborrado= false ".$sql.' ORDER BY id ASC',
																		[':idcredito'=>$modelCredito->id]);
			if($montoCuota){

				$monto_cuota = $montoCuota->monto_cuota;

				// obtener todas las fechas de cobro que se generaron de la tabla de tablaAmortizacion
				$modelFechaDescuento = CreditoTablaAmortizacion::model()->findAll("idcredito=:idcredito AND tipo_cuota='O' AND blnborrado= false AND id >= :id",
																			[':idcredito'=>$modelCredito->id,':id'=>$montoCuota->id]);// obtener todas las fechas de cobro que se generaron de la tabla de tablaAmortizacion

				$primeraCuota = 0;

				CreditoTablaAmortizacion::model()->updateAll(['blnborrado'=>true,'id_usuario'=>Yii::app()->user->id],'idcredito=:id '.$sql,[':id'=>$modelCredito->id]);


				$modelTablaAmortizacion = [];

				if($mantener_cuota){

					$modelResultadoTablaAmortizacion = CreditoTablaAmortizacion::model()->tablaAmortizacion(array(
																						'tipo_credito'=>$modelCredito->idTipoCredito,
																						'monto_credito'=>$array_credito['monto_nuevo_credito'],
																						'monto_cuota'=>$monto_cuota,
																						'mantener_cuota'=>true,
																						'generar_cuotas_especiales'=>($generar_cuotas_especiales)?1:0,
																						'idTipoNomina'=> $modelCredito->id_tipo_nomina));

					$modelTablaAmortizacion = $modelResultadoTablaAmortizacion['tablaAmortizacion'];

				}
				else{

					$modelResultadoTablaAmortizacion = CreditoTablaAmortizacion::model()->tablaAmortizacion(array('tipo_credito'=>$modelCredito->idTipoCredito,
																								'monto_credito'=>$array_credito['monto_nuevo_credito'],
																								'idTipoNomina'=>$modelCredito->id_tipo_nomina,
																								'generar_cuotas_especiales'=>($generar_cuotas_especiales)?1:0,
																								'mantener_cuota'=>false,
																								'numeroCuota'=>$cuotasTotales->numero_cuota,));
					$modelTablaAmortizacion = $modelResultadoTablaAmortizacion['tablaAmortizacion'];
				}

				foreach($modelTablaAmortizacion as $key =>$value){

						$value->idcredito = $array_credito['id_credito'];

						$cuotaLibre = false;

						$numeroCuota = $value->numero_cuota;

						do{
							
							$modelNumero = CreditoTablaAmortizacion::model()->find('idcredito=:idcredito AND numero_cuota=:numero_cuota AND blnborrado = false AND tipo_cuota=:tipo_cuota',
																					[':idcredito'=>$value->idcredito,':numero_cuota'=> $numeroCuota ,':tipo_cuota'=> $value->tipo_cuota]);
							
							if(!$modelNumero){
								
								$value->numero_cuota = $numeroCuota;
								
								$cuotaLibre = true;
							
							}
							
							$numeroCuota++;
						
						} while (!$cuotaLibre);
						
						if(!$value->save()){
							
							$valido = false;
						}
						else{
							
							if($key == 0)
								
								$primeraCuota = $value->id;
						}

				}

			}
			else{

				###################################EL CREDITO NO POSEE CUOTAS ORDINARIAS ACTIVAS ############################################
				################################### SOLO TIENE CUOTAS ANUALES ###############################################################

				$tipo_cuota = 'A';
				$montoCuota = CreditoTablaAmortizacion::model()->find("idcredito=:idcredito AND tipo_cuota='A' AND blnborrado= false ".$sql.' ORDER BY id ASC',
																		[':idcredito'=>$modelCredito->id]);

				if($montoCuota){

					$numero_cuota = CreditoTablaAmortizacion::model()->count("idcredito=:idcredito AND tipo_cuota='A' AND blnborrado= false ".$sql,
																			[':idcredito'=>$modelCredito->id]);

					$modelFechaDescuento = CreditoTablaAmortizacion::model()->findAll("idcredito=:idcredito AND tipo_cuota='A' AND blnborrado= false AND id >= :id",
																				[':idcredito'=>$modelCredito->id,':id'=>$montoCuota->id]);

					$numeroCuotaEspecialAnual = TipoCreditoCuotasEspeciales::model()->find(' to_char(fecha_cuota::date,\'MM-DD\')=:fecha_cuota AND id_tipo_credito=:id_tipo_credito',
                                                                                [':fecha_cuota'=>date('m-d',strtotime($modelFechaDescuento[0]->fecha_vencimiento )), ':id_tipo_credito'=>$modelCredito->id_tipo_credito]);

					$monto_cuota = $montoCuota->monto_cuota;

					CreditoTablaAmortizacion::model()->updateAll(['blnborrado'=>true,'id_usuario'=>Yii::app()->user->id],'idcredito=:id '.$sql,[':id'=>$modelCredito->id]);

					$modelResultadoTablaAmortizacion = CreditoTablaAmortizacion::model()->tablaAmortizacionAnualizada(array(
																									'tipo_credito'=>$modelCredito->idTipoCredito,
																									'cuotas_prestamos'=>$modelFechaDescuento,
																									'monto_abonar'=>$array_credito['monto_abonar'],
																									'monto_nuevo_credito'=>$array_credito['monto_nuevo_credito'],
																									'numeroCuotaEspecial'=>$numeroCuotaEspecialAnual->numero_cuota
																								));

					foreach($modelResultadoTablaAmortizacion as $key =>$value){
							$value->idcredito = $array_credito['id_credito'];

							$cuotaLibre = false;

							$numeroCuota = $value->numero_cuota;

							$value->tipo_cuota = 'A';

							do{
								
								$modelNumero = CreditoTablaAmortizacion::model()->find('idcredito=:idcredito AND numero_cuota=:numero_cuota AND blnborrado = false AND tipo_cuota=:tipo_cuota',
																						[':idcredito'=>$value->idcredito,':numero_cuota'=> $numeroCuota ,':tipo_cuota'=> $value->tipo_cuota]);
								
								if(!$modelNumero){
									
									$value->numero_cuota = $numeroCuota;
									
									$cuotaLibre = true;
								
								}
								
								$numeroCuota++;
							
							} while (!$cuotaLibre);
							
							if(!$value->save()){
								
								$valido = false;
							}
							else{
								
								if($key == 0)
									
									$primeraCuota = $value->id;
							}

					}
					
				}




			}

			$fechaPrimerDescuento =  $ultima_fecha =  '';

			foreach ($modelFechaDescuento as $keyMD => $valueFD) {
				
				if($fechaPrimerDescuento == ''){

					$modelTipoNomina = TipoNominaPeriodo::model()->find('id_tipo_nomina=:id_tipo_nomina AND :fecha BETWEEN fecha_desde AND fecha_hasta',[':id_tipo_nomina'=>$modelCredito->id_tipo_nomina, ':fecha'=>$valueFD->fecha_vencimiento]);
	                
	                if($modelTipoNomina){
	                    
	                    $model = DatosPreNominaCredito::model()->with('preNominaSeguimientos')->together(true)->find('id_tipo_momina_periodo=:id_tipo_momina_periodo AND actual = true and id_estatus_pre_nomina !=9 AND id_unidad=:id_unidad',[':id_tipo_momina_periodo'=>$modelTipoNomina->id,':id_unidad'=>$modelCredito->idAsociado->idunidad]);

	                    if(!$model)
	                        
	                        $fechaPrimerDescuento = $valueFD->fecha_vencimiento;
	                
	                }
	                else

	                	$fechaPrimerDescuento = $valueFD->fecha_vencimiento;
					
				}

				$ultima_fecha = $valueFD->fecha_vencimiento;
			}
			if($fechaPrimerDescuento ==""){

				$fechaPrimerDescuento = $modelCredito->generarFechaDescuentos(['tipo_cuota'=>$tipo_cuota, 
																			'ultima_fecha'=>$ultima_fecha]);

			}


			unset($modelFechaDescuento);

			Credito::model()->UpdateAll(['fecha_primer_descuento'=>$fechaPrimerDescuento],'id=:idcredito',[':idcredito'=>$modelCredito->id]);
			// Credito::model()->UpdateAll(array('fecha_primer_descuento'=>$fechaPrimerDescuento),'id=:idcredito',array(':idcredito'=>$model->idcredito));
	
		}
		else{


			CreditoTablaAmortizacion::model()->updateAll(['blnborrado'=>true,'id_usuario'=>Yii::app()->user->id],'idcredito=:id '.$sql,[':id'=>$modelCredito->id]);

		}

		// CreditoTablaAmortizacion::model()->updateAll(['blnborrado'=>true,'id_usuario'=>Yii::app()->user->id],'idcredito=:id '.$sql,[':id'=>$modelCredito->id]);

		$cuotas = CreditoTablaAmortizacion::model()->count('idcredito=:idcredito AND blnborrado= false '.$sql,[':idcredito'=>$modelCredito->id]);

		if($cuotas == 0){
		
			CreditoSeguimiento::model()->updateAll(['actual'=>false],'id_credito=:id',[':id'=>$modelCredito->id]);
		
			$creditoSeguimiento = new CreditoSeguimiento();
		
			$creditoSeguimiento->id_credito=$modelCredito->id;
		
			$creditoSeguimiento->id_estatus_credito = 14;
		
			$creditoSeguimiento->save();
		
		}
		$valido = true;
        
        return $valido;
                                
	}
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('CreditoAbono');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

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

	public function actionPrestamosAsociado()
	{
		$modelReporteCredito = new ReporteCreditos('search');
		$modelReporteCredito->unsetAttributes();

        if (isset($_GET['ReporteCreditos'])) {
            $modelReporteCredito->attributes = $_GET['ReporteCreditos'];
		}

		return $this->renderPartial('_prestamosAsociado', [
			'modelReporteCredito' => $modelReporteCredito
		]);
	}

	/**
	 * 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=CreditoAbono::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']==='credito-abono-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
