<?php

/* Classe para tratar os dados das cotações recebidos pela API da Agritask */

class Agro_AgritaskCotacao {

	private $id_proposta = null;
    private $id_proposta_extenso = null;
    private $id_cotacao = '';
    private $id_corretor = null;
    private $id_usuario = null;
    private $id_produto = null;
    private $items = array();
    private $indices = array();
	private $atributos = array();
	private $proponente = array();    
    private $propriedade = array();
    private $croqui = array();
    private $talhoes = array();
    private $codigo_segurado = '';
    private $codigo_item_principal = '';
    private $coordenada_sede = '';
    private $documento = '';
    private $nome_proponente = '';
    private $tipo_pessoa = '';
    private $status = null;
    private $dt_vigencia_inicio = '';
    private $dt_vigencia_fim = '';
    private $ds_email_proponente = '';
    private $ds_telefone = '';
    private $vl_franquia = null;
    private $vl_taxa = null;
    private $vl_premio = null;
    private $vl_lmga = null;
    private $lmga_parcial = null;
    private $premio_parcial = null;
    private $id_usuario_corretor = null;
    private $taxas_disponiveis = array();
    private $codigos_itens = array();

    const STATUS_COTACAO_NOVA_COM_FRANQUIA = 102;
    const STATUS_APOLICE_EMITIDA = 11;
    const STATUS_PROPOSTA_EFETIVADA = 3;
    const STATUS_PROPOSTA_CANCELADA = 9;
    const STATUS_APOLICE_CANCELADA = 10;

    public function getIdProposta() : int { return $this->id_proposta; }
    public function getIdPropostaExtenso() : string { return $this->id_proposta_extenso; }
    public function getIdCotacao() : string { return $this->id_cotacao; }
    public function getIdCorretor() :? int { return $this->id_corretor; }
    public function getIdUsuario() :? int { return $this->id_usuario; }
    public function getIdUsuarioCorretor() :? int { return $this->id_usuario_corretor; }
    public function getIdProduto() : int { return $this->id_produto; }
    public function getItems() : array { return $this->items; }
    public function getIndices() : array { return $this->indices; }
    public function getAtributos() : array { return $this->atributos; }
    public function getProponente() : array { return $this->proponente; }
    public function getPropriedade() : array { return $this->propriedade; }
    public function getCroqui() : array { return $this->croqui; }
    public function getTalhoes() : array { return $this->talhoes; }
    public function getCodigoSegurado() : string { return $this->codigo_segurado; }
    public function getCodigoItemPrincipal() : string { return $this->codigo_item_principal; }
    public function getCoordenadaSede() : string { return $this->coordenada_sede; }
    public function getDocumento() : string { return $this->documento; }
    public function getNomeProponente() : string { return $this->nome_proponente; }
    public function getTipoPessoa() : string { return $this->tipo_pessoa; }
    public function getStatus() :? int { return $this->status; }
    public function getDtVigenciaInicio() : string { return $this->dt_vigencia_inicio; }
    public function getDtVigenciaFim() : string { return $this->dt_vigencia_fim; }
    public function getEmailProponente() : string { return $this->ds_email_proponente; }
    public function getTelefone() : string { return $this->ds_telefone; }
    public function getVlFranquia() : float { return $this->vl_franquia; }
    public function getVlTaxa() : float { return $this->vl_taxa; }
    public function getVlPremio() : float { return $this->vl_premio; }
    public function getVlLmga() :? float { return $this->vl_lmga; }
    public function getPremioParcial() : float { return $this->premio_parcial; }
    public function getLmgaParcial() : float { return $this->lmga_parcial; }
    public function getTaxasDisponiveis() : array { return $this->taxas_disponiveis; }
    public function getCodigosItens() : array { return $this->codigos_itens; }

    public function setIdProposta(int $id) : void {
        if ($id) {
    	    $this->id_proposta = $id;
        }
    }

    public function setIdPropostaExtenso(string $idExtenso) : void {
        if ($idExtenso) {
    	    $this->id_proposta_extenso = $idExtenso;
        }
    }

    public function setIdCotacao(string $id) : void {
        if ($id) {
    	    $this->id_cotacao = $id;
        }
    }

