<?php

class CobroDiferencialCuotaController 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 [
            [
                'allow',
                'actions' => [
                    'admin', 'delete', 'create', 'update', 'index', 'view', 'viewCobro', 'viewCobroReclamar', 'actualizar',
                    'actualizarCuotaRemanente',
                ],
                'users' => ['@'],
            ],
            [
                'deny',
                'users' => ['*'],
            ],
        ];
    }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionViewCobro($id)
	{

		$model = CobroDiferencialCuota::model()->find('id_proceso=:id_proceso AND id_nombre_proceso = 1',[':id_proceso'=>$id]);
		$this->redirect(array('view','id'=>$model->id));

	}
	public function actionViewCobroReclamar($id)
	{

		$model = CobroDiferencialCuota::model()->find('id_proceso=:id_proceso AND id_nombre_proceso = 2',[':id_proceso'=>$id]);
		$this->redirect(array('view','id'=>$model->id));

	}

	public function actionView($id)
    {
        $model = $this->loadModel($id);
        if ($model->id_nombre_proceso == 1) {
            $modelDatosTxt = DatosTxtTablaAmortizacion::model()->find('id=:id', [':id' => $model->id_proceso]);
            $modelPrenomina = $modelDatosTxt->idTablaAmortizacion;
        } else {
            $modelP = PreNominaTablaAmortizacion::model()->find('id=:id', [':id' => $model->id_proceso]);
            $modelPrenomina = $modelP->idTablaAmortizacion;
            $modelDatosTxt = DatosTxtIntegrado::model()->find('id_prenomina_credito=:id_prenomina_credito AND blnborrado= false', [':id_prenomina_credito' => $modelP->id_pre_nomina_credito]);
        }

        $this->render('view', [
            'model' => $model,
            'modelPrenomina' => $modelPrenomina,
            'modelDatosTxt' => $modelDatosTxt,
        ]);
    }

    public function actionActualizar($id)
    {
        $modelCobro = CobroDiferencialCuota::model()->find('id_proceso=:id_proceso AND id_nombre_proceso = 1', [':id_proceso' => $id]);

        $modelSeguimiento = new CobroDiferencialCuotaSeguimiento();

        if ($modelCobro->id_nombre_proceso == 1) {
            $modelDatosTxt = DatosTxtTablaAmortizacion::model()->find('id=:id', [':id' => $modelCobro->id_proceso]);
            $modelPrenomina = $modelDatosTxt->idTablaAmortizacion;
        } else {
            $modelP = PreNominaTablaAmortizacion::model()->find('id=:id', [':id' => $modelCobro->id_proceso]);
            $modelPrenomina = $modelP->idTablaAmortizacion;
            $modelDatosTxt = DatosTxtIntegrado::model()->find('id_prenomina_credito=:id_prenomina_credito AND blnborrado= false', [':id_prenomina_credito' => $modelP->id_pre_nomina_credito]);
        }

        if (isset($_POST['CobroDiferencialCuotaSeguimiento'])) {
            $modelSeguimiento->setAttributes($_POST['CobroDiferencialCuotaSeguimiento']);

            $transaction = Yii::app()->getDb()->beginTransaction();
            try {
                CobroDiferencialCuotaSeguimiento::model()->updateAll(['actual' => false], 'id_cobro_diferencial_cuota=:id', ['id' => $modelCobro->id]);

                $modelSeguimiento->id_cobro_diferencial_cuota = $modelCobro->id;
                if (! $modelSeguimiento->save()) {
                    throw new Exception('No se pudo actualizar el estatus');
                }

                $transaction->commit();

                $this->redirect(['/prestamo/datosPreNominaCredito/view', 'id' => $modelDatosTxt->idTxt->id_prenomina_credito]);
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }

        $this->render('actualizar', [
            'model' => $modelCobro,
            'modelPrenomina' => $modelPrenomina,
            'modelDatosTxt' => $modelDatosTxt,
            'modelSeguimiento' => $modelSeguimiento,
        ]);
    }

    public function actionActualizarCuotaRemanente($id)
    {
        $modelDatosTxt = DatosTxtTablaAmortizacion::model()->find('id=:id', [':id' => $id]);
        $model = new CuotaConciliada($modelDatosTxt);
        $modelSeguimiento = new DatosTxtTablaAmortizacionSeguimiento();

        $modelPrenomina = $modelDatosTxt->idTablaAmortizacion;

        if (isset($_POST['DatosTxtTablaAmortizacionSeguimiento'])) {
            $modelSeguimiento->setAttributes($_POST['DatosTxtTablaAmortizacionSeguimiento']);
            $modelSeguimiento->id_cuota = $modelDatosTxt->id;
            $modelSeguimiento->monto_remanente = $model->remanente();

            $transaction = Yii::app()->getDb()->beginTransaction();
            try {
                DatosTxtTablaAmortizacionSeguimiento::model()->updateAll(['actual' => false], 'id_cuota=:id', [
                    'id' => $modelDatosTxt->id
                ]);

                if (! $modelSeguimiento->save()) {
                    throw new Exception('No se pudo actualizar el estatus');
                }

                $transaction->commit();

                $this->redirect(['/prestamo/datosPreNominaCredito/view', 'id' => $modelDatosTxt->idTxt->id_prenomina_credito]);
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }

        $this->render('actualizarCuotaRemanente', [
            'model' => $model,
            'modelPrenomina' => $modelPrenomina,
            'modelDatosTxt' => $modelDatosTxt,
            'modelSeguimiento' => $modelSeguimiento,
        ]);
    }

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

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

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

		$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['CobroDiferencialCuota']))
		{
			$model->attributes=$_POST['CobroDiferencialCuota'];
			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)
	{
		$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('CobroDiferencialCuota');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

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

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