<?php

class Seguro_Model_Rotinas extends Agro_Db_Table_Abstract {
	protected $_schema = 'seguro';
	protected $_name = 'itens_segurados';
	protected $_primary = array('id','nr_apolice');

	public function save($id, $nr_apolice) {
		$User = Zend_Auth::getInstance()->getIdentity();
		
		$update = "UPDATE seguro.propostas SET nr_apolice='".$nr_apolice."',  id_usuario_alteracao=".$User->id.", id_status=8 WHERE id = '".$id."'";
		$salvou = $this->_db->query($update);

		if ($salvou) {
			$PropostasApolices = new Seguro_Model_PropostaStatus();
			$PropostasApolices->saveApolices($id, $nr_apolice);
		}

		return true;
	}

	public function atualizaBoleto($ds_identificador,$fl_pago) {
	    $User = Zend_Auth::getInstance()->getIdentity();
		if($fl_pago){
			$update = "update seguro.proposta_boletos SET dt_alteracao='now()', id_usuario_alteracao=".$User->id.", dt_verificacao_pagamento='now()', fl_pago=true where ds_identificador='".$ds_identificador."'";
		} else {
			$update = "update seguro.proposta_boletos SET dt_alteracao='now()', id_usuario_alteracao=".$User->id.", dt_verificacao_pagamento='now()', fl_pago=false where ds_identificador='".$ds_identificador."'";
		}
		$salvou = $this->_db->query($update);
		return $salvou;
	}

	public function atualizaParcelas($id_proposta, $nr_parcela, $fl_pago) {
	    $User = Zend_Auth::getInstance()->getIdentity();
		if($fl_pago){
			$update = "update seguro.propostas_parcelas SET id_usuario_alteracao=".$User->id.", dt_verificacao_pagamento='now()', fl_pago=true where nr_parcela='".$nr_parcela."' and id_proposta='".$id_proposta."'";
		} else {
			$update = "update seguro.propostas_parcelas SET id_usuario_alteracao=".$User->id.", dt_verificacao_pagamento='now()' where nr_parcela='".$nr_parcela."' and id_proposta='".$id_proposta."'";
		}
		try {
		    $salvou = $this->_db->query($update);
		} catch (Exception $e) {
		    die($e);
		}

		return $salvou;
	}

	public function getBoletos(){
		$sql = "select
					pr.id,
					b.ds_identificador
				from
					seguro.propostas pr,
					seguro.proposta_boletos b,
					sistema.status s,
					produto.produtos pd,
					seguro.propostas_parcelas pp
				where
				    b.dt_criacao < 'now()'
					and b.fl_ativo = true
					and b.id_proposta = pr.id
					and s.id = pr.id_status
					and pd.id = pr.id_produto
					and pp.id_proposta = pr.id
					and pp.nr_parcela = b.nr_parcela
					and b.fl_pago = false
					and pd.id_safra >= 13
					and pr.id_status not in (2,5,13,59,4)
					and (b.dt_verificacao_pagamento < 'now()' or b.dt_verificacao_pagamento is null)
					and (date(now()) - date(pp.dt_vencimento)) <= 15
				order by
					pr.id
				limit 50
				";

		$Rs = $this->_db->fetchAll($sql);
		return $Rs;
	}

    public function listarBoletos($mensal=false){
		$safra_atual = (new Produto_Model_Safras())->getSafraAtual('id');


        $sql = "select
                    pr.id,
                    b.nu_boleto,
                    b.fl_pago
                from
                    seguro.propostas pr,
                    seguro.propostas_versoes pv,
                    seguro.proposta_boletos b,
                    produto.produtos pd,
                    sistema.status s
                where
                    pv.ds_identificador_seguradora is not null
                    and b.id_proposta = pr.id
                    and pv.id = b.id_versao
                    and s.id = pr.id_status
                    and pd.id = pr.id_produto
                    and pd.id_safra in (".$safra_atual.",".($safra_atual - 1).")
                    and pr.id_status not in (2,5,13,59,4)
                    and to_char(b.dt_verificacao_pagamento, 'dd/mm/yyyy') = to_char(now(), 'dd/mm/yyyy')
        		    and b.vl_total > 0 ";

        if (!$mensal) { $sql .= " and b.fl_pago = false "; }

        $sql .= "   group by
                    pr.id,
                    b.nu_boleto,
                    b.fl_pago
                order by
                    b.nu_boleto
                ";
        $Rs = $this->_db->fetchAll($sql);

        return $Rs;
    }

