<?php

class Seguro_Service_Apolice
{
    private Zend_Db_Table_Row_Abstract $proposta;
    private Zend_Db_Table_Row_Abstract $propostaMae;

    /**
     * @throws Zend_Db_Table_Exception
     */
    public function __construct(int $idProposta)
    {
        $this->proposta = (new Seguro_Model_Propostas())->find($idProposta)->current();
        $this->propostaMae = $this->proposta['id'] != $this->proposta['id_proposta_mae']
            ? (new Seguro_Model_Propostas())->find($this->proposta['id_proposta_mae'])->current()
            : $this->proposta;
    }

    /**
     * @throws \Mpdf\MpdfException
     * @throws Zend_Exception
     */
    public function gerarPdf(): array
    {
        return (new Seguro_Service_GeracaoApolice($this))->gerarPdf();
    }

    public function getProposta(): ?Zend_Db_Table_Row_Abstract
    {
        return $this->proposta;
    }

    public function getPropostaMae(): ?Zend_Db_Table_Row_Abstract
    {
        return $this->propostaMae;
    }

    /**
     * @throws Zend_Exception
     */
    public function retornarDataEmissao(string $formato = Agro_Utils_Date::FORMAT_ISO_8601): string
    {
        $where[] = "id_proposta = {$this->proposta['id']}";
        $where[] = "id_status = " . Seguro_Model_Propostas::ID_STATUS_APOLICE_EMITIDA;
        $propostaStatus = (new Seguro_Model_PropostaStatus())->fetchAll(implode(' AND ', $where))->current();

        if (empty($propostaStatus)) {
            throw new Zend_Exception('Emissão de apólice não encontrada.');
        }

        return Agro_Util::formatDate($propostaStatus['dt_criacao'], $formato);
    }

    /**
     * @throws Zend_Exception
     */
    public function retornarDataEmissaoApoliceOriginal(string $formato = Agro_Utils_Date::FORMAT_ISO_8601): string
    {
        $where[] = "id_proposta = {$this->proposta['id_proposta_mae']}";
        $where[] = "id_status = " . Seguro_Model_Propostas::ID_STATUS_APOLICE_EMITIDA;
        $propostaStatus = (new Seguro_Model_PropostaStatus())->fetchAll(implode(' AND ', $where))->current();

        if (empty($propostaStatus)) {
            throw new Zend_Exception('Emissão de apólice não encontrada.');
        }

        return Agro_Util::formatDate($propostaStatus['dt_criacao'], $formato);
    }

    /**
     * @throws Zend_Exception
     */
    public function emissaoAPartir2026(): bool
    {
        return Agro_Util::contarDiasEntreDatas(
                '01/01/2026', $this->retornarDataEmissao(Agro_Utils_Date::FORMAT_PT_BR)
            ) >= 0;
    }
}