<?php

(defined('BASEPATH')) OR exit('No direct script access allowed');

/** load the CI class for Modular Extensions * */
require dirname(__FILE__) . '/Base.php';

 /**
  * Modular Extensions - HMVC
  *
  * Adapted from the CodeIgniter Core Classes
  * @link	http://codeigniter.com
  *
  * Description:
  * This library replaces the CodeIgniter Controller class
  * and adds features allowing use of modules and the HMVC design pattern.
  *
  * Install this file as application/third_party/MX/Controller.php
  *
  * @copyright	Copyright (c) 2015 Wiredesignz
  * @version 	5.5
  * 
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
  * in the Software without restriction, including without limitation the rights
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  * copies of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  * 
  * The above copyright notice and this permission notice shall be included in
  * all copies or substantial portions of the Software.
  * 
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  * */
 class MX_Controller
 {

 	public $autoload = array();

 	public function __construct()
 	{
 		$class                                 = str_replace(CI::$APP->config->item('controller_suffix'), '', get_class($this));
 		log_message('debug', $class . " MX_Controller Initialized");
 		Modules::$registry[strtolower($class)] = $this;

 		/* copy a loader instance and initialize */
 		$this->load = clone load_class('Loader');
 		$this->load->initialize($this);

 		/* autoload module items */
 		$this->load->_autoloader($this->autoload);

 		$this->segmento = $this->session->userdata('NOMBRE_SEGMENTO')?$this->session->userdata('NOMBRE_SEGMENTO'):'Agencia';

 		$this->load->model(['empresas/Empresa', 'textos/Texto', 'instancias/Instancia']);
 	}

 	public function __get($class)
 	{
 		return CI::$APP->$class;
 	}

     /**
      * Campos de control para inserción o edición de registros en la base de datos - Jaime.
      * 
      * @param bolean $activo. Si va quitar el BOL_ACTIVO.
      * @return array 
      */
     public function get_campos_control_DB($no_activo = null, $no_delete = null)
     {
     	$data = [
           //'COD_CREAUSU' => $this->session->userdata('user_id'), //$this->current_user->user_id,
           'COD_CREAUSU'  => 1, //$this->current_user->user_id,
           'FEC_CREACION' => date("Y-m-d H:i:s"),
           'TEX_CREANOTA' => $this->input->ip_address(),
           'BOL_ACTIVO'   => '1',
           'IS_DELETE'    => '0',
        ];

        if ($no_activo) {
        	unset($data['BOL_ACTIVO']);
        }
        if ($no_delete) {
        	unset($data['IS_DELETE']);
        }

        return $data;
     }

     public function redirect_no_login()
     {
     	redirect('usuarios/login');
     }

     public function redirect_no_login_sufragantes()
     {
     	redirect('acceso/login');
     }

     /**
      * Lectura de archivos CSV.
      * 
      * @param type $filename
      * @param type $delimiter
      * @return array
      */
     function csv_to_array($filename = '', $delimiter = ';')
     {
     	if (!file_exists($filename) || !is_readable($filename)) return false;

     	$data   = array();
     	if (($handle = fopen($filename, 'r')) !== FALSE) {
     		while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
     			$data[] = $row;
     		}
     		fclose($handle);
     	}
     	return $data;
     }

//------------------------------------------------------------------------------ 

     /**
      * Inicialización de la librería de desencriptado. 
      */
     public function ini_desencriptado()
     {
     	$this->load->library('encryption');
     	$this->encryption->initialize(
     		array(
     			'cipher' => 'aes-256',
     			'mode'   => 'cbc',
     			'key'    => $this->config->item('encryption_key')
     		)
     	);
     }

//------------------------------------------------------------------------------ 

     /**
      * Desencripta un string.
      * 
      * @param type $texto
      * @return type
      */
     public function desencriptar_texto($texto)
     {
     	return $this->encryption->decrypt($texto);
     }

//------------------------------------------------------------------------------ 

     /**
      * Encripta un string.
      * 
      * @param type $texto
      * @return type
      */
     public function encriptar_texto($texto)
     {
     	return $this->encryption->encrypt($texto);
     }

//------------------------------------------------------------------------------ 

     /**
      *  
      * 
      *  @param Array $array
      *  @param Obj $obj
      * @return Obj
      */
     private function _array_to_obj($array, &$obj)
     {
     	foreach ($array as $key => $value) {
     		if (is_array($value)) {
     			$obj->$key = new stdClass();
     			$this->_array_to_obj($value, $obj->$key);
     		}
     		else {
     			$obj->$key = $value;
     		}
     	}
     	return $obj;
     }

//------------------------------------------------------------------------------ 

     /**
      *  Array to Obj instancia
      * @param Array $array
      * @return Obj
      */
     public function array_to_object($array)
     {
     	$object = new stdClass();
     	return $this->_array_to_obj($array, $object);
     }

     /**
      * Para generar pin envío SMS. 
      */
     public function get_pin_sms($size = null)
     {
     	return mt_rand(1000, 9999);
     }

     /**
      * Para generar la fecha hora actual. 
      */
     public function get_fecha_hora_hoy()
     {
     	return date('Y-m-d H:i:s');
     }

     /**
      *  Para envío de Mail.
      * 
      * @param html $template
      * @param string $mail_type
      * @param string $to
      * @param type $from_mail
      * @param type $from_name
      * @param type $suject
      */
     public function sendMail($template, $to, $from_mail, $suject)
     {
     	$this->load->library('email');
     	$result = $this->email->from($from_mail)
     	->to($to)
     	->subject($suject)
     	->message($template)
     	->set_mailtype('html')
     	->send();
     	var_dump($result);
     	echo '<br />';
     	echo $this->email->print_debugger();

     	exit;
     }

     public function get_module_name()
     {
     	return $this->router->fetch_module();
     }

     /**
		Trae el ID de la empresa
	  */
		protected function get_empresa_id()
		{
			return $this->Empresa->get_id();
		}
		/**
		Trae texto del sistema
		*/
		protected function get_texto_sistema($valor)
		{    
			return $this->Texto->get_by(['TEX_VALOR'=>$valor]);

		}

/**
		Trae texto del sistema
		*/
		protected function get_valida_cierre_instancia()
		{    
			$instancia =  $this->Instancia->get_by(['BOL_ACTIVO'=>1, 'IS_DELETE'=>0]);
			if(!$instancia) {
				return false;
			}

			$fecha_instancia = $instancia->FEC_FINUSO;
			$fecha_hoy = date('Y-m-d H:i:s');
			if($fecha_hoy < $fecha_instancia) {
				return true;              
			}
			return false;
		}

	}
