<?php
namespace Store;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Files\File;

use CodeIgniter\I18n\Time;
use CodeIgniter\I18n\TimeDifference;

use Psr\Log\LoggerInterface;
use ClassPhpIco\PHP_ICO;

use OTPHP\TOTP;
use Base32\Base32;
use chillerlan\QRCode\QRCode;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

use Constant\ConstantHelper;
use StoreApp\DataAppHelper;

class DataHelper extends Controller {
	public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) {
		parent::initController($request, $response, $logger);
	}


	/***************************************************************
	*
	*			ALL							
	*
	***************************************************************/

	/**
	* função global retorna somente numeros de uma string
	* 
	* @version 1.0.0.0 - 2022-18-05
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	protected $dados = [];

	function DH_loadGlobalData() {
		$this->constantHelper	= new ConstantHelper;

		helper(['form', 'date', 'html', 'number', 'text', 'filesystem']); 
		
		$this->constantHelper->CNT_dataConstant();
		$data = array();

		if(!service('request')->isAJAX()) {
			$datetime	= new Time('now', 'America/Sao_Paulo', 'pt_BR');
			
			$class = str_replace(array('\\', '\\', '\\', '\\'), '/', service('router')->controllerName());
			$class = explode('/', $class);
			if(count($class) >= 4) {
				foreach ($class as $key => $cl) {
					$class[$key] = strtolower($cl);
				}

				$class = $class[4];
			}
			else {
				$class = "";
			}

			$data['MyUser'] = $this->DH_getCmsUser();

			if(isset($data['MyUser']) AND !empty($data['MyUser'])) {
				if($data['MyUser']->id == 1) {
					$data['MyMenu'] = $this->DH_getMenu();
				}
				else {
					$data['MyMenu'] = unserialize(base64_decode($data['MyUser']->menu));
				}
			}
			else {
				$data['MyMenu'] = null;
			}

			$data['seo'] 							= $this->DH_getSeo();
			$data['MyAncora'] 				= $this->DH_getAncoras();
			$data['MyCores'] 					= $this->DH_getCores();
			$data['MyConfigEmail'] 		= $this->DH_getEmailConfig();
			$data['MyConfig'] 				= $this->DH_getCmsConfig();
			$data['MyInstitucional'] 	= $this->DH_getInstitucional();
			$data['MyAjustes'] 				= $this->DH_getAjustes();
			$data['MyPlataforma']			= $this->DH_getPlataforma();

			if(isset($class) AND !empty($class)) {
				$data['MyModulo']					= $this->DH_getModulo($class, $data['MyMenu']);
				$data['MyMet'] 						= service('router')->methodName();
			}

			$data['conf_gerais'] 			= $data['MyConfig'];

			$data['nowUsDateTime'] 		= $datetime->format('Y-m-d H:i:s');
			$data['nowUsDate'] 				= $datetime->format('Y-m-d');
			$data['nowUsTime'] 				= $datetime->format('H:i:s');

			$data['nowBrDateTime'] 		= $datetime->format('d-m-Y H:i:s');
			$data['nowBrDate'] 				= $datetime->format('d-m-Y');
			$data['nowBrTime'] 				= $datetime->format('H:i:s');

			$data['versionDate'] 			= $datetime->format('YmdHis') . "1x";

			if(isset($data['MyModulo']) AND !empty($data['MyModulo'])) {
				if (strpos($data['MyModulo']->url_amigavel, '/') !== false) {
					$MyModuloExplode 	= explode('/', $data['MyModulo']->url_amigavel);
					$data['MyMod'] 		= $MyModuloExplode[0];
				} 
				else {
					$data['MyMod'] = $data['MyModulo']->url_amigavel;
				}
			}
			else {
				$data['MyMod'] = "";	
			}

			$data['MyMonths'] =  array(
				1 => 'Janeiro',
				2 => 'Fevereiro',
				3 => 'Março',
				4 => 'Abril',
				5 => 'Maio',
				6 => 'Junho',
				7 => 'Julho',
				8 => 'Agosto',
				9 => 'Setembro',
				10 => 'Outubro',
				11 => 'Novembro',
				12 => 'Dezembro'
			);

			$this->DH_createXML();

			$fileExists 				 		= $this->DH_validFiles();
			$data['fileExists'] 		= $fileExists;
		}
		else {
			$data['MyUser'] = $this->DH_getCmsUser();
		}

		return $data;
	}

	/**
	* função global retorna somente numeros de uma string
	* 
	* @version 1.0.0.0 - 2022-18-05
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	function DH_loadGlobalDataOnError() {
		$this->constantHelper	= new ConstantHelper;

		$this->constantHelper->CNT_dataConstant();
		$data = array();

		$datetime	= new Time('now', 'America/Sao_Paulo', 'pt_BR');

		$data['MyUser'] = $this->DH_getCmsUser();

		if(isset($data['MyUser']) AND !empty($data['MyUser'])) {
			if($data['MyUser']->id == 1) {
				$data['MyMenu'] = $this->DH_getMenu();
			}
			else {
				$data['MyMenu'] = unserialize(base64_decode($data['MyUser']->menu));
			}
		}
		else {
			$data['MyMenu'] = null;
		}

		$data['seo'] 							= $this->DH_getSeo();
		$data['MyAncora'] 				= $this->DH_getAncoras();
		$data['MyCores'] 					= $this->DH_getCores();
		$data['MyConfigEmail'] 		= $this->DH_getEmailConfig();
		$data['MyConfig'] 				= $this->DH_getCmsConfig();
		$data['MyInstitucional'] 	= $this->DH_getInstitucional();
		$data['MyAjustes'] 				= $this->DH_getAjustes();
		$data['MyPlataforma']			= $this->DH_getPlataforma();

		$data['MyMet'] 						= service('router')->methodName();

		$data['conf_gerais'] 			= $data['MyConfig'];

		$data['nowUsDateTime'] 		= $datetime->format('Y-m-d H:i:s');
		$data['nowUsDate'] 				= $datetime->format('Y-m-d');
		$data['nowUsTime'] 				= $datetime->format('H:i:s');

		$data['nowBrDateTime'] 		= $datetime->format('d-m-Y H:i:s');
		$data['nowBrDate'] 				= $datetime->format('d-m-Y');
		$data['nowBrTime'] 				= $datetime->format('H:i:s');

		$data['versionDate'] 			= $datetime->format('YmdHis') . "1x";

		if(isset($data['MyModulo']) AND !empty($data['MyModulo'])) {
			$data['MyMod'] = $data['MyModulo']->url_amigavel;
		}
		else {
			$data['MyMod'] = "";	
		}

		$data['MyMonths'] =  array(
			1 => 'Janeiro',
			2 => 'Fevereiro',
			3 => 'Março',
			4 => 'Abril',
			5 => 'Maio',
			6 => 'Junho',
			7 => 'Julho',
			8 => 'Agosto',
			9 => 'Setembro',
			10 => 'Outubro',
			11 => 'Novembro',
			12 => 'Dezembro'
		);

		return $data;
	}

	/***************************************************************
	*
	*			ALL							
	*
	***************************************************************/

	/**
	* função global retorna somente numeros de uma string
	* 
	* @version 1.0.0.0 - 2022-18-05
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	function DH_soNumero($str) {
		return preg_replace("/[^0-9]/", "", $str);
	}

	/**
	* Formata o valor de BRL para o valor universal ( SQL )
	* 
	* @version 1.0.0.0 - 2023-06-27
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	function DH_convertBRLtoUSD($valor) {
		if(strpos($valor, 'R$ ') !== FALSE) {
			str_replace('R$ ', '', $valor);
		}

		if(strpos($valor, ',') !== FALSE) {
			$valor = str_replace(" ", "", $valor);
			$valor = str_replace(".", "", $valor);
			$valor = str_replace(",", ".", $valor);
		}
	}

	/**
	* função global que recebe uma string serializada
	* 
	* @version 1.0.0.0 - 2022-18-05
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	function DH_isSerialized( $data, $strict = true ) {
		if ( ! is_string( $data ) ) {
			return false;
		}

		$data = trim( $data );
		
		if ( 'N;' === $data ) {
			return true;
		}
		
		if ( strlen( $data ) < 4 ) {
			return false;
		}
		
		if ( ':' !== $data[1] ) {
			return false;
		}
		
		if ( $strict ) {
			$lastc = substr( $data, -1 );

			if ( ';' !== $lastc && '}' !== $lastc ) {
				return false;
			}
		} 
		else {
			$semicolon = strpos( $data, ';' );
			$brace     = strpos( $data, '}' );

			if ( false === $semicolon && false === $brace ) {
				return false;
			}

			if ( false !== $semicolon && $semicolon < 3 ) {
				return false;
			}

			if ( false !== $brace && $brace < 4 ) {
				return false;
			}
		}

		$token = $data[0];

		switch ( $token ) {
			case 's':
			if ( $strict ) {
				if ( '"' !== substr( $data, -2, 1 ) ) {
					return false;
				}
			} 
			elseif ( false === strpos( $data, '"' ) ) {
				return false;
			}
			case 'a':
			case 'O':
			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
			case 'b':
			case 'i':
			case 'd':
			$end = $strict ? '$' : '';
			return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
		}

		return false;
	} 

	/**
	* função global que recebe uma string em base64 ou serializada
	* 
	* @version 1.0.0.0 - 2022-18-05
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	public function DH_isBase64($str){
		if (!empty($str) && isset($str)) {
			if (is_array($str)) {
				return $str;
			}

			if ($this->DH_isSerialized($str)) {
				return unserialize($str);
			}
			elseif (is_string($str) && @base64_encode(base64_decode($str, true)) === $str) {
				$str = base64_decode($str);

				if ($this->DH_isSerialized($str)) {
					$str = unserialize($str);
				}

				return $str;
			}
			else {
				return $str;
			}
		}
	}

	/**
	* função global que coloca todas as keys em minusculo
	* 
	* @version 1.0.0.0 - 2022-08-05
	* 
	* @param não definido ainda
	* 
	* @return não definido ainda
	*/ 

	public function DH_arrayKeysToLowercase($data) {
		if (is_array($data) || is_object($data)) {
			$lowercaseData = [];

			foreach ($data as $key => $value) {
				if (is_array($value) || is_object($value)) {
					$value = $this->DH_arrayKeysToLowercase($value);
				}

				$lowercaseKey 									= strtolower($key);
				$lowercaseData[$lowercaseKey] 	= $value;
			}

			return $lowercaseData;
		} 
		else {
			return $data;
		}
	}

	/**
	* Mantem apenas letras e números na string.
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param $string string 
	* 
	* @return string
	*/ 

	function DH_cleanString($string) {
		$string = trim($string);
		$string = preg_replace(
			array(
				"/(á|à|ã|â|ä)/",
				"/(Á|À|Ã|Â|Ä)/",
				"/(é|è|ê|ë)/",
				"/(É|È|Ê|Ë)/",
				"/(í|ì|î|ï)/",
				"/(Í|Ì|Î|Ï)/",
				"/(ó|ò|õ|ô|ö)/",
				"/(Ó|Ò|Õ|Ô|Ö)/",
				"/(ú|ù|û|ü)/",
				"/(Ú|Ù|Û|Ü)/",
				"/(ñ)/",
				"/(Ñ)/",
				"/(Ç|ç)/"
			),
			explode(" ", "a A e E i I o O u U n N C c"), $string
		);

		$string = str_replace(' ', '-', $string);
		return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
	}

	/**
	* Verificar se existe cadastro duplicado.
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param $table 	string 
	* @param $index 	string 
	* @param $value 	string 
	* @param $id 			int 
	* 
	* @return string
	*/ 

	public function DH_checkDuplicate($table, $index, $value, $id) {
		$db 			= \Config\Database::connect();;
		$builder  = $db->table($table);
		
		$builder->where($index, $value);

		$query    = $builder->get();
		$consulta = $query->getRow();

		if(isset($consulta) AND !empty($consulta)) {
			if($consulta->id == $id) {
				return $value;
			}
			else {
				return random_string('md5', 12);
			}
		}
		else {
			return $value;
		}
	}

	/**
	* Verificar o link enviado do vídeo ( YouTube )
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param $url string 
	* 
	* @return string
	*/ 

	public function DH_extractYouTubeID($url) {
		$patterns = [
			'/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/',
			'/(?:https?:\/\/)?(?:www\.)?youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)?([a-zA-Z0-9_-]{11})/'
		];

		foreach ($patterns as $pattern) {
			if (preg_match($pattern, $url, $matches)) {
				return $matches[1];
			}
		}

		return $url;
	}

	/**
	* Verificar se existe cadastro duplicado.
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param $table 	string 
	* @param $index 	string 
	* @param $value 	string 
	* @param $id 			int 
	* 
	* @return string
	*/ 

	public function DH_checkDuplicateRegister($table, $index, $value, $id) {
		helper('text');
		
		$check 						= true;
		$checkPercentage 	= 0;
		$checkID 					= 0;

		$db 			= \Config\Database::connect();;
		$builder  = $db->table($table);
		$query    = $builder->get();
		$results 	= $query->getResult();

		if(isset($results) AND !empty($results)) {
			foreach ($results as $key => $result) {
				if(!empty($result->url_amigavel)) {
					$string1 = $value;
					$string2 = $result->url_amigavel;

					$string1 = mb_strtolower($string1);
					$string2 = mb_strtolower($string2);

					$distance = levenshtein($string1, $string2);

					$max_length = max(mb_strlen($string1), mb_strlen($string2));
					$percentage = ((1 - ($distance / $max_length)) * 100);

					if($percentage >= 55) {
						$check 						= false;
						$checkPercentage 	= $percentage;
						$checkID 					= $result->id;
					}
				}
			}

			if($check) {
				$ret = array(
					'status' => 1,
					'data' 	 => $value,
					'msg'		 => 'Nome de usuário criado com sucesso'
				);
			}
			else {
				if($checkID == $id) {
					$ret = array(
						'status' => 1,
						'data' 	 => $value,
						'msg'		 => 'Nome de usuário atualizado com sucesso'
					);
				}
				else {
					$ret = array(
						'status' => 0,
						'data' 	 => '',
						'msg'		 => 'Nome de usuário não pode ser utilizado, taxa de similaridade: ' . $percentage . '%'
					);
				}
			}
		}

		return $ret;
	}

	/**
	* Faz o login usando o token de acesso
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param $token 	string 
	* 
	* @return string
	*/ 

	public function DH_getuserAccessData($currentUserID, $token) {
		$db 			= \Config\Database::connect();

		$table 		= "cms_usuario";
		$builder  = $db->table($table);
		$builder->where("token_access", $token);
		$query    = $builder->get();
		$user 		= $query->getRow();

		$currentUserID 	= unserialize(base64_decode($currentUserID));
		$table 			 		= "cms_usuario";
		$builder 	   		= $db->table($table);
		$builder->where("id", $currentUserID);
		$query    	 		= $builder->get();
		$currentUser 		= $query->getRow();

		if((isset($user) AND !empty($user)) AND (isset($currentUser) AND !empty($currentUser))) {
			if(empty($user->permissoes)) {
				$table 	 = "cms_usuario_categorias";
				$result  = $db->table($table)->where('id', $user->id_categoria)->get()->getRow();

				$permissoes 				= unserialize(base64_decode($result->permissoes));
				$idModuloCategoria 	= $permissoes['idModuloCategoria'];
				$idModulo 					= $permissoes['idModulo'];

				$moduloCadastrar		= $permissoes['moduloCadastrar'];
				$moduloEditar				= $permissoes['moduloEditar'];
				$moduloSalvar				= $permissoes['moduloSalvar'];
				$moduloExcluir			= $permissoes['moduloExcluir'];
				$moduloLote					= $permissoes['moduloLote'];
				$moduloDashboard		= "";

				if(isset($idModuloCategoria) AND !empty($idModuloCategoria)) {
					foreach ($idModuloCategoria as $keyCategoria => $categoria) {
						$dadosModulosCategoria[$keyCategoria] = $this->DH_getDadosModulosCategoria($categoria);
						$dadosModulos 												= $this->DH_getDadosModulos($dadosModulosCategoria[$keyCategoria]->id, $idModulo);

						foreach ($dadosModulos as $keyModulo => $modulo) {
							if(isset($moduloCadastrar) AND !empty($moduloCadastrar) AND in_array($modulo->id . "-1", $moduloCadastrar)) {
								$modulo->cadastrar = 1;
							}
							else {
								$modulo->cadastrar = 0;
							}

							if(isset($moduloEditar) AND !empty($moduloEditar) AND in_array($modulo->id . "-1", $moduloEditar)) {
								$modulo->editar = 1;
							}
							else {
								$modulo->editar = 0;
							}

							if(isset($moduloSalvar) AND !empty($moduloSalvar) AND in_array($modulo->id . "-1", $moduloSalvar)) {
								$modulo->salvar = 1;
							}
							else {
								$modulo->salvar = 0;
							}

							if(isset($moduloExcluir) AND !empty($moduloExcluir) AND in_array($modulo->id . "-1", $moduloExcluir)) {
								$modulo->excluir = 1;
							}
							else {
								$modulo->excluir = 0;
							}

							if(isset($moduloLote) AND !empty($moduloLote) AND in_array($modulo->id . "-1", $moduloLote)) {
								$modulo->lote = 1;
							}
							else {
								$modulo->lote = 0;
							}

							if(isset($moduloDashboard) AND !empty($moduloDashboard) AND in_array($modulo->id . "-1", $moduloDashboard)) {
								$modulo->dashboard = 1;
							}
							else {
								$modulo->dashboard = 0;
							}

							$dadosModulosCategoria[$keyCategoria]->submenu = $dadosModulos;
						}
					}
				}

				if((isset($idModuloCategoria) AND !empty($idModuloCategoria)) AND (isset($idModulo) AND !empty($idModulo))) {
					$ar = array(
						'idModuloCategoria' 	=> $idModuloCategoria, 
						'idModulo' 						=> $idModulo,
						'moduloCadastrar' 		=> $moduloCadastrar,
						'moduloEditar' 				=> $moduloEditar,
						'moduloSalvar' 				=> $moduloSalvar,
						'moduloExcluir' 			=> $moduloExcluir,
						'moduloLote' 					=> $moduloLote,
						'moduloDashboard'			=> $moduloDashboard
					);

					$table 					 = "cms_usuario";
					$updPermissions  = $db->table($table);
					$updPermissions->set('menu', base64_encode(serialize($dadosModulosCategoria)));
					$updPermissions->set('permissoes', base64_encode(serialize($ar)));
					$updPermissions->where('id', $user->id);
					$updPermissions->update();
				}
			}

			service('session')->set('modulos_permite_acesso', 1);
			service('session')->set('usuario_logado', 1);
			service('session')->set('usuario_origem', $currentUser);
			service('session')->set('usuario', $user);

			$data = [
				'id_usuario' 			=> $currentUser->id,
				'modulo'  	 			=> 'Login',
				'metodo'  				=> 'Login',
				'id_item'  				=> 0,
				'descricao'  			=> "O usuário <b>" . $currentUser->titulo . "</b> acessou o painel com os dados do usuário <b>" . $user->titulo . "</b>",
				'ativo'  					=> 1,
				'data_cadastro'  	=> date("Y-m-d H:i:s")
			];

			$table 		= "cms_auditoria";
			$builder  = $db->table($table);
			$query    = $builder->insert($data);

			return redirect()->to('/pagina-inicial');
		}
		else {
			die("------------------------------------------------------------[ x ]");
		}
	}

	/**
	* Adiciona a view contendo os campos de contatos do WhatsApp.
	* 
	* @version 1.0.0.0 - 2022-11-11
	* 
	* @uses $_POST['num']		ajax
	*/

	public function DH_getDadosModulosCategoria($id) {
		$db 			= \Config\Database::connect();
		$table 		= "cms_modulos_categorias";
		$builder  = $db->table($table)->where('id', $id);
		$query    = $builder->get();
		$result 	= $query->getRow();

		$result->submenu = array();

		return $result;
	}

	/**
	* Adiciona a view contendo os campos de contatos do WhatsApp.
	* 
	* @version 1.0.0.0 - 2022-11-11
	* 
	* @uses $_POST['num']		ajax
	*/

	public function DH_getDadosModulos($id, $modulos) {
		$db 			= \Config\Database::connect();
		$table 		= "cms_modulos";
		$builder  = $db->table($table)->where('id_categoria', $id)->whereIn('id', $modulos);
		$query    = $builder->get();
		$result 	= $query->getResult();

		return $result;
	}

	/**
	* Adiciona a view contendo os campos de contatos do WhatsApp.
	* 
	* @version 1.0.0.0 - 2022-11-11
	* 
	* @uses $_POST['num']		ajax
	*/

	public function DH_ajaxAddWhatsApp() {
		$num 					= service('request')->getPost('num');
		$dados['num'] = $num;
		$viewPath 		= "Modules\\Cad_institucional\\Views\\view_cad_institucional_whatsapp";

		echo view($viewPath, $dados);
	}

	/**
	* Define os módulos para geração do SEO e dos arquivos XML, Sitemaps...
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param 	array $contentDynamic 
	* @param 	array $contentFixed 
	* @param 	array $contentExcluded 
	* 
 	* @return object
	*/

 	function DH_getContents() {

 		/*
 		* Modules
 		*/

 		$content = new \stdClass;

 		$content->excluded = array(
 		);

 		$content->dynamic = array(
 		);

 		$content->fixed = array(
 			'cms' => array(
 				'table' 			=> 'cad_seo',
 				'column' 			=> 'url',
 				'folder' 			=> 'upload_cad_seo',
 				'subfolder'		=> 'item_'
 			),
 			'conheca-a-kits' => array(
 				'table' 			=> 'cad_seo',
 				'column' 			=> 'url',
 				'folder' 			=> 'upload_cad_seo',
 				'subfolder'		=> 'item_'
 			)
 		);

 		return $content;
 	}

 	/**
	* Pega os dados para preenchimentos dos metatags ( seo ).
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getSeo() {

 		/*
 		* Dados institucionais
 		*/

 		$institucional = $this->DH_getInstitucional();

 		$seo = array(
 			'title'				=> '',
 			'description'	=> '',
 			'keywords'		=> '',
 			'canonical'		=> '',
 			'author'			=> '',
 			'url'					=> '',
 			'image'				=> '',
 			'alt'					=> '',
 			'site_name'		=> ''
 		);

 		$db = \Config\Database::connect();

 		$uri = service('uri');
 		$segments = $uri->getSegments();

 		$uri_0 		= @$segments[0];
 		$uri_1 		= @$segments[1];
 		$uri_2 		= @$segments[2];
 		$uri_3 		= @$segments[3];

 		$content  = $this->DH_getContents();

 		if(array_key_exists($uri_0, $content->fixed)) {
 			$data = $content->fixed[$uri_0];

 			if(isset($data) AND !empty($data)) {
 				$table 			= $data['table'];
 				$column 		= $data['column'];
 				$folder 		= $data['folder'];
 				$subfolder 	= $data['subfolder'];

 				$builder  = $db->table($table);
 				$builder->where($column, $uri_0);
 				$query    = $builder->get();
 				$result 	= $query->getRow(); 	

 				if(isset($result) AND !empty($result)) {
 					$seo['title'] 				= $result->titulo;
 					$seo['description'] 	= $result->descricao;
 					$seo['keywords'] 			= $result->tags;
 					$seo['canonical'] 		= BASEURL . $uri_0;
 					$seo['author'] 				= $result->autor;
 					$seo['url'] 					= BASEURL . $uri_0;
 					$seo['alt'] 					= $result->titulo;
 					$seo['site_name'] 		= $institucional->titulo; 

 					if(isset($subfolder) AND !empty($subfolder)) {
 						$seo['image'] = PUBLICURL . 'uploads/' . $folder . '/' . $subfolder . $result->id . '/' . $result->imagem;
 					}
 					else {
 						$seo['image'] = PUBLICURL . 'uploads/' . $folder . '/' . $result->imagem;
 					}
 				}
 			}	
 		}

 		if(array_key_exists($uri_0, $content->dynamic) AND !empty($uri_1)) {
 			$data = $content->dynamic[$uri_0];

 			if(isset($data) AND !empty($data)) {
 				$table 			= $data['table'];
 				$column 		= $data['column'];
 				$folder 		= $data['folder'];
 				$subfolder 	= $data['subfolder'];
 				$category 	= $data['category'];

 				if(isset($category) AND !empty($category) AND $category['url'] == $uri_1) {
 					$table 			= $category['table'];
 					$column 		= $category['column'];
 					$folder 		= $category['folder'];
 					$subfolder 	= $category['subfolder'];

 					$builder  = $db->table($table);
 					$builder->where($column, $uri_2);
 					$query    = $builder->get();
 					$result 	= $query->getRow(); 	
 				}
 				else {
 					$builder  = $db->table($table);
 					$builder->where($column, $uri_1);
 					$query    = $builder->get();
 					$result 	= $query->getRow(); 	
 				}

 				if(isset($result) AND !empty($result)) {
 					$seo['title'] 				= $result->seo_titulo;
 					$seo['description'] 	= $result->seo_descricao;
 					$seo['keywords'] 			= $result->seo_tags;
 					$seo['canonical'] 		= BASEURL . $uri_0;
 					$seo['author'] 				= $result->seo_autor;
 					$seo['url'] 					= BASEURL . $uri_0 . '/' . $uri_1 . '/' . $uri_2;
 					$seo['alt'] 					= $result->seo_titulo;
 					$seo['site_name'] 		= $institucional->titulo; 

 					if(isset($subfolder) AND !empty($subfolder)) {
 						$seo['image'] = PUBLICURL . 'uploads/' . $folder . '/' . $subfolder . $result->id . '/' . $result->seo_imagem;
 					}
 					else {
 						$seo['image'] = PUBLICURL . 'uploads/' . $folder . '/' . $result->seo_imagem;
 					}
 				}	
 			}
 		}

 		if(array_key_exists($uri_0, $content->excluded)) {
 			$result = "";
 		}

 		/*
 		* Default
 		*/

 		if(empty($result)) {
 			$table 			= 'cad_seo';
 			$column 		= 'url';
 			$folder 		= 'upload_cad_seo';
 			$subfolder 	= 'item_';

 			$builder  = $db->table($table);

 			if($uri_0 == "") {
 				$builder->where($column, '');
 				$query    = $builder->get();
 				$result 	= $query->getRow(); 
 			}
 			elseif($uri_0 != "") {
 				$builder->where($column, $uri_0);
 				$query    = $builder->get();
 				$result 	= $query->getRow(); 
 			}
 			
 			if($result == "") {
 				$builder->where($column, 'default');
 				$query    = $builder->get();
 				$result 	= $query->getRow(); 
 			}

 			$seo['title'] 				= $result->titulo;
 			$seo['description'] 	= $result->descricao;
 			$seo['keywords'] 			= $result->tags;
 			$seo['canonical'] 		= BASEURL . $uri_0;
 			$seo['author'] 				= $result->autor;
 			$seo['url'] 					= BASEURL . $uri_0;
 			$seo['alt'] 					= $result->titulo;
 			$seo['site_name'] 		= $institucional->titulo;

 			if(isset($subfolder) AND !empty($subfolder)) {
 				$seo['image'] = PUBLICURL . 'uploads/' . $folder . '/' . $subfolder . $result->id . '/' . $result->imagem;
 			}
 			else {
 				$seo['image'] = PUBLICURL . 'uploads/' . $folder . '/' . $result->imagem;
 			}
 		}

 		return (object) $seo;
 	}

	/**
	* Pega todos os cadastros da tabela cad_ancora;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getAncoras() {
 		$db 			= \Config\Database::connect();

 		$table 		= "cad_ancora";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		$consulta = $query->getResult();

 		$lista 		= array();

 		foreach($consulta as $valor) {
 			$lista[$valor->atalho] = $valor;
 		}

 		return $lista;
 	}

	/**
	* Pega as três cores principais, para serem usadas na customização do painel.
	* São usadas na view_topo_assets:
	* 
	* --color-custom-primary
	* --color-custom-secondary
	* --color-custom-tertiary
	* 
	* @version 1.0.0.0 - 2022-07-16
	*
 	* @return object
	*/

 	function DH_getCores() {
 		$db 			= \Config\Database::connect();

 		$table 		= "conf_cores";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

	/**
	* Pega as configurações para envio de email;
	* 
	* @version 1.0.0.0 - 2023-02-10
	* 
 	* @return object
	*/

 	function DH_getEmailConfig() {
 		$db 			= \Config\Database::connect();

 		$table 		= "conf_email";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

 	/**
	* Pega as configurações para envio de email;
	* 
	* @version 1.0.0.0 - 2023-02-10
	* 
 	* @return object
	*/

 	function DH_getCmsConfig() {
 		$db 			= \Config\Database::connect();

 		$table 		= "cms_conf_gerais";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

	/**
	* Pega os dados institucionais;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getInstitucional() {
 		$db 			= \Config\Database::connect();

 		$table 		= "cad_institucional";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

 	/**
	* Pega os textos e imagens dos blocos
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getTextos() {
 		$db 			= \Config\Database::connect();

 		$table 		= "cad_textos";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

	/**
	* Pega todos os cadastros da tabela cad_ancora;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getInstitucionalTextos() {
 		$db 	  	= \Config\Database::connect();

 		$table 	  = "cad_institucional_textos";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

	/**
	* Pegas os pixels cadastrados em cad_pixels;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getPixel() {
 		$db 	  	= \Config\Database::connect();

 		$table 	  = "cad_pixel";
 		$builder  = $db->table($table);

 		$builder->where('ativo', '1');
 		$builder->orderBy('posicao', 'ASC');

 		$query    = $builder->get();

 		return $query->getResult();
 	}

	/**
	* Pegas os dados cadastrados em cad_modulos;
	* Este módulo é usado normalmente para criação de campos 
	* para customização de informações do projetos que não fazem 
	* parte das tabaelas de cadastros.
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getModGeral() {
 		$db 	  = \Config\Database::connect();

 		$table 	  = "cad_modulos";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

	/**
	* Pegas os dados cadastrados em conf_ajustes;
	* Este módulo é usado normalmente definição da largura e altura
	* dos logos, do topo e/ou rodapé.
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return object
	*/

 	function DH_getAjustes() {
 		$db 			= \Config\Database::connect();

 		$table 		= "conf_ajustes";
 		$builder  = $db->table($table);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

	/**
	* Pega a vídeo aula cadastradas em res_videos do módulo solicitado;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param 	string $modulo 
	* 
 	* @return object
	*/

 	function DH_getTreinamento($modulo) {
 		$db 			= \Config\Database::connect();

 		$table 		= "res_videos";
 		$builder  = $db->table($table)->where('modulo', $modulo)->where('ativo', 1);
 		$query    = $builder->get();

 		return $query->getRow();
 	}

 	/**
	* Pega os segmentos da URL
	* 
	* @version 1.0.0.1 - 2022-07-18
	* 
 	* @return object
	*/

 	function DH_getSegments() {
 		$uri 		= current_url(true)->getSegments();
 		$index 	= array_search('cms', $uri);

 		if ($index !== false) {
 			$uriNew = array_slice($uri, $index);
 		} 

 		return $uriNew;
 	}

 	/**
	* Pega a classe
	* 
	* @version 1.0.0.1 - 2022-07-18
	* 
 	* @return object | false
	*/

 	function DH_getClass() {
 		$classe 		= str_replace(array('\\', '\\', '\\', '\\'), '/', service('router')->controllerName());
 		$classe 		= explode('/', $classe);

 		foreach ($classe as $key => $cl) {
 			$cl = strtolower($cl);
 		}

 		return $cl;
 	}

 	/**
	* Pega os dados da plataforma ativada
	* 
	* @version 1.0.0.0 - 2022-11-11
	* 
	* @uses $_POST['num']		ajax
	*/

	public function DH_getPlataforma() {
		$db 			= \Config\Database::connect();
		$table 		= "cms_plataformas";
		$builder  = $db->table($table);

		$builder->where('ativo', 1);
		
		$query    = $builder->get();
		$result 	= $query->getRow();

		return $result;
	}

	/***************************************************************
	*
	*			MENU
	*
	***************************************************************/

	/**
	* Pega os dados do módulo solicitado pela URL amigável;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param 	string $modulo 
	* 
	* @return object
	*/

	function DH_getModuloByURL($modulo, $menus = null) {
		if(isset($menus) AND !empty($menus)) {
			foreach ($menus as $keyM => $menu) {
				foreach ($menu->submenu as $key => $sub) {
					if($sub->nome == $modulo) {
						return $sub;
					}
				}
			}
		}
		else {
			$db					= \Config\Database::connect();
			$builder 		= $db->table('cms_modulos')->where('url_amigavel', $modulo);
			$query    	= $builder->get();
			$modulo 		= $query->getRow();

			return $modulo;
		}
	}

	/**
	* Pega os dados do módulo solicitado;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param 	string $modulo 
	* 
	* @return object
	*/

	function DH_getModulo($modulo, $menus = null) {
		if(isset($menus) AND !empty($menus)) {
			foreach ($menus as $keyM => $menu) {
				if(isset($menu->submenu) AND !empty($menu->submenu)) {
					foreach ($menu->submenu as $key => $sub) {
						if($sub->nome == $modulo) {
							return $sub;
						}
					}
				}
			}
		}
		else {
			$db					= \Config\Database::connect();
			$builder 		= $db->table('cms_modulos')->where('nome', $modulo);
			$query    	= $builder->get();
			$modulo 		= $query->getRow();

			return $modulo;
		}
	}

	/**
	* Pega os dados do usuário na sessão
	* 
	* @version 1.0.0.1 - 2022-07-18
	* 
	* @return object | false
	*/

	function DH_getCmsUser() {
		$db = \Config\Database::connect();
		$u  = service('session')->get('usuario');

		if(isset($u) AND !empty($u)) {
			$table 		= "cms_usuario";
			$builder  = $db->table($table)->where('id', $u->id);
			$query    = $builder->get();
			$result 	= $query->getRow();

			service('session')->set('usuario', $result);

			return $result;
		}
		else {
			return false;
		}
	}

	/**
	* Pega os dados do usuário na sessão
	* 
	* @version 1.0.0.1 - 2022-07-18
	* 
	* @return object | false
	*/

	function DH_getCmsUserByID($id) {
		$db = \Config\Database::connect();

		$table 		= "cms_usuario";
		$builder  = $db->table($table)->where('id', $id);
		$query    = $builder->get();
		$result 	= $query->getRow();

		return $result;
	}

	/**
	* Função responsável por montar o menu lateral esquerdo do Painel CMS;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @return object
	*/

	function DH_getMenu() {
		if(!empty(service('session')->get('usuario'))) { 
			$db					= \Config\Database::connect();

			$builder 		= $db->table('cms_modulos_categorias')->where('ativo', 1);
			$query    	= $builder->get();
			$categorias = $query->getResult();

			$builder 		= $db->table('cms_modulos')->where('ativo', 1);
			$query    	= $builder->get();
			$modulos 		= $query->getResult();

			/*
			* Monta o menu
			*/

			foreach ($categorias as $key => $categoria) {
				foreach ($modulos as $key => $modulo) {
					if(isset($modulo->id_categoria) AND isset($categoria->id) AND $modulo->id_categoria == $categoria->id) {
						if($modulo->thirdmenu == 0) {
							$categoria->submenu[] = $modulo;
						}

						if($modulo->thirdmenu == 1) {
							$categoria->thirdmenu[] = $modulo;
						}
					}
				}

				if(isset($categoria->submenu) AND !empty($categoria->submenu)) {
					usort($categoria->submenu, fn($a, $b) => strcmp(sprintf("%05d", $a->ordem), sprintf("%05d", $b->ordem)));
				}
			}

			return $categorias;
		}
	}

	/***************************************************************
	*
	*			FILES 
	*
	***************************************************************/

	/**
	* Criar o arquivo sitemap.xml;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return int | int
	*/

 	function DH_createXML() {
 		$db = \Config\Database::connect();
 		$conf_gerais 		= $this->DH_getCmsConfig();

		/*
		* Verifica se o arquivo existe
		*/

		$file 		  = 'sitemap.xml';
		$filePath 	= ROOTPATH . $file;

		if (!file_exists($filePath)) {
			fopen($filePath, "w");
		}

		$dateCurrent  = date("Y-m-d");
		$dateModified = date("Y-m-d", filemtime($filePath));

		if($dateCurrent > $dateModified) {

			/*
			* Cria os linkas para o URL List
			*/

			$linksList = "";

			/*
			* Cria os links com conteúdos dinâmicos
			*/

			$linksDynamic = array();
			$dynamics 		= $this->DH_getContents()->dynamic;

			foreach ($dynamics as $key => $dynamic) {
				$table 		= $dynamic['table'];
				$builder  = $db->table($table)->select($dynamic['column'])->where('ativo', 1);
				$query    = $builder->get();

				$result 	= $query->getResult();

				foreach ($result as $k => $r) {
					$l = str_replace('cms/', '', site_url('')) . $dynamic['url'] . '/' . $r->url_amigavel;
					array_push($linksDynamic, $l);
				}
			}

			/*
			* Cria os links das páginas fixas (principais)
			*/

			$linksFixed = array();
			$fixeds 	= $this->DH_getContents()->fixed;

			foreach ($fixeds as $key => $fixed) {
				$l = str_replace('cms/', '', site_url('')) . $key;
				array_push($linksFixed, $l);
			}

			/*
			* Gera o XML
			*/

			$xmlContent = "";
			$xmlContent .= "<?xml version='1.0' encoding='UTF-8'?>";
			$xmlContent .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xsi:schemaLocation=" http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';

			$xmlContent .= "<url>";
			$xmlContent .= "<loc>" . str_replace('cms/', '', site_url('')) . "</loc>";
			$xmlContent .= "<lastmod>" . date('Y-m-d') . "</lastmod>";
			$xmlContent .= '<priority>1.0</priority>';
			$xmlContent .= "<changefreq>daily</changefreq>";
			$xmlContent .= "</url>";

			$linksList  .=  str_replace('cms/', '', site_url('')) . "\n";

			foreach ($linksFixed as $klf => $linkFixed) {
				$xmlContent .= "<url>";
				$xmlContent .= "<loc>" . $linkFixed . "</loc>";
				$xmlContent .= "<lastmod>" . date('Y-m-d') . "</lastmod>";
				$xmlContent .= '<priority>0.9</priority>';
				$xmlContent .= "<changefreq>daily</changefreq>";
				$xmlContent .= "</url>";

				$linksList  .=  $linkFixed . "\n";
			}

			foreach ($linksDynamic as $kld => $linkDynamic) {
				$xmlContent .= "<url>";
				$xmlContent .= "<loc>" . $linkDynamic . "</loc>";
				$xmlContent .= "<lastmod>" . date('Y-m-d') . "</lastmod>";
				$xmlContent .= '<priority>0.8</priority>';
				$xmlContent .= "<changefreq>daily</changefreq>";
				$xmlContent .= "</url>";

				$linksList  .=  $linkDynamic . "\n";
			}

			$xmlContent .= "</urlset>";

			/*
			* Gera o arquivo URL List.
			*/

			if(!empty($conf_gerais->form_urllist)){
				$this->DH_createURL($linksList);
			}

			if(!empty($conf_gerais->form_sitemap)){
				file_put_contents($filePath, $xmlContent);
			}

			return 1;
		}
		else {
			return 0;
		}
	}

	/**
	* Criar o arquivo urllist.txt;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param 	array $linksList os valores são enviados pela função DH_createXML
	* 
 	* @return int
	*/

 	function DH_createURL($linksList) {

		/*
		* Verifica se o arquivo existe
		*/

		$file     	= 'urllist.txt';
		$filePath 	= ROOTPATH . $file;

		if (!file_exists($filePath)) {
			fopen($filePath, "w");
		}

		file_put_contents($filePath, $linksList);
		return 1;
	}

	/**
	* Valida se existem os arquivos:
	* urllist.txt
	* sitemap.xml
	* robots.txt
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
 	* @return array
	*/

 	function DH_validFiles() {

		/*
		* Verifica se o arquivo existe
		*/

		$path 			= str_replace('cms', '', realpath('.'));

		$fileURL    = 'urllist.txt';
		$fileXML    = 'sitemap.xml';
		$fileROB    = 'robots.txt';

		$valid = array(
			'validFileURL' => 0,
			'validFileXML' => 0,
			'validFileROB' => 0
		);

		if (file_exists($path . $fileURL)) {
			$valid['validFileURL'] = date("d/m/Y", filemtime( $path . $fileURL ));
		}

		if (file_exists($path . $fileXML)) {
			$valid['validFileXML'] = date("d/m/Y", filemtime( $path . $fileXML ));
		}

		if (file_exists($path . $fileROB)) {
			$valid['validFileROB'] = date("d/m/Y", filemtime( $path . $fileROB ));
		}

		return $valid;
	}

	/***************************************************************
	*
	*			AJAX							
	*
	***************************************************************/

  /**
	* Muda o status do cadastro ( ativo/desativo );
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @uses $_POST['id'] 		 ajax
	* @uses $_POST['status'] ajax
	*/

	public function DH_ajaxChangeRegisterStatus() {
		$db = \Config\Database::connect();

		/*
		* $_POST
		*/

		$id		  	= service('request')->getPost('id');
		$status	  = service('request')->getPost('status');

		/*
		* Salva no banco de dados
		*/

		$table 		= service('request')->getPost('table');
		$column		= service('request')->getPost('column');
		$builder  = $db->table($table);

		if(isset($column) AND !empty($column)) {
			$builder->set($column, $status)->where('id', $id);
		}
		else {
			$builder->set('ativo', $status)->where('id', $id);
		}

		$this->DH_actionRecord($id);

		$builder->update();
	}

	/**
	* Adiciona os blocos de conteúdos extras
	* 
	* @version 1.0.0.0 - 2022-07-22
	* 
	* @uses $_POST['id'] 		 ajax
	* @uses $_POST['status'] ajax
	*/

	public function DH_ajaxExtraContent() {
		$orig = service('request')->getPost('orig');

		if ($orig == "app") {
			$cont 	= service('request')->getPost('cont');
			$mode 	= "model_" . service('request')->getPost('mode');
			$func 	= service('request')->getPost('func');
			$indx 	= service('request')->getPost('indx');
			$view 	= service('request')->getPost('view');
			$items 	= service('request')->getPost('items');

			if (isset($func) && !empty($func)) {
				$fullClassName = "\\Modules\\$cont\\Models\\$mode";

				if (class_exists($fullClassName)) {
					$db 	= \Config\Database::connect();
					$fun 	= array_filter(explode(';', $func));
					$ind 	= array_filter(explode(';', $indx));
					
					$modelInstance = new $fullClassName();

					foreach ($fun as $key => $f) {
						if (method_exists($modelInstance, $f)) {
							$dados[$ind[$key]] = call_user_func(array($modelInstance, $f));
						} 
						else {
							$result = "Método '$f' não encontrado na classe '$fullClassName'";
						}
					}
				} 
				else {
					$result = "Classe de modelo '$fullClassName' não encontrada";
				}	

				$dados['items'] 	= $items;
				$dados['action'] 	= "insert";
				$dados['imagem'] 	= "";
				$dados['ativo'] 	= 0;

				$dados = array_merge($this->DH_loadAppGlobalData(), $dados);

				$this->constantHelper	= new ConstantHelper;
				$this->constantHelper->CNT_dataConstant();

				$viewPath = "Modules\\" . $cont . "\Views\\" . $view;
				echo view($viewPath, $dados);
			}
		}
		else {
			$mod    			= service('request')->getPost('mod');
			$view   			= service('request')->getPost('view');
			$index  			= service('request')->getPost('index');
			$num    			= service('request')->getPost('num');
			$dados['num'] = $num;
			$viewPath 		= "Modules\\" . $mod . "\Views\\" . $view;

			echo view($viewPath, $dados);
		}
	}

	/**
	* Faz a exclusão de multiplos cadastros
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @uses $_POST ajax
	*/

	public function DH_ajaxBatchAction() {
		$db 			= \Config\Database::connect();

		$ids 			= service('request')->getPost('ids');
		$table 		= service('request')->getPost('table');
		$upload		= service('request')->getPost('upload');

		$total 		= count($ids);
		$module   = $this->DH_getModulo($table);

		foreach ($ids as $key => $id) {
			$builder = $db->table($table);

			$builder->where('id', $id);
			$builder->delete();

			$method = "Batch Delete";
			$msg 		= "deletou um cadastro no módulo <b>" . $module->titulo . "</b>. ID do cadastro: <b>" . $id . "</b>";
			$this->DH_actionRecordBatch($id, $method, $table, $msg);

			if(isset($upload) AND !empty($upload) AND $upload == 1) {
				$this->uploadHelper->UPH_deleteFolder('upload_' . $table, $id);

				$method = "Batch Delete";
				$msg 		= "deletou uma pasta de arquivos no módulo <b>" . $module->titulo . "</b>. ID do cadastro: <b>" . $id . "</b>";
				$this->DH_actionRecordBatch($id, $method, $table, $msg);
			}
		}
	}

	/**
	* Adiciona o child no dataTable
	* 
	* @version 1.0.0.1 - 2023-07-25
	* 
	* @uses $_POST['id']				ajax
	* @uses $_POST['mod']				ajax
	* @uses $_POST['table']			ajax
	* @uses $_POST['where']			ajax
	* @uses $_POST['type']			ajax
	* @uses $_POST['variable']	ajax
	* @uses $_POST['view']			ajax
	* @uses $_POST['inp']				ajax
	* @uses $_POST['api']				ajax
	* @uses $_POST['cla']				ajax
	*/

	public function DH_ajaxDataTableGetChilds() {
		$db = \Config\Database::connect();

		$id 				= service('request')->getPost('id');
		$mod 				= service('request')->getPost('mod');
		$tables 		= service('request')->getPost('table');
		$wheres 		= service('request')->getPost('where');
		$types 			= service('request')->getPost('type');
		$variables 	= service('request')->getPost('variable');
		$view 			= service('request')->getPost('view');
		$inp				= service('request')->getPost('inp');
		$api				= service('request')->getPost('api');
		$cla				= service('request')->getPost('cla');

		$tables 		= explode(';', $tables);
		$types 			= explode(';', $types);
		$wheres			= explode(';', $wheres);
		$variables	= explode(';', $variables);

		foreach ($tables as $key => $table) {
			$builder 	= $db->table($table);

			$builder->select('*');

			if(isset($wheres[$key]) AND !empty($wheres[$key]) AND $wheres[$key] != "none") {
				$builder->where($wheres[$key], $id);
			}

			if(isset($inp[$key]) AND !empty($inp[$key]) AND $inp[$key] != "none") {
				$queryDate 	= $inp[$key][0] . '-' . $inp[$key][1] . '-01';

				$firstDate 	= date('Y-m-01', strtotime($queryDate));
				$builder->where('data_format >= ', $firstDate);

				$lastDate 	= date('Y-m-t', strtotime($queryDate));
				$builder->where('data_format <= ', $lastDate);
			}

			$query = $builder->get();

			if($types[$key] == "getRow") {
				$dados[$variables[$key]] = $query->getRow();
			}
			elseif($types[$key] == "getResult") {
				$dados[$variables[$key]] = $query->getResult();
			}
			else {
				$dados[$variables[$key]] = $query->getResult();
			}
		}

		$MyUser = $this->DH_getCmsUser();

		if($MyUser->id == 1) {
			$MyMenu = $this->DH_getMenu();
		}
		else {
			$MyMenu = unserialize(base64_decode($MyUser->menu));
		}

		$MyModulo = $this->DH_getModulo($cla, $MyMenu);

		$dados['MyUser'] 	 = $MyUser;
		$dados['MyMenu'] 	 = $MyMenu;
		$dados['MyModulo'] = $MyModulo;
		$dados['MyMod'] 	 = $MyModulo->url_amigavel;

		if(service('request')->isAJAX()) {
			$this->constantHelper	= new ConstantHelper;
			$this->constantHelper->CNT_dataConstant();
		}

		$viewPath = "Modules\\" . $mod . "\Views\\" . $view;
		echo view($viewPath, $dados);
	}

	/**
	* Envia os dados de acesso do CMS por e-mail para o usuário cadastrado;
	* 
	* @version 1.0.0.1 - 2023-07-25
	* 
	* @uses $_POST['id']				ajax
	*/

	public function DH_ajaxSendUserAccessData() {
		$this->constantHelper	= new ConstantHelper;
		$this->constantHelper->CNT_dataConstant();

		$db = \Config\Database::connect();

		$dataAtual 		= date('d/m/Y H:i:s');
		$configEmail 	= $this->DH_getEmailConfig();
		$config 	 		= $this->DH_getCmsConfig();	

		$id 					= service('request')->getPost('id');
		$table 				= "cms_usuario";
		$builder  		= $db->table($table);

		$builder->where('id', $id);

		$query    	 = $builder->get();
		$user 			 = $query->getRow();
		$user->senha = service('encrypter')->decrypt(hex2bin($user->senha), ['key' => getenv('ENCRYPTKEY')]);

		$data = array(
			"dataAtual"     	=> $dataAtual,
			"configTitulo"   	=> "Dados de acesso", 
			"configImagem"   	=> (!empty($configEmail->imagem)) ? $configEmail->imagem : "", 
			"userLogin" 			=> (!empty($user->email)) ? $user->email : "Não informado",
			"userPassword" 		=> (!empty($user->senha)) ? $user->senha : "Não informado",
			"userLink"				=> site_url()
		);

		$viewPath = "\\Store\Views\\view_store_dados_acesso";
		$html 		= view($viewPath, $data);
		$debug 		= 0;

		try {
			$phpMailerException = PUBLICFOL . 'assets/vendor/PHPMailer-6.6.3/src/Exception.php';
			$phpMailer 					= PUBLICFOL . 'assets/vendor/PHPMailer-6.6.3/src/PHPMailer.php';
			$phpMailerSMTP 			= PUBLICFOL . 'assets/vendor/PHPMailer-6.6.3/src/SMTP.php';

			require($phpMailerException);
			require($phpMailer);
			require($phpMailerSMTP);

			$email = new PHPMailer(true);

			$email->isSMTP();
			$email->SMTPAuth    = true;
			$email->SMTPSecure  = $configEmail->e_secure;
			$email->Host        = $configEmail->e_host;
			$email->Username    = $configEmail->e_username;
			$email->Password    = $configEmail->e_password;
			$email->Port 				= $configEmail->e_port;
			$email->CharSet     = 'utf-8';
			$email->IsHTML			= true;

			$email->SetFrom($configEmail->e_from, $configEmail->e_from_name);
			$email->addAddress($user->email);

			$email->Subject = $data['configTitulo'] . ' - ' . $data['dataAtual'];
			$email->MsgHTML($html);

			@$email->Send();

			$this->DH_actionRecord($id);
			$arrResult = array ('response' => 'success', 'successMessage' => 'os dados de acesso foram enviados com sucesso', 'errorMessage' => '', 'log' => '');
		} 
		catch (Exception $e) {
			$arrResult = array ('response' => 'error', 'successMessage' => '', 'errorMessage' => $e->errorMessage(), 'log' => '');
		} 
		catch (\Exception $e) {
			$arrResult = array ('response' => 'error', 'successMessage' => '', 'errorMessage' => $e->getMessage(), 'log' => '');
		}

		if ($debug == 0) {
			echo json_encode($arrResult);
		}
	}

	/***************************************************************
	*
	*			DATABASE							
	*
	***************************************************************/

	/**
	* Pega as colunas da tabela solicitada;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param string 				 $tabela 
	* @uses $_POST['status'] directly
	* 
	* @return array 
	*/

	function DH_getTableColumns($tabela) {
		$db = \Config\Database::connect();
		return $db->getFieldNames($tabela);
	}

	/***************************************************************
	*
	*			LOGS							
	*
	***************************************************************/

	/**
	* Cria arquivo de log de alterações;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param int 					$id 
	* @param object|array $post 
	* @param string 			$acao 
	* @param string 			$pasta 
	* @param string 			$subpasta 
	*/

	function DH_createLogFile($id, $post, $acao, $pasta, $subpasta) {

		/*
		`* Valida a pasta
		*/

		$path = PUBLICLOG . $pasta;

		if(!is_dir($path)) {
			mkdir($path);
		}

		if(isset($subpasta) AND !empty($subpasta)) {
			$path = PUBLICLOG . $pasta . '/' . $subpasta;

			if(!is_dir($path)) {
				mkdir($path);
			}
		}

		/*
		* Arquivo
		*/

		$now 				= date("Y-m-d-H-i-s");
		$file 		  = $now . '.log';
		$filePath 	= $path . '/' . $file;

		if (!file_exists($filePath)) {
			fopen($filePath, "w");
		}

		/*
		* Conteúdo 
		*/

		$post = (array)$post;

		$post['log_tipo'] 	 = "Tipo de ação: " . $acao;
		$post['log_data'] 	 = "Data da ação: " . $now;
		$post['log_usuario'] = "Ação realizada por: " . service('session')->get('usuario')->titulo;
		$post 							 = bin2hex(service('encrypter')->encrypt(serialize($post), [ 'key' => getenv('ENCRYPTKEY') ]));

		file_put_contents($filePath, $post);
	}

	/**
	* Pega os logs de alterações;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param string $pasta 
	* @param string $subpasta 
	*/

	function DH_getLogFile($pasta, $subpasta) {

		/*
		* Valida a pasta
		*/

		$path 	= PUBLICLOG . $pasta;
		$files 	= array();

		if(isset($subpasta) AND !empty($subpasta)) {
			$path = PUBLICLOG . $pasta . '/' . $subpasta;
		}

		if (is_dir($path) AND $handle = opendir($path)) {

			$count = 0;

			while (false !== ($entry = readdir($handle))) {
				if ($entry != "." && $entry != "..") {
					$files[$count]['name'] = $entry;
					$files[$count]['path'] = $path . '/' . $entry;
					
					$count++;
				}
			}

			closedir($handle);
		}

		return $files;
	}

	/**
	* Salva as ações do usuário no banco de dados;
	* Ações conhecidas:
	* 	-> novo-cadastro
	* 	-> cadastrando
	* 	-> alterando-cadastro
	* 	-> atualizando-cadastro
	* 	-> deletando-cadastro
	* Segmentos:
	* 	-> $segments[0]: Painel
	* 	-> $segments[1]: Módulo
	* 	-> $segments[2]: Ação
	* 	-> $segments[3]: ID do cadastro
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param int | null $id 
	*/

	function DH_actionRecord($id = null, $type = null, $extraData = null) {
		$db 			= \Config\Database::connect();

		$uri 			= current_url(true);
		$segments = array_values(array_unique($uri->getSegments()));
		$index 		= array_search("cms", $segments);

		$user 		= service('session')->get('usuario');
		$msg 			= "";

		if(service('request')->isAJAX()) {
			if(service('request')->getMethod(true) == "POST") {
				if(in_array('DH_ajaxChangeRegisterStatus', $segments)) {
					$post 		= (object) $_POST;
					$metodo 	= "Ajax";

					$table 		= "cms_modulos";
					$builder  = $db->table($table)->where('nome', $post->table);
					$query    = $builder->get();

					$module 	= $query->getRow();

					if($post->status == 1) {
						$action = "mudou o status do cadastro de ID <b>" . $post->id . "</b> no módulo <b>" . $module->titulo . "</b> para <b>Ativo</b>.";
					}
					else {
						$action = "mudou o status do cadastro de ID <b>" . $post->id . "</b> no módulo <b>" . $module->titulo . "</b> para <b>Desativado</b>.";
					}

					$msg  = "O usuário <b>" . $user->titulo . "</b> " . $action;
					$data = [
						'id_usuario' 			=> $user->id,
						'modulo'  	 			=> $module->titulo,
						'metodo'  				=> $metodo,
						'id_item'  				=> $post->id,
						'descricao'  			=> $msg,
						'ativo'  					=> 1,
						'data_cadastro'  	=> date("Y-m-d H:i:s")
					];
				}

				if(in_array('ajaxPedidosGetDados', $segments)) {
					$post 		= (object) $_POST;
					$metodo 	= "Ajax";

					$table 		= "cms_modulos";
					$builder  = $db->table($table)->where('nome', $post->table);
					$query    = $builder->get();

					$module 	= $query->getRow();

					$action = "fez o envio do pedido de ID <b>" . $post->idPedido . "</b> no módulo <b>" . $module->titulo . "</b>.";

					$msg  = "O usuário <b>" . $user->titulo . "</b> " . $action;
					$data = [
						'id_usuario' 			=> $user->id,
						'modulo'  	 			=> $module->titulo,
						'metodo'  				=> $metodo,
						'id_item'  				=> $post->idPedido,
						'descricao'  			=> $msg,
						'ativo'  					=> 1,
						'data_cadastro'  	=> date("Y-m-d H:i:s")
					];
				}

				if(in_array('DH_ajaxSendUserAccessData', $segments)) {
					$post 		= (object) $_POST;
					$metodo 	= "Ajax";

					$table 		= "cms_usuario";
					$builder  = $db->table($table);

					$builder->where('id', $post->id);

					$query    = $builder->get();
					$user 		= $query->getRow();

					$action = "fez o envio dos dados de acesso do cadastro <b>" . $user->titulo . "</b>. ID do cadastro: <b>" . $id . "</b>";

					$msg  = "O usuário <b>" . service('session')->get('usuario')->titulo . "</b> " . $action;
					$data = [
						'id_usuario' 			=> service('session')->get('usuario')->id,
						'modulo'  	 			=> 'Usuários',
						'metodo'  				=> $metodo,
						'id_item'  				=> $id,
						'descricao'  			=> $msg,
						'ativo'  					=> 1,
						'data_cadastro'  	=> date("Y-m-d H:i:s")
					];
				}

				$table 		= "cms_auditoria";
				$builder  = $db->table($table);
				$query    = $builder->insert($data);
			}
		}
		else {
			if(isset($segments[0]) AND in_array("cms", $segments)) {
				$table 		= "cms_modulos";
				$builder  = $db->table($table)->where('url_amigavel', $segments[$index + 1]);
				$query    = $builder->get();

				$module 	= $query->getRow();

				/*
				* Cadastro
				*/

				if(isset($id) AND !empty($id)) {
					$table 			= $module->nome;
					$builder  	= $db->table($table)->where('id', $id);
					$query    	= $builder->get();

					$result   	= $query->getRow();

					$actionCad 	= "ID do cadastro: <b>" . $id . "</b>";
				}
				else {
					$actionCad  = "";
				}

				if(isset($segments[$index + 2]) AND !empty($segments[$index + 2])) {
					if($segments[$index + 2] == "novo-cadastro") {
						$metodo = "Create";
						$action = "está realizando um novo cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "cadastrando") {
						$metodo = "Insert";
						$action = "realizou um novo cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "alterando-cadastro") {
						$metodo = "Read";
						$action = "está alterando um cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "atualizando-cadastro") {
						$metodo = "Update";
						$action = "realizou uma alteração de cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "deletando-cadastro") {
						$metodo = "Delete";
						$action = "deletou um cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "visualizar") {
						$metodo = "Visualize";
						$action = "está visualizando um cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "imprimir") {
						$metodo = "Print";
						$action = "está imprimindo um cadastro no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "xlsx") {
						$metodo = "Export";
						$action = "gerou uma exportação em EXCEL de dados no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}

					if($segments[$index + 2] == "pdf") {
						$metodo = "Export";
						$action = "gerou uma exportação em PDF de dados no módulo <b>" . $module->titulo . "</b>. " . $actionCad;
					}
				}
				else {
					if(!empty($actionCad)){
						$actionCad = $actionCad;
					}
					else {
						$actionCad = '';
					}

					$metodo = "Access";
					$action = "acessou o módulo <b>" . $module->titulo . "</b>. " . $actionCad;
				}

				if(!empty($action)){
					$action = $action;
				}
				else {
					$action = '';
				}
				
				if(!empty($metodo)){
					$metodo = $metodo;
				}
				else {
					$metodo = '';
				}

				if($type == "api") {
					if(isset($extraData['action']) AND !empty($extraData['action'])) {
						if($extraData['action'] == "update") {
							$action = "e atualizou";
						}

						if($extraData['action'] == "read") {
							$action = "e está alterando";
						}
					}

					if($extraData['function'] == "grupos") {
						$function 		= "grupos";
						$apiFunction 	= ", " . $action . " os dados de <b>" . $function . "</b>. ";
					}

					if($extraData['function'] == "vendedores") {
						$function 		= "vendedores";
						$apiFunction 	= ", " . $action . " os dados de <b>" . $function . "</b>. ";
					}

					if($extraData['function'] == "configuracoes") {
						$function 		= "configurações";
						$apiFunction 	= ", " . $action . " os dados de <b>" . $function . "</b>. ";
					}

					if($extraData['function'] == "categorias") {
						$function 		= "categorias";
						$apiFunction 	= ", " . $action . " os dados de <b>" . $function . "</b>. ";
					}

					if($extraData['function'] == "cadastrando") {
						$apiFunction = ", e " . $action . " os dados do cadastro. ";
					}

					$api = "usando a API <b>" . $extraData['apiID'] . '</b>' . $apiFunction . $actionCad;

					$metodo = "API";
					$action = "está acessando o módulo <b>" . $module->titulo . "</b>, " . $api;
				}

				$msg  = "O usuário <b>" . $user->titulo . "</b> " . $action;
				$data = [
					'id_usuario' 			=> $user->id,
					'modulo'  	 			=> $module->titulo,
					'metodo'  				=> $metodo,
					'id_item'  				=> 0,
					'descricao'  			=> $msg,
					'ativo'  					=> 1,
					'data_cadastro'  	=> date("Y-m-d H:i:s")
				];

				$table 		= "cms_auditoria";
				$builder  = $db->table($table);
				$query    = $builder->insert($data);
			}
			else {
				die('<br/>----------------------------------------------[2]<br/>');
			}
		}
	}

	/**
	* Salva as ações do usuário no banco de dados;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param int | null $id 
	*/

	function DH_actionRecordUpload($modulo, $id, $action) {
		$db 			= \Config\Database::connect();

		$uri 			= current_url(true);
		$segments = $uri->getSegments();

		$user 		= service('session')->get('usuario');
		$msg 			= "";

		$modulo 	= $this->DH_getModulo($modulo);

		$metodo = "Upload";

		$msg  = "O usuário <b>" . $user->titulo . "</b> " . $action;
		$data = [
			'id_usuario' 			=> $user->id,
			'modulo'  	 			=> $modulo->titulo,
			'metodo'  				=> $metodo,
			'id_item'  				=> $id,
			'descricao'  			=> $msg,
			'ativo'  					=> 1,
			'data_cadastro'  	=> date("Y-m-d H:i:s")
		];

		$table 		= "cms_auditoria";
		$builder  = $db->table($table);
		$query    = $builder->insert($data);
	}

	/**
	* Salva as ações do usuário no banco de dados;
	* 
	* @version 1.0.0.0 - 2022-07-16
	* 
	* @param int | null $id 
	*/

	function DH_actionRecordBatch($id, $method, $module, $action) {
		$db 			= \Config\Database::connect();

		$uri 			= current_url(true);
		$segments = $uri->getSegments();

		$user 		= service('session')->get('usuario');
		$msg 			= "";

		$modulo 	= $this->DH_getModulo($module);

		$metodo 	= $method;

		$msg  = "O usuário <b>" . $user->titulo . "</b> " . $action;
		$data = [
			'id_usuario' 			=> $user->id,
			'modulo'  	 			=> $modulo->titulo,
			'metodo'  				=> $metodo,
			'id_item'  				=> $id,
			'descricao'  			=> $msg,
			'ativo'  					=> 1,
			'data_cadastro'  	=> date("Y-m-d H:i:s")
		];

		$table 		= "cms_auditoria";
		$builder  = $db->table($table);
		$query    = $builder->insert($data);
	}

	/**
	* Limpa os logs de alterações;
	* 
	* @version 1.0.0.0 - 2022-07-20
	* 
	* @uses $_POST['modulo'] 	ajax
	* @uses $_POST['item'] 		ajax
	*/

	public function DH_ajaxDeletaAuditoria() {
		$db 		= \Config\Database::connect();
		$modulo = service('request')->getPost('modulo');
		$item 	= service('request')->getPost('item');

		if($modulo == 'cms-auditoria') {
			$table 		= 'cms_auditoria';
			$builder 	= $db->table($table);

			$builder->truncate();
		}
		else {
			// Pega os dados do modulo
			$modulo = $db->table('cms_modulos')->where('url_amigavel', $modulo)->get()->getRow();

			// Limpa os registros no banco de dados
			$table 		= 'cms_auditoria';
			$builder 	= $db->table($table);

			$builder->where('modulo', $modulo->titulo);

			if(!empty($item)) {
				$builder->where('id_item', $item);
			}

			$builder->delete();

			// Deleta os arquivos de log
			$path = PUBLICLOG . $modulo->nome;

			if(!empty($item)) {
				$path .= '/item_'.$item;

				// Verifica se o modulo possui a subpasta item_
				if(!$this->DH_deletarPasta($path)) {
					$path = PUBLICLOG . $modulo->nome;
					$this->DH_deletarPasta($path);
				}
			}
			else {
				$this->DH_deletarPasta($path);
			}
		}

		echo json_encode(array('error' => '0'));
	}

	/**
	* Limpa os arquivos e depois exclui a pasta raiz;
	* 
	* @version 1.0.0.0 - 2022-07-20
	* 
	* @param string @pasta
	*/

	protected static function DH_deletarPasta($pasta) {
		if(!is_dir($pasta)) {
			return false;
		}
		
		if(substr($pasta, strlen($pasta) - 1, 1) != '/') {
			$pasta .= '/';
		}

		$files = glob($pasta . '*', GLOB_MARK);
		
		foreach($files as $file) {
			if(is_dir($file)) {
				self::DH_deletarPasta($file);
			}
			else {
				unlink($file);
			}
		}
		
		rmdir($pasta);
		return true;
	}

	/***************************************************************
	*
	*			2FA							
	*
	***************************************************************/

	/**
	* Gera o QR Code para autenticação de dois fatores
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param int $id_usuario
	* 
	* @return string
	*/ 

	function DH_geraToken2FA($id_usuario) {
		require PUBLICFOL . 'assets/vendor/Otphp/autoload.php';
		$db = \Config\Database::connect();
		$usuario = $db->table('cms_usuario')->where('id', $id_usuario)->get()->getRow();

		if(!empty($usuario)) {
			$secret = random_bytes(256);
			$encoded_secret = Base32::encode($secret);

			$totp = new TOTP(
				$usuario->email,
				$encoded_secret
			);

			$db->table('cms_usuario')->set('token_totp', $encoded_secret)->where('id', $id_usuario)->update();

			$html = '<img width="255" src="'.(new QRCode)->render($totp->getProvisioningUri()).'">';
			return $html;
		}
	}

	/**
	* Valida o codigo da autenticação de dois fatores
	* 
	* @version 1.0.0.0 - 2022-07-19
	* 
	* @param int $id_usuario
	* @param int $codigo
	* 
	* @return boolean
	*/ 

	function DH_validaToken2FA($id_usuario, $codigo) {
		require PUBLICFOL . 'assets/vendor/Otphp/autoload.php';

		$db 			= \Config\Database::connect();
		$usuario 	= $db->table('cms_usuario')->where('id', $id_usuario)->get()->getRow();

		if(!empty($usuario)) {
			$totp = new TOTP(
				$usuario->email,
				$usuario->token_totp
			);

			$totp->now();

			if($totp->verify($codigo)) {
				return true;
			}
			else {
				return false;
			}
		}
		return false;
	}

	/***************************************************************
	*
	*			Estado / Cidade					
	*
	***************************************************************/

	public function DH_getEstados() {
		$db 	  	= \Config\Database::connect();

		$table 	  = "cad_estados";
		$builder  = $db->table($table);
		$query 		= $builder->get();
		$ret 			= $query->getResult();

		return $ret;
	}

	public function DH_getCidades($idEstado = null) {
		$db = \Config\Database::connect();

		if (service('request')->isAJAX()) {
			$idEstado = service('request')->getPost('idEstado');

			$builder = $db->table('cad_cidades');

			if (!empty($idEstado)) {
				$builder->where('id_estado', $idEstado);
			}

			$builder->orderBy('titulo', 'ASC');

			$query = $builder->get();
			$ret 	 = $query->getResult();

			echo json_encode($ret);
		}
		else {
			if(isset($idEstado) AND !empty($idEstado)) {
				$builder = $db->table('cad_cidades');

				if (!empty($idEstado)) {
					$builder->where('id_estado', $idEstado);
				}

				$builder->orderBy('titulo', 'ASC');

				$query = $builder->get();
				$ret 	 = $query->getResult();

				return $ret;
			}
		}
	}

	/***************************************************************
	*
	*			End DataHelper							
	*
	***************************************************************/
}