    public function setItems(array $it) : void {

        if (count($it) > 0) {
            foreach ($it as $key => $value ) {
                if ($value) {
                    $temp[$key] = $value;
                }

                if ($key === 'IS_LMGA_PARCIAL') {
                    $this->lmga_parcial += $value;
                }

                if ($key === 'IS_VALOR_CUSTEIO') {
                    $this->premio_parcial += $value;
                }
            }
            array_push($this->items, $temp);
        }
    }

    public function setIndices(array $idx) : void {
        if (count($idx) > 0) {
            foreach ($idx as $key => $value) {
                if ($value) {
                    $indices[$key] = $value;
                }
            }
            array_push($this->indices, $indices);
        }
    }

    public function setAtributos(array $att) : void {
        if (count($att) > 0) {
            foreach ($att as $key => $value) {
                if ($value) {
                    $this->atributos[$key] = $value;
                }
            }
        }
    }

    public function setProponente(array $proponente) : void {
        if (count($proponente) > 0) {
            foreach ($proponente as $key => $value) {
                if ($value) {
                    $this->proponente[$key] = $value;
                }
            }
        }
    }

    public function setPropriedade(array $propriedade) : void {
        if (count($propriedade) > 0) {
            foreach ($propriedade as $key => $value) {
                if ($value) {
                    $this->propriedade[$key] = $value;
                }
            }
        }
    }

    public function setCroqui(array $croqui) : void {
        if (count($croqui) > 0) {
            foreach ($croqui as $key => $value) {
                if ($value) {
                    $this->croqui[$key] = $value;
                }
            }
        }
    }

    public function setTalhoes(array $talhoes) : void {
        if (count($talhoes) > 0) {
            foreach ($talhoes as $key => $value) {
                if ($value) {
                    $temp[$key] = $value;
                }
            }
            array_push($this->talhoes, $temp);
        }
    }

    public function setIdCroqui(int $id) : void {
        for ($i=0; $i<count($this->talhoes); $i++) {
            $this->talhoes[$i]['id_croqui'] = $id;
        }
    }

    public function setCodigoSegurado(string $codigo) : void {
        $this->codigo_segurado = $codigo;
    }

    public function setCodigoItemPrincipal(string $codigo) : void {
        $this->codigo_item_principal = $codigo;
    }

    public function setCoordenadaSede(string $coordenada) : void {
        $this->propriedade['ds_coordenadas'] = $coordenada;
    }

    public function setDocumento(string $doc) : void {
        $this->documento = $doc;
    }

    public function setNomeProponente(string $nome) : void {
        $this->nome_proponente = $nome;
    }

    public function setTipoPessoa(string $tipo) : void {
        $this->tipo_pessoa = $tipo;
    }

    public function setStatus(int $status) : void {
        $this->status = $status;
    }

    public function setDtVigenciaInicio(string $data) : void {
        $this->dt_vigencia_inicio = $data;
    }

    public function setDtVigenciaFim(string $data) : void {
        $this->dt_vigencia_fim = $data;
    }

    public function setEmailProponente(string $mail) : void {
        $this->ds_email_proponente = $mail;
    }

    public function setTelefone(string $fone) : void {
        $this->ds_telefone = $fone;
    }

    public function setVlFranquia(float $franquia) : void {
        $this->vl_franquia = $franquia;
    }

    public function setVlTaxa(float $taxa) : void {
        $this->vl_taxa = $taxa;
    }

    public function setVlPremio(float $vl_premio) : void {
        $this->vl_premio = $vl_premio;
    }

    public function setIdCorretor(int $id) : void {
        $this->id_corretor = $id;
    }

    public function setIdUsuario(int $id) : void {
        $this->id_usuario = $id;
    }

    public function setIdUsuarioCorretor(int $id) : void {
        $this->id_usuario_corretor = $id;
    }

    public function setIdProduto(int $id) : void {
        $this->id_produto = $id;
    }

    public function setVlLmga(float $vl_lmga) : void {
        $this->vl_lmga = $vl_lmga;
    }

    public function setTaxasDisponiveis(array $td) : void {
        $this->taxas_disponiveis = $td;
    }

    public function addCodigoItem(string $codigoItem) : void {
        $this->codigos_itens[] = $codigoItem;
    }

