<?php

class AjustesController extends Controller{

	// Layout
	public $layout='panel';

	/**
	 * @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
		);
	}

	/**
	 * 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', 'obtenerDatos', 'agregar', 'modificar', 'log'),
				'users' => array('@'),
			),
			array(
				'deny',  // deny all users
				'users' => array('*'),
			),
		);
	}

	public function actionIndex(){
		// $model = new SidcaiParametro;
		$model = SidcaiParametro::model()->find();

		Yii::import('application.controllers.FuncionesController');

		if($model->para_interfazseniat == null) $model->para_interfazseniat = 0;
		if($model->para_interfazbanca == null) $model->para_interfazbanca = 0;

		$model->para_cantidadunidadestributarias = number_format($model->para_cantidadunidadestributarias, 0, ',', '.');
		$model->para_fecha_tope_prorroga = FuncionesController::convertirFecha($model->para_fecha_tope_prorroga, "dd/mm/yyyy");

		$this->performAjaxValidation($model);

		if(isset($_POST['SidcaiParametro'])){
			if(isset($_POST['ok'])){
				$data = null; // Variable que sera enviada por JSON

				$data['datos'] = $this->guardar($model, $_POST['SidcaiParametro'], "modificar");

				echo json_encode($data);
			}
			Yii::app()->end();
		}else
			$this->render('index', array('model' => $model));
	}

	public function actionLog(){
		$mostrar = false;
		$codigo = "";
		$ruta = "";

		// Busca el archivo
		if(isset($_POST['enviar'])){
			$ruta = trim(CHtml::encode($_POST['ruta']));

			// Si el archivo existe lo mostrará
			if(file_exists($ruta)){
				$mostrar = true;
				$file = file($ruta);

				foreach($file as $f){
					$codigo .= CHtml::decode($f);
			    }

			}else{
				Yii::app()->user->setFlash('error', 'No se logró conseguir el archivo, por favor verifique que la ruta sea la correcta <b>"'.$ruta.'"</b>.');
			}
		}

		$this->render("log", [
			'mostrar' => $mostrar,
			'codigo' => $codigo,
			'ruta' => $ruta
		]);
	}
	/**
	 * 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 SidcaiUnidadtributaria the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=SidcaiParametro::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param SidcaiUnidadtributaria $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='sidcai-parametro-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

		/**
		* Función para guardar un registro tango en agregar como en modificar.
		* Función llamada en "actionIndex"
		* @return array("alert", "mensaje", "(solo en $model->save()) agregar : modificar")
	**/
	private function guardar($model, array $post, string $accion, int $id = null) : array{
		// Se importa el controlador FuncionesController para hacer uso de "erroresModel" y "convertirFecha".
		Yii::import("application.controllers.FuncionesController");
		$atributos = [];
		// Se limpia los campos para evitar Ataque XSS.
		foreach($post as $key => $value){
			$atributos[$key] = CHtml::encode($value);
		}

		$model->attributes = $atributos;

		$msj_error ="Por favor verifique el siguiente campo:<br><br>";

		// Se valida primero el $model
		if(!$model->validate()) {
			$errores = FuncionesController::erroresModel($model, "SidcaiParametro");
			return ["warning", $msj_error.$errores];
		}
		// Una vez validado el $model se proceden a validar los datos.

		// Se convierten las fechas al formato "yyyy-mm-dd" para que se puedan guardar en la BD.
		$para_fecha_tope_prorroga = FuncionesController::convertirFecha($model->para_fecha_tope_prorroga, "yyyy-mm-dd");

		// Se remueven los "." y luego se reemplaza la "," por "." para poder guardar el valor en la BD.
		$unidades_tributarias = str_replace(".", "", $model->para_cantidadunidadestributarias);
		$unidades_tributarias = str_replace(",", ".", $unidades_tributarias);

		$actualizar = SidcaiParametro::model()->updateAll([
			'para_fecha_tope_prorroga' => $para_fecha_tope_prorroga,
			'para_cantidadunidadestributarias' => $unidades_tributarias,

		]
		);


		if($actualizar == 0 || $actualizar == NULL)
			$guardar = ["danger", "No se logró modificar los Ajustes."];
		else
			$guardar = ["success", "Se modificó los Ajustes correctamente.", $accion];

		unset($_POST['SidcaiParametro']); // Se limpia el POST enviado por el formulario.
		$model->unsetAttributes(); // Se limpia el model.

		return $guardar;
	}

	/*********************************************************************************************

											Expresiones

	*********************************************************************************************/
}

?>