<?php

class TituloTipoCreditoController 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','ConfigurarFormula', 'formula','UpdateConfGeneral'),
				'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 TituloTipoCredito;

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

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

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

    public function actionConfigurarFormula()
    {
        Yii::import('application.modules.configuracion.models.*');

        $model = Basica::model()->find();
        $model->scenario = 'formula_personalizada';

        if (isset($_POST['Basica'])) {
            $model->attributes = $_POST['Basica'];

            if ($model->id_tipo_formula == 1) {
                $model->setScenario('formula_global');
                $model->id_formula = $model->id_formula_global;
            } else {
                $model->id_formula = $model->id_formula_personalizada;
            }

            if (! $model->guardarFormula($_POST['Basica'])) {
                return $this->render('configurarFormula', array(
                    'model' => $model,
                ));
            }

            Yii::app()->user->setFlash('success', 'Configuración guardada con éxito.');
            $this->refresh();
        }

        return $this->render('configurarFormula', 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('TituloTipoCredito');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

		$modeConfG = ConfGeneralCredito::model()->find(); 
		$this->render('admin',array(
			'model'=>$model,
			'modeConfG'=>$modeConfG,
		));
	}

    public function actionFormula()
    {
        Yii::import('application.modules.configuracion.models.*');

        $formula = Formulas::formulaArray($_POST['id_formula']);
        $procesosFormulas = (new Warp([13, 2, 1]))->map(function ($proceso) use ($formula) {
            return [
                'id' => $proceso,
                'name' => TituloProcesoPago::getNameById($proceso),
                'items' => array_merge($formula,  [
                    'H' => $this->renderPartial('_letra', [
                        'titulo' => 'H',
                        'name' => 'h',
                        'id' => $proceso,
                        'datos' => FormulaDetalle::getAll([
                            'global' => 1,
                            'letra' => 'h',
                            'formula' => $_POST['id_formula'],
                            'proceso' => $proceso,
                        ])
                    ], true),
                    'R' => $this->renderPartial('_letra', [
                        'titulo' => 'R',
                        'name' => 'r',
                        'id' => $proceso,
                        'datos' => FormulaDetalle::getAll([
                            'global' => 3,
                            'letra' => 'r',
                            'formula' => $_POST['id_formula'],
                            'proceso' => $proceso,
                        ])
                    ], true),
                    'X' => $this->renderPartial('_letra', [
                        'titulo' => 'X',
                        'name' => 'x',
                        'id' => $proceso,
                        'datos' => FormulaDetalle::getAll([
                            'global' => 2,
                            'letra' => 'x',
                            'formula' => $_POST['id_formula'],
                            'proceso' => $proceso,
                        ])
                    ], true),
                    'P' => $this->renderPartial('_letra', [
                        'titulo' => 'P',
                        'name' => 'p',
                        'id' => $proceso,
                        'datos' => FormulaDetalle::getAll([
                            'global' => 4,
                            'letra' => 'p',
                            'formula' => $_POST['id_formula'],
                            'proceso' => $proceso,
                        ])
                    ], true),
                ]),
            ];
        });

        echo json_encode([
            'form' => $this->renderPartial('_formulas', [
                'procesos' => $procesosFormulas
            ], true)
        ]);
    }

    public function actionUpdateConfGeneral(){

    	$model = ConfGeneralCredito::model()->find();

    	$resultado = [
    		'mostar_form'=>0,
    		'html'=>'',
    	];

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

    		$model->attributes = $_POST['ConfGeneralCredito'];

    		if($model->consulta){

		    	$resultado['mostar_form'] = 1;

		    	$resultado['html'] = '	<div class="span3">
		                            
				                            <h3 class="text-center">Administrador</h3>

				                            <div class="row">
				                                <b>Reestructuraci&oacute;n de deuda multiple</b> <br>
				                                <input type="checkbox" data-size="normal" class= "data-toggle" name="ConfGeneralCredito[reestructuracion_multiple_adm]" '.(($model->reestructuracion_multiple_adm)? 'checked':'').' data-toggle="toggle" data-on="Si" data-off="No">

				                            </div>
				                            <br><br>
				                            <div class="row">
				                                <b>Refinanciamiento de deuda multiple</b> <br>
				                                <input type="checkbox" data-size="normal" class= "data-toggle" name="ConfGeneralCredito[refinanciamiento_multiple_adm]" '.(($model->refinanciamiento_multiple_adm)? 'checked':'').' data-toggle="toggle" data-on="Si" data-off="No">
				                            </div>
				                        </div>	
				                        <div class="span3">
		                            
				                            <h3 class="text-center">Asociado</h3>

				                            <div class="row">
				                                <b>Reestructuraci&oacute;n de deuda multiple</b> <br>
				                                <input type="checkbox" data-size="normal" class= "data-toggle" name="ConfGeneralCredito[reestructuracion_multiple_asc]" '.(($model->reestructuracion_multiple_asc)? 'checked':'').' data-toggle="toggle" data-on="Si" data-off="No">

				                            </div>
				                            <br><br>
				                            <div class="row">
				                                <b>Refinanciamiento de deuda multiple</b> <br>
				                                <input type="checkbox" data-size="normal" class= "data-toggle" name="ConfGeneralCredito[refinanciamiento_multiple_asc]" '.(($model->refinanciamiento_multiple_asc)? 'checked':'').' data-toggle="toggle" data-on="Si" data-off="No">
				                            </div>
				                        </div>';
    		}
    		else{
    			
    			$model->reestructuracion_multiple_adm = (isset($_POST['ConfGeneralCredito']['reestructuracion_multiple_adm']))?1:0;
    			$model->refinanciamiento_multiple_adm = (isset($_POST['ConfGeneralCredito']['refinanciamiento_multiple_adm']))?1:0;
    			$model->reestructuracion_multiple_asc = (isset($_POST['ConfGeneralCredito']['reestructuracion_multiple_asc']))?1:0;
    			$model->refinanciamiento_multiple_asc = (isset($_POST['ConfGeneralCredito']['refinanciamiento_multiple_asc']))?1:0;
    			$model->save();
    		}
    	}

    	
                    // echo "<pre>";print_r($resultado);exit;
       	echo CJSON::encode($resultado);

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