<?php

class Seguro_Model_PropostasSubvencao extends Agro_Db_Table_Abstract
{
    public const DS_CHAVE_CONCEDIDA = 'CONCEDIDA';
    public const DS_CHAVE_EM_FILA_ENVIO = 'EM_FILA_ENVIO';
    public const DS_CHAVE_NAO_CONCEDIDA = 'NAO_CONCEDIDA';
    public const DS_CHAVE_RESERVADA = 'RESERVADA';
    public const DS_CHAVE_SEM_SUBVENCAO = 'SEM_SUBVENCAO';
    
    public const ID_STATUS_EM_FILA_ENVIO = 334;
    public const ID_STATUS_RESERVADA = 335;
    public const ID_STATUS_CONCEDIDA = 336;
    public const ID_STATUS_NAO_CONCEDIDA = 337;
    public const ID_STATUS_SEM_SUBVENCAO = 338;

    const TIPO_SUBVENCAO_ESTADUAL = 'estadual';
    const TIPO_SUBVENCAO_FEDERAL = 'federal';

    protected $_schema = 'seguro';
    protected $_name = 'propostas_subvencao';
    protected $_primary = 'id';

    public static function getChavesStatus()
    {
        return [
            self::DS_CHAVE_CONCEDIDA,
            self::DS_CHAVE_EM_FILA_ENVIO,
            self::DS_CHAVE_NAO_CONCEDIDA,
            self::DS_CHAVE_RESERVADA,
            self::DS_CHAVE_SEM_SUBVENCAO,
        ];
    }

    public static function getChavesStatusPodemObrigarDataValor() : array
    {
        return [
            self::DS_CHAVE_CONCEDIDA,
            self::DS_CHAVE_RESERVADA,
        ];
    }

    public static function getDeParaChavesStatusDataValorObrigatorio() : array
    {
        return [
            self::DS_CHAVE_EM_FILA_ENVIO => [self::DS_CHAVE_CONCEDIDA, self::DS_CHAVE_RESERVADA],
            self::DS_CHAVE_CONCEDIDA => [self::DS_CHAVE_RESERVADA],
            self::DS_CHAVE_NAO_CONCEDIDA => [self::DS_CHAVE_CONCEDIDA, self::DS_CHAVE_RESERVADA],
        ];
    }

    public function getPropostaSubvencao(int $idProposta) : ?Zend_Db_Table_Row_Abstract
    {
        $campos = [
            'sps.*',
            'ssestadual.ds_chave as status_chave_estadual',
            'ssefederal.ds_chave as status_chave_federal',
        ];
        $select = $this->select()
            ->setIntegrityCheck(false)
            ->from(['spe' => 'seguro.propostas_endosso'], $campos)
            ->join(
                ['spe2' => 'seguro.propostas_endosso'],
                'spe2.id_endosso = spe.id_endosso AND spe2.fl_proposta_vigente is true',
                false
            )
            ->join(['sp' => 'seguro.propostas'], 'sp.id = spe2.id_proposta', false)
            ->join(['sps' => "{$this->_schema}.{$this->_name}"], 'sps.id_proposta = sp.id_proposta_mae', false)
            ->join(['ssestadual' => 'sistema.status'], 'ssestadual.id = sps.id_status_subvencao_estadual', false)
            ->join(['ssefederal' => 'sistema.status'], 'ssefederal.id = sps.id_status_subvencao_federal', false)
            ->where('spe.id_proposta = ?', $idProposta);

        return $this->fetchRow($select);
    }

    public function getStatusIndiceChave(string $chaveStatus = '')
    {
        $rows = (new Sistema_Model_Status())->getDadosStatusByChaveTipoStatus(
            Sistema_Model_Tipostatus::DS_CHAVE_SUBVENCAO
        )->toArray();

        $status = [];

        foreach ($rows as $row) {
            $status[$row['ds_chave']] = $row['id'];
        }

        return !empty($chaveStatus) ? $status[$chaveStatus] : $status;
    }

    public function save(array $dados, bool $deleteByProposta = false)
    {
        if ($deleteByProposta) {
            $this->delete($dados['id_proposta'], 'id_proposta');
        }

        $row = $this->getRow($dados['id']);
        $row->id_proposta = $dados['id_proposta'];
        $row->id_status_subvencao_estadual = $dados['id_status_subvencao_estadual'];
        $row->id_status_subvencao_federal = $dados['id_status_subvencao_federal'];

        $save = $row->save();

        if (!$save) {
            return null;
        }

        return $save;
    }

    /**
     * Retorna o status concatenado com a sua descrição
     * @param string $dsChave
     * @param string $dsStatus
     * @return string
     */
    public function getDescricaoStatusSubvencao(string $dsChave, string $dsStatus): string
    {
        $descricaoStatus = $dsStatus;

		switch ($dsChave) {
			case self::DS_CHAVE_EM_FILA_ENVIO:
				$descricaoStatus .= " - A proposta será submetida à consulta ao governo.";
				break;
			
			case self::DS_CHAVE_RESERVADA:
				$descricaoStatus .= " - Proposta enviada ao governo e aguardando confirmação da subvenção.";
				break;

			case self::DS_CHAVE_CONCEDIDA:
				$descricaoStatus .= " - Subvenção confirmada para a apólice.";
				break;

			case self::DS_CHAVE_NAO_CONCEDIDA:
				$descricaoStatus .= " - Subvenção não aprovada para a proposta.";
				break;

			default:
				$descricaoStatus = '- Sem subvenção.';
				break;
		}

		return $descricaoStatus;
    }
}