<?php
namespace StoreApp;

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 Store\DataHelper;

class DataAppHelper extends Controller {
	protected $dataHelper = null;

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

	function DAH_loadAppGlobalData() {
		$this->constantHelper	= new ConstantHelper;
		$this->dataHelper 		= new DataHelper;

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

		$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];
		}

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

		$data['appSeo']									= $this->dataHelper->DH_getSeo();
		$data['appAncora'] 							= $this->dataHelper->DH_getAncoras();
		$data['appCores']								= $this->dataHelper->DH_getCores();
		$data['appConfigEmail'] 				= $this->dataHelper->DH_getEmailConfig();
		$data['appInstitucionalTextos'] = $this->dataHelper->DH_getInstitucionalTextos();
		$data['appInstitucionalDados']	= $this->dataHelper->DH_getInstitucional();
		$data['appAjustes'] 						= $this->dataHelper->DH_getAjustes();
		$data['appPlataforma']					= $this->dataHelper->DH_getPlataforma();
		$data['appPixel']           		= $this->dataHelper->DH_getPixel();

		$data['appBlocos']							= $this->DAH_getBlocos();
		$data['appEstados']          		= $this->DAH_appGetEstados();
		
		$data['appMet'] 								= service('router')->methodName();
		$data['appMod']          				= $class;

		$data['appUri1']         				= (isset($segments[0]) AND !empty($segments[0])) ? $segments[0] : 'pagina-inicial';
		$data['appUri2']         				= (isset($segments[1]) AND !empty($segments[1])) ? $segments[1] : '';
		$data['appUri3']         				= (isset($segments[2]) AND !empty($segments[2])) ? $segments[2] : '';
		$data['appUri4']         				= (isset($segments[3]) AND !empty($segments[3])) ? $segments[3] : '';

		$data['appUser']         				= service('session')->get('appUser');

		$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['nowBrHour'] 							= $datetime->format('H:i');
		$data['nowBrWeek'] 							= $datetime->format('N');
		$data['versionDate'] 						= $datetime->format('YmdHis') . "1";

		$data['unixTimestamp'] 					= strtotime($data['nowUsDateTime']);

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

		$data['appMonths'] =  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'
		);

		if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Chrome-Lighthouse') === false) {
			$data['lighthouse'] = false;
		}
		else {
			$data['lighthouse'] = true;
		}

		if(isset($data['appInstitucionalDados']->whatsapp) AND !empty($data['appInstitucionalDados']->whatsapp)) {
			$data['whatsapps'] = unserialize($data['appInstitucionalDados']->whatsapp);
		}

		/*
		* App - Global
		*/

		$data['appGalerias'] = $this->DAH_appGetGalerias();

		return $data;
	}

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

		$id_estado = service('request')->getPost('idEstado');
		$dados = $db->table('cad_cidades')->where('id_estado', $id_estado)->orderBy('titulo', 'ASC')->get()->getResult();
		
		echo json_encode($dados);
	}

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

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

		return $query->getRow();
	}

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

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

		return $query->getResult();
	}

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

		$tableCategorias 	= 'cad_banner_categorias';
		$tableBanners 		= 'cad_banner';
		
		$builder = $db->table($tableCategorias);
		$builder->select('cad_banner.*');
		$builder->join($tableBanners, $tableBanners . '.id_categoria = ' . $tableCategorias . '.id', 'inner');
		$builder->where('cad_banner_categorias.modulo', $modulo);
		$builder->where('cad_banner.ativo', 1);

		$builder->orderBy('cad_banner.ordem', 'asc');

		$query = $builder->get();
		return $query->getResult();
	}

	/*
	* App
	*/

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

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

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

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

		return $result;
	}

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

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

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

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

		return $result;
	}

	public function DAH_appGetBlogs() {
		$db = \Config\Database::connect();
		
		$table 			= "cad_blog";
		$builder  	= $db->table($table);
		
		$builder->select('cad_blog.*, cad_blog_categorias.titulo AS categoria');
		$builder->join('cad_blog_categorias', 'cad_blog_categorias.id = ' . $table . '.id_categoria', 'left');
		$builder->where('cad_blog.ativo', 1);

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

		return $result;
	}
}