<?php declare(strict_types=1);

use Mpdf\Mpdf;

class Seguro_Service_GerarPdfProposta
{
    public function __construct()
    {
        $this->view = new Zend_View();
        $this->view->setScriptPath(APPLICATION_PATH . '/modules/seguro/views/scripts/');

        $this->view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
        $this->view->addHelperPath('Agro/View/Helper', 'Agro_View_Helper');
        

        $this->view->addHelperPath(
            APPLICATION_PATH . '/modules/seguro/views/helpers',
            'Seguro_View_Helper'
        );
    }

    public function executar(
        int $idProposta,
        bool $retornarPdfComoString = false,
        bool $isEnviarDocusign = false,
        string $filePath = ''
    ) {
        $Propostas = new Seguro_Model_Propostas();
        
        $proposta = $Propostas->get($idProposta);
		$this->view->proposta = $proposta;
        $html = '';

        $this->gerarCodigosBarra($idProposta);

		// Busca, se houver, locais de entrega
		if (!empty(array_intersect(array(33, 40), array_keys($proposta->coberturas_contratadas('adicional'))))) {
			$LocaisEntrega = new Seguro_Model_PropostasCooperativas();
			$this->view->locais_entrega = $LocaisEntrega->getByIdProposta($idProposta)->toArray();
		}

		$this->view->title .= ' » Visualização ';
		$this->view->module = 'seguro';
		$this->view->apenasPrint = true;
		$this->view->isEnviarDocusign = $isEnviarDocusign;
        $this->view->importarEstilosPrint = true;
        
        $html = $this->adicionarTrechoAgroBrasilAnexo4($proposta);

        $mpdf = new Mpdf([
            'tempDir' => APPLICATION_PATH . '/upload_files/temp',
            'margin_top' => 39,
            'margin_bottom' => 10
        ]);

        $sanitizedPath = realpath($_SERVER['DOCUMENT_ROOT']."/resources/css/seguro/propostaprint_mpdf.css");
		$headerProposta = new Agro_View_Helper_HeaderProposta();

		$css = file_get_contents($sanitizedPath);
        $mpdf->SetHTMLHeader('<div>'.$headerProposta->headerProposta($proposta, 0, 0, false, '', true, "PRO-SIGN").'</div>');
		$mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);

