<?php

declare(strict_types=1);

class Agronet_Service_Buscahtmlcarrosselcomprovantedespesa
{
    public function busca(array $parametros): array
    {
        if (empty($parametros['idsVistoriadoresDespesas']) && empty($parametros['idCobrancaRelatorio'])) {
            throw new Exception('Parâmetros incorretos.');
        }
        
        if (!empty($parametros['idsVistoriadoresDespesas'])) {
            $arquivos = (new Sinistro2_Model_VistoriadorDespesaArquivo())->getArquivos(
                explode(',', $parametros['idsVistoriadoresDespesas'])
            );
        } else {
            $idCobrancaRelatorio = $parametros['idCobrancaRelatorio'];
            $isPrevia = $parametros['tipoRelatorio'] == 'P' ? true : false;

            $arquivos = (new Sinistro2_Model_VistoriadorDespesaArquivo())
                ->getArquivosByCobranca((int) $idCobrancaRelatorio, $isPrevia);
        }
        
        // Busca valor do combustível quando ainda não houver vínculo com cobrança
        $valorCombustivel = null;
        if (!empty($parametros['idProposta']) && !empty($parametros['dataVistoria'])) {
            $combustivel = (new Sinistro2_Model_CobrancaValorCombustivel())
                ->getValorCombustivelByProposta((int) $parametros['idProposta'], $parametros['dataVistoria']);
            
            $valorCombustivel = $combustivel['valor'] ?? null;
        }
        
        $comprovantes = [];

        $path = '/agronet/file/viewcarrossel/path/vistoriador_despesa/name/';

        $totalArquivos = 0;
        
        foreach ($arquivos as $arquivo) {
            if (file_exists($arquivo['ds_caminho_arquivo'])) {
                $unidade = $arquivo['ds_unidade'];
                $valor = $arquivo['vl_despesa'];

                if ($unidade == 'R$') {
                    $valor = 'R$ ' . number_format((float) $valor, 2, ',', '.');
                } else {
                    $valor = "{$valor} {$unidade}";
                }

                $gastoCombustivel = null;
                if ($arquivo['id_tipo_despesa'] == Sinistro2_Model_TipoDespesa::TIPO_DESPESA_KM) {
                    if (!is_null($valorCombustivel)) {
                        $gastoCombustivel = Sinistro2_Model_CobrancaValorCombustivel::calculaGastoCombustivel(
                            (float) $arquivo['vl_despesa'],
                            $valorCombustivel
                        );

                        $gastoCombustivel = 'R$ ' . number_format($gastoCombustivel, 2, ',', '.');
                    } else {
                        $gastoCombustivel = 'R$ ' . number_format((float) $arquivo['vl_custo_quilometragem'], 2, ',', '.');
                    }
                }

                $data = DateTime::createFromFormat('Y-m-d H:i:s', $arquivo['dt_despesa'])->format('d/m/Y');

                $row = [
                    'path' => $path . basename($arquivo['ds_caminho_arquivo']),
                    'tipoDespesa' => $arquivo['ds_tipo_despesa'],
                    'valor' => $valor,
                    'data' => $data,
                    'justificativa' => $arquivo['ds_justificativa']
                ];

                if (!is_null($gastoCombustivel)) {
                    $row['gastoCombustivel'] = $gastoCombustivel;
                }

                if (!empty($parametros['idCobrancaRelatorio'])) {
                    $row['idProposta'] = $arquivo['id_proposta'];
                }

                $comprovantes[] = $row;
                $totalArquivos++;
            }
        }

        return $this->montaHtmlSlidesCarrossel($comprovantes, $totalArquivos <= 10);
    }

    private function montaHtmlSlidesCarrossel(array $comprovantes, bool $showBullets): array
    {
        $htmlComprovantes = '';
        $activeClass = 'active';
        foreach ($comprovantes as $comprovante) {
            $divJustificativa = $divGastoCombustivel = $divIdProposta = '';
            if (!empty($comprovante['justificativa'])) {
                $divJustificativa = '<div>Justificativa: '. $comprovante['justificativa'] .' </div>';
            }
            
            if (!empty($comprovante['idProposta'])) {
                $divIdProposta = '<div>Proposta: '. $comprovante['idProposta'] .'</div>';
            }

            if (!empty($comprovante['gastoCombustivel'])) {
                $divGastoCombustivel = '<div>Gasto Combustível: '. $comprovante['gastoCombustivel'] .'</div>';
            }

            $infoArquivo = pathinfo($comprovante['path']);
            $htmlArquivo = '<img src="'. $comprovante['path'] .'" alt="">';
            
            if ($infoArquivo['extension'] == 'pdf') {
                $htmlArquivo = '<iframe class="iframe-carousel" src="'. $comprovante['path'] .'" width="100%" height="600px"></iframe>';
            }
            
            $htmlComprovantes .= '
                <div class="carousel-item '. $activeClass .'">
                    '. $htmlArquivo .'
                    <div class="overlay-text">
                        '. $divIdProposta .'
                        <div>Tipo Despesa: '. $comprovante['tipoDespesa'] .' </div>
                        <div>Valor: '. $comprovante['valor'] .' </div>
                        '. $divGastoCombustivel .'
                        <div>Data: '. $comprovante['data'] .' </div>
                        '. $divJustificativa .'
                    </div>
                </div>
            ';
            $activeClass = '';
        }

        return [
            'htmlSlides' => $htmlComprovantes
        ];
    }
}

?>