<?php

class ParametrosContablesController 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','configurar'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','configurar','anular', 'configuracionParametros', 'configuracionGlobal', 'escenarioAuxiliares'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','configurar','cuentamov','autocomplete','update_1'),
				'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),
		));
	}

public function actionAutocomplete($term)
{
 $criteria = new CDbCriteria;
 $criteria->compare('LOWER(descripcion)', strtolower($_GET['term']), true);
 $criteria->compare('LOWER(codigo_cuenta)', strtolower($_GET['term']), true, 'OR');
 $criteria->addCondition('blnborrado=false');
 $criteria->order = 'codigo_cuenta';
 $criteria->limit = 30;
 $data = CuentasConsolidada::model()->findAll($criteria);

 if (!empty($data))
 {
  $arr = array();
  foreach ($data as $item) {
   $arr[] = array(
    'id' => $item->id,
    'value' => $item->codigo_cuenta.'-'.$item->descripcion,
    'label' => $item->codigo_cuenta.'-'.$item->descripcion,
   );
  }
 }
 else
 {
  $arr = array();
  $arr[] = array(
   'id' => '',
   'value' => 'No se han encontrado resultados para su búsqueda',
   'label' => 'No se han encontrado resultados para su búsqueda',
  );
 }

 echo CJSON::encode($arr);
}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new ParametrosContables;

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

		if(isset($_POST['ParametrosContables']))
		{
			$model->attributes=$_POST['ParametrosContables'];
                        $model->valor = str_replace('.', '', $model->cuenta_descripcion);
//                       echo "<pre>";print_r($_POST);exit;
                        $cuenta0=$_POST["ParametrosContables"]["cuenta_descripcion"];
                        $cuenta= explode("-", $cuenta0);
                        $padre = CuentasConsolidada::model()->find('"codigo_cuenta"=:id',array(':id'=>$cuenta[0]));
			 if($padre){
                              $model->valor=$padre->id;
                         }else{
                              $model->valor=null;
                         }
                        $model->id_escenario=$_GET['id2'];
                        if($model->save())
				$this->redirect(array('create','id2'=>$model->id_escenario));
		}

		$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['ParametrosContables']))
		{
			$model->attributes=$_POST['ParametrosContables'];
                        $model->valor = str_replace('.', '', $model->cuenta_descripcion);
//                       echo "<pre>";print_r($_POST);exit;
                        $cuenta0=$_POST["ParametrosContables"]["cuenta_descripcion"];
                        $cuenta= explode("-", $cuenta0);
                        $padre = CuentasConsolidada::model()->find('"codigo_cuenta"=:id',array(':id'=>$cuenta[0]));
			 if($padre){
                              $model->valor=$padre->id;
                         }else{
                              $model->valor=null;
                         }
                         $model->id_escenario=$model->id_escenario;
			if($model->save())
				$this->redirect(array('create','id2'=>$model->id_escenario));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	public function actionUpdate_1($id)
	{
		$model=$this->loadModel($id);

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

		if(isset($_POST['ParametrosContables']))
		{
			$model->attributes=$_POST['ParametrosContables'];
                        $model->valor = str_replace('.', '', $model->cuenta_descripcion);
//                       echo "<pre>";print_r($_POST);exit;
                        $cuenta0=$_POST["ParametrosContables"]["cuenta_descripcion"];
                        $cuenta= explode("-", $cuenta0);
                        $padre = CuentasConsolidada::model()->find('"codigo_cuenta"=:id',array(':id'=>$cuenta[0]));
			 if($padre){
                              $model->valor=$padre->id;
                         }else{
                              $model->valor=null;
                         }
                         $model->id_escenario=$model->id_escenario;
			if($model->save())
				$this->redirect(array('configurar','id'=>$model->id_escenario));
		}

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

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

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

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



        public function actionConfigurar()
        {
            //Hacer aca que cargue modelo vacio o registor si viene un id... y configurar funcion de guardar

            $model=new ParametrosContables;

            // uncomment the following code to enable ajax-based validation
            /*
            if(isset($_POST['ajax']) && $_POST['ajax']==='parametros-contables-parametrizacion_contable-form')
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
            */

            if(isset($_POST['ParametrosContables']))
            {
                $model->attributes=$_POST['ParametrosContables'];
                if($model->validate())
                {
                    // form inputs are valid, do something here

			if($model->save())
				$this->redirect(array('configurar','id'=>$model->id));

                    //return;
                }
            }
            $this->render('configurar',array('model'=>$model));
        }



        public function actionCuentamovId($term) {
            $criteria = new CDbCriteria;
            $criteria->condition = "titulo_mov=2 AND  LOWER(codigo_cuenta) like LOWER(:term)";
            $criteria->params = array(':term'=> ''.$_GET['term'].'%');
            $criteria->limit = 30;
            $criteria->order = 'codigo_cuenta asc';

            $data = CuentasConsolidada2015::model()->findAll($criteria);
            $arr = array();
            foreach ($data as $item) {
                         $cuenta=$item->codigo_cuenta."-".$item->descripcion;
                $arr[] = array(
                    'id' => $item->cuenta,
                    'value' => $cuenta,
                    'label' => $cuenta,
                );
            }
            echo CJSON::encode($arr);
      }


      public function actionCuentamov($term) {
            $criteria = new CDbCriteria;
            $criteria->condition = "titulo_mov=2 AND  LOWER(codigo_cuenta) like LOWER(:term)";
            $criteria->params = array(':term'=> ''.$_GET['term'].'%');
            $criteria->limit = 30;
            $criteria->order = 'codigo_cuenta asc';

            $data = CuentasConsolidada::model()->findAll($criteria);
            $arr = array();
            foreach ($data as $item) {
                         $cuenta=$item->codigo_cuenta."-".$item->descripcion;
                $arr[] = array(
                    'id' => $item->id,
                    'value' => $cuenta,
                    'label' => $cuenta,
                );
            }
            echo CJSON::encode($arr);
      }

     	public function actionAnular()
	{
            $idparam=$_GET['id'];

            $model = ParametrosContables::model()->findByPk($idparam);
            $model->blnborrado =true;
            $model->update(array('blnborrado'));

           $this->redirect(array('create','id'=>$model->id_escenario));

        }

    public function actionConfiguracionParametros($id)
    {
        $model = $this->loadModel($id);

        if ($model->id == 19) {
            Yii::app()->user->setFlash('error', 'No se encuentra definida una configuración de unidad para este movimiento.');
            return $this->redirect(["/contable/ParametrosContables/configurar&id={$model->id_escenario}"]);
        }

        $model->conf_unidad = true;
        $model->save();

        return $this->redirect(["/contable/ParametrosContables/configurar&id={$model->id_escenario}"]);
    }

    public function actionConfiguracionGlobal($id)
    {
        $model = $this->loadModel($id);
        $model->conf_unidad = false;
        $model->save();

        return $this->redirect(["/contable/ParametrosContables/configurar&id={$model->id_escenario}"]);
    }

    public function actionEscenarioAuxiliares($id, $clv)
    {
        $model = new Parametros('search');
        $model->unsetAttributes();

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

        $this->render('escenario_auxiliares', array(
            'model' => $model,
            'escenario' => ParamEscenarios::model()->findByPk($id),
            'clave' => $clv,
        ));
    }
}