        $mpdf->SetHTMLFooter('
            <div style="text-align: right; font-size: 10px;">
                {PAGENO}/{nbpg}
            </div>
        ');
        
        $dados = [
            'proposta' => $this->view->proposta,
            'isEnviarDocusign' => $this->view->isEnviarDocusign,
            'isAssinaturaFinalizada' => (new Seguro_Model_PropostasDocusign())->isAssinaturaFinalizada($proposta->id)
        ];
        
        ob_start();
        extract($dados); // Torna as chaves variáveis dentro do template
        
        include __DIR__ . '/../views/scripts/proposta/termos_subvencao_print.phtml';

        $htmlTermosSubvencao = ob_get_clean();
        $htmlTermosPagamento = $this->getHtmlTermosPagamento();

        if ($retornarPdfComoString) {
            $mpdf->WriteHTML($html);

            $mpdf->SetHTMLHeader('');
            $mpdf->SetTopMargin(10);
            $mpdf->WriteHTML($htmlTermosSubvencao . $htmlTermosPagamento);

            // Retorna o PDF como string
            return $mpdf->Output('', \Mpdf\Output\Destination::STRING_RETURN);
        } else {

            $html = str_replace("/resources/", $_SERVER['DOCUMENT_ROOT']."/resources/", $html);

            $mpdf->WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);

            $mpdf->SetHTMLHeader('');
            $mpdf->SetTopMargin(10);
            $mpdf->WriteHTML($htmlTermosSubvencao . $htmlTermosPagamento,  \Mpdf\HTMLParserMode::HTML_BODY);

		    $mpdf->Output($filePath, \Mpdf\Output\Destination::FILE);
        }
    }

    private function getHtmlTermosPagamento()
    {
        $dadosTermos = [
            'nome_proponente' => $this->view->proposta->proponente()['ds_nome_proponente'],
            'id_proposta'     => $this->view->proposta->id
        ];

        $beneficiarios = $this->view->proposta->beneficiarios();

        foreach ($beneficiarios as $beneficiario) {
            if ($beneficiario['fl_favorecido_autorizacao_credito']) {
                $beneficiarioAutorizado['nome'] = $beneficiario['ds_conta'] === 's'
                    ? $beneficiario['ds_nome_banco']
                    : $beneficiario['ds_nome_beneficiarios'];
                $beneficiarioAutorizado['cpf_cnpj'] = $beneficiario['nr_cpf_cnpj'];
            }
        }
        
        $rowInformacoesBancariasPropostas = (new Seguro_Model_InformacoesBancariasPropostas())
            ->fetchAll(["id_proposta = {$this->view->proposta->id}"])
            ->current();
        
        $html = '';

        if (!empty($rowInformacoesBancariasPropostas)) {
            $rowInformacoesBancarias = (new Sistema_Model_InformacoesBancarias())
                ->find($rowInformacoesBancariasPropostas['id_informacoes_bancarias'])
                ->current();
            $rowBanco = (new Sistema_Model_Bancos())->find($rowInformacoesBancarias['id_banco'])->current();
        
            $dadosTermos['numero_agencia'] = $rowInformacoesBancarias['ds_agencia'];
            $dadosTermos['digito_agencia'] = $rowInformacoesBancarias['nu_digito_agencia'];
            $dadosTermos['numero_conta'] = $rowInformacoesBancarias['ds_conta'];
            $dadosTermos['digito_conta'] = $rowInformacoesBancarias['nu_digito_conta'];
            $dadosTermos['tipo_conta'] = $rowInformacoesBancarias['ds_tipo_conta'];
            $dadosTermos['nome_banco'] = $rowBanco['ds_nome_banco'];
            
            ob_start();
            extract(['dadosTermos' => $dadosTermos, 'isEnviarDocusign' => $this->view->isEnviarDocusign]);

            if ($rowInformacoesBancariasPropostas['fl_titular_conta']) {
                include __DIR__ . '/../views/scripts/proposta/termo_autorizacao_pagamento_titular_conta.phtml';
            } else {
                include __DIR__ . '/../views/scripts/proposta/termo_autorizacao_pagamento_ordem_pagamento.phtml';
            }

            $html = ob_get_clean();
        }

        if (!empty($beneficiarioAutorizado)) {
            $dadosTermos['nome_beneficiario'] = $beneficiarioAutorizado['nome'];
            $dadosTermos['cpf_cnpj_beneficiario'] = $beneficiarioAutorizado['cpf_cnpj'];
            
            ob_start();
            extract(['dadosTermos' => $dadosTermos, 'isEnviarDocusign' => $this->view->isEnviarDocusign]);
            
            include __DIR__ . '/../views/scripts/proposta/termo_autorizacao_pagamento_beneficiario.phtml';
            
            $html .= ob_get_clean();
        }

        return $html;
    }

    private function gerarCodigosBarra(int $idProposta)
    {
        /*
		* GERA CODIGO DE BARRAS ESPECIFICO PARA PROPOSTA, CROQUI, TERMO DE SUBVENCAO FEDERAL E ESTADUAL
		*/
		$rendererOptions = array();
		$barcodeOptions  = array('text' => $idProposta . ' - PRO', 'barHeight' => 25);
		$renderer = Zend_Barcode::factory('code128', 'image', $barcodeOptions, $rendererOptions);
		$handle = $renderer->draw();
		$filename = 'resources/imagens/barcode/' . $idProposta . '-PRO-SIGN.gif';
		imagepng($handle, $filename);

		$barcodeOptions  = array('text' => $idProposta . ' - CRO', 'barHeight' => 25);
		$renderer = Zend_Barcode::factory('code128', 'image', $barcodeOptions, $rendererOptions);
		$handle = $renderer->draw();
		$filename = 'resources/imagens/barcode/' . $idProposta . '-CRO-SIGN.gif';
		imagepng($handle, $filename);

		$barcodeOptions  = array('text' => $idProposta . ' - TMF', 'barHeight' => 25);
		$renderer = Zend_Barcode::factory('code128', 'image', $barcodeOptions, $rendererOptions);
		$handle = $renderer->draw();
		$filename = 'resources/imagens/barcode/' . $idProposta . '-TMF-SIGN.gif';
		imagepng($handle, $filename);

		$barcodeOptions  = array('text' => $idProposta . ' - TME', 'barHeight' => 25);
		$renderer = Zend_Barcode::factory('code128', 'image', $barcodeOptions, $rendererOptions);
		$handle = $renderer->draw();
		$filename = 'resources/imagens/barcode/' . $idProposta . '-TME-SIGN.gif';
		imagepng($handle, $filename);
    }

    private function adicionarTrechoAgroBrasilAnexo4($proposta){
        $dtTransmissaoMae = $proposta['dt_transmissao'] ?? '';
        $dtTransmissaoMaeFormatada = '';

        if (!empty($dtTransmissaoMae)) {
            $dateTime = new DateTime($dtTransmissaoMae);
            $dtTransmissaoMaeFormatada = $dateTime->format('d/m/Y');
        }

        $dom = new DOMDocument;
        libxml_use_internal_errors(true);

        $data = $proposta['dt_transmissao'] ?? $proposta['dt_criacao'];
        
        $viewFile = (strtotime($data) >= strtotime(DATA_INICIO_NOVA_LEI_SEGURO)
            || $proposta['id_status'] == Seguro_Enum_PropostaStatus::ID_NAO_ENVIADA)
                ? 'view_print_nova_lei.phtml'
                : 'view_print.phtml';
        
        //colocando encode utf-8 pra não quebrar acentuação
        $html = mb_convert_encoding($this->view->render("proposta/{$viewFile}"), 'HTML-ENTITIES', 'UTF-8');
        $dom->loadHTML($html);

        libxml_clear_errors();
        $bloco_termo_lgpd = $dom->getElementById('termo_lgpd');
        $bloco_termo_titularidade_dados = $dom->getElementById('termo_titularidade_dados');

        $dataValida = $dtTransmissaoMaeFormatada > DATA_ALTERACAO_PDF_PROPOSTA;
   
        if($bloco_termo_lgpd && $dataValida && $bloco_termo_titularidade_dados){
            $textContent = explode("Eu autorizo",$bloco_termo_lgpd->textContent);
            $textContent2 = explode("para fornecê-los à Essor",$bloco_termo_titularidade_dados->textContent);

            $novoTextContent_bloco_lgpd = "Eu autorizo a AgroBrasil e ".$textContent[1];
            $novoTextContent_bloco_titularidade = "Eu me responsabilizo e declaro estar formalmente autorizado e/ou ser o responsável legal pelo titular destes dados
pessoais acima indicados para fornecê-los à AgroBrasil e Essor ".$textContent2[1];

            $bloco_termo_lgpd->textContent = $novoTextContent_bloco_lgpd;
            $bloco_termo_titularidade_dados->textContent = $novoTextContent_bloco_titularidade;
        }

        return $dom->saveHTML();
    }
}
