<?php declare(strict_types=1);

class Log_Model_EnvioFormularioEcmPlugEssor extends Agro_Db_Table_Abstract {
	protected $_schema = 'log';
	protected $_name = 'envio_formulario_ecm_plug_essor';
	protected $_primary = 'id';
	public $_order = 'dt_criacao desc';
	
	public function save(array $dados): ?int
    {
		$row = $this->createRow();
		
		$row->id_proposta = $dados['id_proposta'];
		$row->id_endosso_erp = $dados['id_endosso_erp'];
        $row->id_documento_erp = $dados['id_documento_erp'];
		$row->json_erro = $dados['json_erro'];
        $row->ds_chave_tipo_envio = $dados['ds_chave_tipo_envio'];
		$row->ds_nome_arquivo_erp = $dados['ds_nome_arquivo_erp'] ?? '';
		$row->ds_caminho_arquivo_agronet = $dados['ds_caminho_arquivo_agronet'];
		$row->fl_sucesso_envio = $dados['fl_sucesso_envio'] ? 1 : 0;

		return $row->save();
	}

	public function getFormulario(int $idProposta, int $tipoEnvio): ?Zend_Db_Table_Row
	{
		return $this->fetchRow(
			$this->select()
				->where('id_proposta = ?', $idProposta)
				->where('fl_sucesso_envio IS TRUE')
				->where(
					'ds_chave_tipo_envio = ?',
					Seguro_Service_EnviarFormularioEcmPlugEssor::DESCRICAO_TIPOS_PDF[$tipoEnvio]
				)
		);
	}

	public function formularioEnviado(int $idProposta, int $tipoEnvio): bool
	{
		$row = $this->fetchRow(
			$this->select()
				->where('id_proposta = ?', $idProposta)
				->where('fl_sucesso_envio IS TRUE')
				->where(
					'ds_chave_tipo_envio = ?',
					Seguro_Service_EnviarFormularioEcmPlugEssor::DESCRICAO_TIPOS_PDF[$tipoEnvio]
				)
		);

		return !empty($row);
	}
	
	public function getFormulariosErroEnvio(DateTime $dateTimeInicio): Zend_Db_Table_Rowset
	{
		$dataInicio = $dateTimeInicio->format('Y-m-d');

		$select = $this->select()
			->setIntegrityCheck(false)
			->from(
				['log_envio' => 'log.envio_formulario_ecm_plug_essor'],
				['id_proposta', 'ds_chave_tipo_envio', 'fl_sucesso_envio', 'min(dt_criacao) as dt_criacao']
			)
			->where('fl_sucesso_envio IS FALSE')
			->where("dt_criacao >= '{$dataInicio}'")
			->where('NOT EXISTS (
				SELECT 1
				FROM log.envio_formulario_ecm_plug_essor aux
				WHERE aux.fl_sucesso_envio IS TRUE
					AND aux.id_proposta = log_envio.id_proposta
					AND aux.ds_chave_tipo_envio = log_envio.ds_chave_tipo_envio
			)')
			->group('id_proposta, ds_chave_tipo_envio, fl_sucesso_envio')
			->order('dt_criacao DESC');
		
		return $this->fetchAll($select);
	}

	public function getNumeroTentativasComErro(int $idProposta, int $tipoEnvio)
	{
		$select = $this->select()
			->setIntegrityCheck(false)
			->from(
				['log_envio' => 'log.envio_formulario_ecm_plug_essor'],
				['COUNT(1) AS numero_tentativas']
			)
			->where('id_proposta = ?', $idProposta)
			->where('ds_chave_tipo_envio = \'' . Seguro_Service_EnviarFormularioEcmPlugEssor::DESCRICAO_TIPOS_PDF[$tipoEnvio] . '\'')
			->where('log_envio.fl_sucesso_envio IS FALSE')
			->where('NOT EXISTS(
				SELECT 1
				FROM log.envio_formulario_ecm_plug_essor
				WHERE
					envio_formulario_ecm_plug_essor.id_proposta = log_envio.id_proposta
					AND envio_formulario_ecm_plug_essor.ds_chave_tipo_envio = log_envio.ds_chave_tipo_envio
					AND envio_formulario_ecm_plug_essor.fl_sucesso_envio IS TRUE
			)');
		
		return $this->_db->fetchOne($select);
	}
}