    /**
     * Executa a requisição CURL para a Agritask com os dados informados do xml.
     * 
     * @param int $idProposta
     * @param string $filename
     */
    private function executarCurlAgritask(int $idProposta, string $filename) : void {

        if (!file_exists($filename)) {
            throw new Exception("Arquivo CSV da proposta {$idProposta} não encontrado.");
        }

        $url = (APPLICATION_ENV == 'production') ? AGRITASK_BASE_URL_PROD : AGRITASK_BASE_URL_DEV;
        $url .= (APPLICATION_ENV == 'production') ? '/i/import/do' : '/t/import/do';

        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array(
            'file'=> new CURLFILE($filename),
            'wskey' => (APPLICATION_ENV == 'production') ? AGRITASK_WSKEY_PROD : AGRITASK_WSKEY_DEV,
            'class' => 'com.scantask.tms.importdata.ScriptImportUpdatePlots',
            'project' => AGRITASK_PROJECT_PROD
            ),
        ));
        
        $resp = curl_exec($curl);

        if (curl_errno($curl) > 0) {
            throw new Exception("Não foi possível obter conexão/acesso com a Agritask.");
        }
        
        if (strpos($resp, 'error')) {
            throw new Exception("Erro ao atualizar o a franquia: \n {$resp}.");
        }

        curl_close($curl);
    }

    /**
     * Atualiza na Agritask a franquia, valor da taxa, valor do prêmio e status para proposta efetivada.
     * 
     * @param int $idProposta
     */
    public function atualizarFranquiaSelecionada(int $idProposta) : void {

        $filename = $this->criarCSVFranquiaSelecionada($idProposta);
        $this->executarCurlAgritask($idProposta, $filename);
    }

    /**
     * Atualiza na Agritask o status informado no parâmetro.
     * 
     * @param int $idProposta
     * @param int $status
     */
    public function atualizarStatus(int $idProposta, int $status) : void {

        $filename = $this->criarCSVAtualizarStatus($idProposta, $status);
        $this->executarCurlAgritask($idProposta, $filename);
    }

    /**
     * Atualiza na Agritask o número da apólice e status para apólice emitida.
     * 
     * @param int $idProposta
     * @param int $numeroApolice
     */
    public function atualizarApolice(int $idProposta, string $numeroApolice) : void {
        $filename = $this->criarCSVApolice($idProposta, $numeroApolice);
        $this->executarCurlAgritask($idProposta, $filename);
    }

    /**
     * Cria o arquivos CSV para atualizar na Agritask a franquia, valor da taxa, valor do prêmio e status para proposta efetivada.
     * 
     * @param int $idProposta
     * @return string
     */
    private function criarCSVFranquiaSelecionada(int $idProposta) : string {
        $rowPropostaCotacaoAgritask = $this->getRowPropostaCotacaoAgritask($idProposta);
        
        $modelPropostasCoberturas = new Seguro_Model_PropostasCoberturas();
        $dataPropostaCobertura = $modelPropostasCoberturas->getCoberturasSalvas($idProposta);
        
        if (empty($dataPropostaCobertura[Produto_Model_Coberturas::BAIXA_INDICE])) {
            throw new Exception("Não foram encontradas coberturas salvas para a proposta {$idProposta}.");
        }
        
        $filename = APPLICATION_PATH . "/upload_files/log/agritask/update_franquia_{$idProposta}.csv";
        file_put_contents($filename, "Grower name,Plot name/Policy number,N/A,N/A_1,N/A_2,N/A_3,N/A_4,N/A_5,N/A_6,N/A_7,N/A_8,N/A_9,N/A_10,policy_status,franchise_percent_agronet,premium_rate_percent_agronet,premium_reals_agronet\n");
        
        $linha =  $rowPropostaCotacaoAgritask['ds_codigo_segurado'] . ','; // Grower name
        $linha .= $rowPropostaCotacaoAgritask['ds_codigo_item'] . ","; // Plot name/Policy number
        $linha .= ",,,,,,,,,,,"; // N/A,N/A_1,N/A_2,N/A_3,N/A_4,N/A_5,N/A_6,N/A_7,N/A_8,N/A_9,N/A_10
        $linha .= self::STATUS_PROPOSTA_EFETIVADA .","; //policy_status
        $linha .= (float)$dataPropostaCobertura[Produto_Model_Coberturas::BAIXA_INDICE]['vl_franquia'] . ","; //franchise_percent_agronet
        $linha .= (float)$dataPropostaCobertura[Produto_Model_Coberturas::BAIXA_INDICE]['vl_taxa'] . ","; //premium_rate_percent_agronet
        $linha .= (float)$dataPropostaCobertura[Produto_Model_Coberturas::BAIXA_INDICE]['vl_premio']; //premium_reals_agronet
        $linha .= "\n";

        file_put_contents($filename, $linha, FILE_APPEND);

        return $filename;
    }

    /**
     * Cria o arquivos CSV para atualizar na Agritask o status passado por parâmetro.
     * 
     * @param int $idProposta
     * @param int $status
     * @return string
     */
    private function criarCSVAtualizarStatus(int $idProposta, int $status) : string {
        $rowPropostaCotacaoAgritask = $this->getRowPropostaCotacaoAgritask($idProposta);
        
        $filename = APPLICATION_PATH . "/upload_files/log/agritask/{$idProposta}_update_status_{$status}.csv";
        file_put_contents($filename, "Grower name,Plot name/Policy number,N/A,N/A_1,N/A_2,N/A_3,N/A_4,N/A_5,N/A_6,N/A_7,N/A_8,N/A_9,N/A_10,policy_status\n");
        
        $linha =  $rowPropostaCotacaoAgritask['ds_codigo_segurado'] . ','; // Grower name
        $linha .= $rowPropostaCotacaoAgritask['ds_codigo_item'] . ","; // Plot name/Policy number
        $linha .= ",,,,,,,,,,,"; // N/A,N/A_1,N/A_2,N/A_3,N/A_4,N/A_5,N/A_6,N/A_7,N/A_8,N/A_9,N/A_10
        $linha .= $status; //policy_status
        $linha .= "\n";

        file_put_contents($filename, $linha, FILE_APPEND);

        return $filename;
    }

    /**
     * Cria o arquivos CSV para atualizar na Agritask o número da apólice e o status para Apólice Emitida.
     * 
     * @param int $idProposta
     * @param int $numeroApolice
     * @return string
     */
    private function criarCSVApolice(int $idProposta, string $numeroApolice) : string {
        $rowPropostaCotacaoAgritask = $this->getRowPropostaCotacaoAgritask($idProposta);
        
        $filename = APPLICATION_PATH . "/upload_files/log/agritask/{$idProposta}_adicionar_apolice.csv";
        file_put_contents($filename, "Grower name,Plot name/Policy number,N/A,N/A_1,N/A_2,N/A_3,N/A_4,N/A_5,N/A_6,N/A_7,N/A_8,N/A_9,N/A_10,policy_status,policy_number\n");
        
        $linha =  $rowPropostaCotacaoAgritask['ds_codigo_segurado'] . ','; // Grower name
        $linha .= $rowPropostaCotacaoAgritask['ds_codigo_item'] . ","; // Plot name/Policy number
        $linha .= ",,,,,,,,,,,"; // N/A,N/A_1,N/A_2,N/A_3,N/A_4,N/A_5,N/A_6,N/A_7,N/A_8,N/A_9,N/A_10
        $linha .= self::STATUS_APOLICE_EMITIDA . ","; //policy_status
        $linha .= $numeroApolice; //policy_number
        $linha .= "\n";

        file_put_contents($filename, $linha, FILE_APPEND);

        return $filename;
    }

    /**
     * Retorna a row da PropostaCotacaoAgritask filtrando pela proposta
     * 
     * @param int $idProposta
     * @return Zend_Db_Table_Row
     */
    private function getRowPropostaCotacaoAgritask(int $idProposta) : Zend_Db_Table_Row {
        $modelPropostaCotacaoAgritask = new Seguro_Model_PropostasCotacaoAgritask();
        $rowPropostaCotacaoAgritask = $modelPropostaCotacaoAgritask->getRow($idProposta);
        
        if (empty($rowPropostaCotacaoAgritask['id_proposta'])) {
            throw new Exception("Não foi encontrada cotação para a proposta {$idProposta}.");
        }

        return $rowPropostaCotacaoAgritask;
    }
}