	public function getBoletosEssor($count=false, $mensal=false){
		ini_set('memory_limit', '2048M');

		ini_set('max_execution_time', 6000);

		if(!$count) {
			$limit = "limit 3000";
		}

		$safra_vigente = (new Produto_Model_Safras())->getSafraAtual('id');
	    
	    $sql = "select
                    pr.id,
                    case when (pv.ds_identificador_seguradora is null or pv.ds_identificador_seguradora = '') then pr.ds_identificador_seguradora else pv.ds_identificador_seguradora end as ds_identificador_seguradora,
                    b.id_versao,
                    b.nr_parcela
                from
                    seguro.propostas pr,
                    seguro.propostas_versoes pv,
                    seguro.proposta_boletos b,
                    produto.produtos pd,
                    sistema.status s,
                    seguro.propostas_corretores pc
                where
                        pv.ds_identificador_seguradora is not null
                    and b.id_proposta = pr.id
                    and pv.id = b.id_versao
                    and s.id = pr.id_status
                    and pd.id = pr.id_produto";

                if (!$mensal) { $sql .= " and b.fl_pago = false "; }

        $sql .= "   and pd.id_safra in (".$safra_vigente.",".($safra_vigente - 1).")
                    and (b.dt_verificacao_pagamento < 'now()' or b.dt_verificacao_pagamento is null)
                    and pc.id_proposta = pr.id
                    and pc.id_usuario  <> 487
                    and b.vl_total > 0
					
					-- and (date(now()) - date(b.dt_vencimento)) <= 2 -- removida temporariamente
                    
					and s.ds_chave not in ('PROPOSTA_INCOMPLETA' , 'NAO_ENVIADA' , 'DEVOLVIDA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'SOLICITACAO_CANCELADA')
                    and pr.id_versao = b.id_versao
                group by
                    pr.id,
                    pv.ds_identificador_seguradora,
                    b.id_versao,
                    b.nr_parcela
                order by
					b.nr_parcela,
                    pr.id,
                    b.id_versao
					$limit
				";

	    $Rs = $this->_db->fetchAll($sql);
	    return $Rs;
	}

	public function getParcelas(){
		$sql = "select
                    distinct(pr.id)
                from
                    seguro.propostas pr,
                    produto.produtos pd,
                    seguro.propostas_parcelas pp,
                    sistema.status st
                where
                	    pp.dt_vencimento < 'now()'
                    and pp.fl_pago = false
                    and pd.id_safra >= 14
                    and pr.id_status not in (2,5,13,59,4)
                    and (pp.dt_verificacao_pagamento < 'now()' or pp.dt_verificacao_pagamento is null)
                    and pd.id = pr.id_produto
                    and pp.id_proposta = pr.id
                    and st.id = pr.id_status
                    and st.ds_chave in ('APOLICE_EMITIDA')
                order by
                    pr.id
                limit 500
				";

		$Rs = $this->_db->fetchAll($sql);
		return $Rs;
	}

	public function getIdentificadorBoleto($nuBoleto){
		$sql = "select ds_identificador from seguro.proposta_boletos where nu_boleto='".$nuBoleto."'";
		return $this->_db->fetchOne($sql);
	}

	public function getNumeroApolice($id_proposta){
		$sql = "select nr_apolice from seguro.propostas where id='".$id_proposta."'";
		return $this->_db->fetchOne($sql);
	}

	public function alteraVencimentosParcelas($data, $parcela, $proposta){
		$hoje = Zend_Date::now();
		$hoje = Agro_Util::formatDate($hoje,Zend_Date::W3C);
		$User = Zend_Auth::getInstance()->getIdentity();

		$update = "UPDATE seguro.propostas_parcelas SET dt_vencimento='".$data."',dt_alteracao='".$hoje."',id_usuario_alteracao='".$User->id."' WHERE nr_parcela='".$parcela."' AND id_proposta='".$proposta."'";
		$this->_db->query($update);
	}

	public function marcaParcelasPagas($parcela, $proposta){
		$hoje = Zend_Date::now();
		$hoje = Agro_Util::formatDate($hoje,Zend_Date::W3C);
		$User = Zend_Auth::getInstance()->getIdentity();

		$update = "UPDATE seguro.propostas_parcelas SET fl_pago=true,dt_alteracao='".$hoje."',id_usuario_alteracao='".$User->id."' WHERE nr_parcela='".$parcela."' AND id_proposta='".$proposta."'";
		$this->_db->query($update);
	}

}
