<?php

namespace App\Controllers;

use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrder;
use App\DAO\Order\QueryOrderTranslator;
use App\Services\ProcedimentoValorService;
use App\Services\RelatorioService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use Dompdf\Dompdf;

class RelatorioController extends BaseController {

	public function getProcedimentosConsulta(int $id_consulta) {

		$termo = (new RelatorioService())->getTermoProcedimentosConsulta( $id_consulta );
		$termo->stream( 'relatorio-consulta.pdf' );
		exit( 0 );

	}

	public function getTermoAutorizacaoEutanazia(int $id_pet) {

		$termo = (new RelatorioService())->getTermoAutorizacaoEutanazia( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function getTermoAtestadoObito(int $id_pet) {

		$termo = (new RelatorioService())->getTermoAtestadoObito( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function getTermoAutorizacaoGeral(int $id_pet) {

		$termo = (new RelatorioService())->getTermoAutorizacaoGeral( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function getTermoDoacaoInsumosProdutos() {

		$termo = (new RelatorioService())->getTermoDoacaoInsumosProdutos( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function getTermoGravarAudioImagemVideo(int $id_pet) {

		$termo = (new RelatorioService())->getTermoGravarAudioImagemVideo( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function getTermoRecusaGeral(int $id_pet) {

		$termo = (new RelatorioService())->getTermoRecusaGeral( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function getTermoRemocaoEmObito(int $id_pet) {

		$termo = (new RelatorioService())->getTermoRemocaoEmObito( $id_pet );
		$termo->stream( 'teste.pdf' );
		exit( 0 );

	}

	public function relatorioAcessoPdf($dataInicio, $dataFim, $id_usuario) {

		$dataInicial = $this->toIsoDate( $dataInicio );
		$dataFinal = $this->toIsoDate( $dataFim );

		$sql = <<<SQL
		    select
		        l.data,
		        l.time as hora,
		        u.email as usuario,
		        pf.nome,
		        p.descricao
		    from
		        logsys l, usuario u, pessoa_fisica pf, usuario_perfil up, perfil p
		    where
		        l.id_usuario = u.id
		        and u.id_pessoa = pf.id_pessoa
		        and u.id = up.id_usuario
		        and up.id_perfil = p.id
		        and l.data >= :data_inicio:
		        and l.data <= :data_fim:
		        and l.id_usuario = :id_usuario:
		SQL;
		$binds = [ 
			'data_inicio' => $dataInicial,
			'data_fim' => $dataFinal,
			'id_usuario' => $id_usuario
		];
		$usuariosLogados = db_connect()->query( $sql, $binds )
			->getResultArray();

		$rows = '';
		foreach ( $usuariosLogados as $key => $item ) {
			$key = $key++;
			$table_hover = $key % 2 ? "background-color: #DCDCDC;" : "";
			$data_acesso = date( "d/m/Y", strtotime( $item ['data'] ) );
			$rows .= '
                <tr style="' . $table_hover . '">
                    <td style="text-align: center;">' . $item ["nome"] . ' </td>
                    <td style="text-align: center;">' . $data_acesso . ' </td>
                    <td style="text-align: center;">' . $item ["hora"] . '</td>
                    <td style="text-align: center;">' . $item ["descricao"] . '</td>
                </tr>
            ';
		}

		$html = '';
		$html .= '<html>';
		$html .= '<head> ';
		$html .= '<style> ';
		$html .= "
                <style> 
                    @page {
                        margin: 0cm 0cm;
                    }
                    body {
                        margin-top: 3cm;
                        margin-bottom: 2cm;
                    }
        
                    /** Define the header rules **/
                    header {
                        position: fixed;
                        top: -1cm;
                        left: 0cm;
                        right: 0cm;
                        height: 2cm;
                        text-align: center; 
                    }
                </style> 
        
        ";
		$html .= '</style> ';
		$html .= '</head> ';
		$html .= '<body> ';
		// Foreach para pegar comanda
		// $data_final = $comanda->data_fechada != "1900-01-01" ? date("d/m/Y", strtotime($comanda['data_fechada'])) : "";
		$html .= '<header>';
		$html .= "<h2 style='text-align: center; font-size: 30px'> Relatório de Acessos </h2>";
		$html .= '	<table border="0" width="100%">
                <tr>
                    <td>Data do Sistema: ' . date( "d/m/Y" ) . '</td>
                </tr>
            </table>';
		$html .= '<hr>';
		$html .= '</header>';
		$html .= '<main>';
		$html .= '<table style="font-size: 13px" border="0" width="100%">
                 <tr>
                    <td style="text-align: center"><strong>Nome </strong></td>
                    <td style="text-align: center" width="100px"><strong>Data do Acesso </strong></td>
                    <td style="text-align: center"><strong>Hora do Acesso </strong></td>
                    <td style="text-align: center"><strong>Tipo Usuário </strong></td>
                </tr>
                ' . $rows . '
                </tr>';
		$html .= '</table>';
		$html .= '</main>';
		$html .= '</html>';

		$dompdf = new Dompdf();
		$dompdf->loadHtml( $html );
		$dompdf->setPaper( 'A4', 'landscape' );
		$dompdf->render();
		$dompdf->stream( 'realtorio.pdf' );
		exit( 0 );

	}

	private function isDate(string $data) {

		return checkdate( intval( substr( $data, 4, 2 ) ), intval( substr( $data, 6, 2 ) ), intval( substr( $data, 0, 4 ) ) );

	}

	private function toIsoDate(string $data) {

		return substr( $data, 0, 4 ) . '-' . substr( $data, 4, 2 ) . '-' . substr( $data, 6, 2 );

	}

	public function getRelatorioPetUnidadePdf(int $id_unidade) {

		$termo = (new RelatorioService())->getRelatorioPetUnidadePdf( $id_unidade );
		$termo->stream( 'relatorio-pet-unidade.pdf' );
		exit( 0 );

	}

	public function getRelatorioPetUnidadeExcel(int $id_unidade) {

		$termo = (new RelatorioService())->getRelatorioPetUnidadeExcel( $id_unidade );
		$termo->save( 'php://output' );
		exit( 0 );

	}

	public function getRelatorioProcedimentoValorPdf() {

		$pagination = $this->getPaginationFromRequest();

		if ($_GET ['sort'] === null) {
			$_GET ['sort'] = "descricao";
		}

		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::procedimento() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::procedimento() );
		$relatorio_service_response = (new ProcedimentoValorService())->getProcedimentoValorList( $pagination, $query_filter_collection, $query_order_collection );

		$termo = (new RelatorioService())->getRelatorioProcedimentoValorPdf( $relatorio_service_response->data ['procedimentos'] );
		$termo->stream( 'relatorio-procedimento-valor.pdf' );
		exit( 0 );

	}

	public function getRelatorioProcedimentoValorExcel() {

		$pagination = $this->getPaginationFromRequest();

		if ($_GET ['sort'] === null) {
			$_GET ['sort'] = "descricao";
		}

		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::procedimento() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::procedimento() );
		$relatorio_service_response = (new ProcedimentoValorService())->getProcedimentoValorList( $pagination, $query_filter_collection, $query_order_collection );

		$termo = (new RelatorioService())->getRelatorioProcedimentoValorExcel( $relatorio_service_response->data ['procedimentos'] );
		$termo->save( 'php://output' );
		exit( 0 );

	}

	# ------------------------------------------------------------------------------------------------------------------------------- #
	# ------------------------------------------------- RELATORIO ESTATÍSTICO ------------------------------------------------------- #
	# ------------------------------------------------------------------------------------------------------------------------------- #
	public function getRelatorioEstatisticoTotalProcedimentoPdf(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoProcedimentoExecutadoPdf( $dtini, $dtfim, $idunidade );
		$termo->stream( 'relatorio-estatistico-procedimentos.pdf' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoTotalProcedimentoExcel(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoProcedimentoExecutadoExcel( $dtini, $dtfim, $idunidade );
		$termo->save( 'php://output' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoConsultaPdf(int $dtini, int $dtfim, int $idunidade, int $tipoprocedimento) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoConsultaPdf( $dtini, $dtfim, $idunidade, $tipoprocedimento );
		$termo->stream( 'relatorio-estatistico-consultas.pdf' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoConsultaExcel(int $dtini, int $dtfim, int $idunidade, int $tipoprocedimento) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoConsultaExcel( $dtini, $dtfim, $idunidade, $tipoprocedimento );
		$termo->save( 'php://output' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoPrimeiraConsultaPdf(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoPrimeiraConsultaPdf( $dtini, $dtfim, $idunidade );
		$termo->stream( 'relatorio-estatistico-primeira-consulta.pdf' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoPrimeiraConsultaExcel(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoPrimeiraConsultaExcel( $dtini, $dtfim, $idunidade );
		$termo->save( 'php://output' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoCadastroTutorPdf(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoCadastroTutorPdf( $dtini, $dtfim, $idunidade );
		$termo->stream( 'relatorio-estatistico-cadastro-tutor.pdf' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoCadastroTutorExcel(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoCadastroTutorExcel( $dtini, $dtfim, $idunidade );
		$termo->save( 'php://output' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoFaturamentoPdf(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoFaturamentoPdf( $dtini, $dtfim, $idunidade );
		$termo->stream( 'relatorio-estatistico-faturamento.pdf' );
		exit( 0 );

	}

	public function getRelatorioEstatisticoFaturamentoExcel(int $dtini, int $dtfim, int $idunidade) {

		$termo = (new RelatorioService())->getRelatorioEstatisticoFaturamentoExcel( $dtini, $dtfim, $idunidade );
		$termo->save( 'php://output' );
		exit( 0 );

	}
	
	public function getAnameseToPdf(int $idpet, int $idprontuario) {
		
		
	}

}