<?php
namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

use Store\DataHelper;
use Constant\ConstantHelper;

class CheckAccessPermission implements FilterInterface {

	/*
	* Verifica se o usuario esta logado
	* -> $segments[0]: Painel
	* -> $segments[1]: Módulo
	* -> $segments[2]: Ação
	* -> $segments[3]: ID do cadastro
	*/

	public function before(RequestInterface $request, $arguments = null) {
		$this->dataHelper = new DataHelper;

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

		if(!empty(service('session')->get('usuario'))) {
			$classe = $this->dataHelper->DH_getClass();

			if($classe != "login" AND $classe != "error") {
				$segments = $this->dataHelper->DH_getSegments();

				if(isset($segments) AND !empty($segments[1])) {
					$db = \Config\Database::connect();

					$table 	 = "cms_modulos";
					$result  = $db->table($table)->where('nome', $classe)->get()->getRow();
					$usuario = service('session')->get('usuario');

					if($usuario->id != 1) {
						$permissoes = unserialize(base64_decode($usuario->permissoes));

						if(isset($permissoes) AND !empty($permissoes)) {
							$categorias  = $permissoes['idModuloCategoria'];
							$modulos 		 = $permissoes['idModulo'];

							if(!empty($categorias) AND !empty($modulos) AND !in_array($result->id, $modulos)) {
								service('session')->set('msg', array('titulo' => 'Acesso negado!', 'descricao' => 'No momento você não possui permissão para acessar este módulo', 'tipo' => 'error'));
								return redirect()->to(BASECMSURL . "pagina-inicial");
							}
						}
						else {
							$table 	 = "cms_usuario_categorias";
							$result  = $db->table($table)->where('id', service('session')->get('usuario')->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->getDadosModulosCategoria($categoria);
									$dadosModulos 												= $this->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;
									}
								}

								$table 		= "cms_usuario";
								$builder  = $db->table($table);
								$builder->set('menu', base64_encode(serialize($dadosModulosCategoria)));
								$builder->where('id', service('session')->get('usuario')->id);
								$builder->update();

								service('session')->get('usuario')->menu = base64_encode(serialize($dadosModulosCategoria));
							}
						}
					}
					else {
						if ($_SERVER['REQUEST_METHOD'] === 'POST') {
						}
					}
				}
				else {
					return redirect()->to(BASECMSURL . "pagina-inicial");
				}
			}
		}
		else {
			return redirect()->to(BASECMSURL . "login");
		}
	}

	public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
	}

	public function 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;
	}

	public function 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;
	}
}