<?
$Propriedade     = $this->proposta->propriedade();
$comercializacao = $this->proposta->comercializacao($Propriedade['id_estado'], $Propriedade['id_municipio']);
$atributos       = $this->proposta->atributos('PROPRIEDADE');
?>

<?=$this->title('Operações')?>
<link rel="stylesheet" href="/resources/css/seguro/proposta_final.css" type="text/css" media="screen" />

<script>
	$(document).ready(function() {
		$('.imprimir').click(function() {
			link = "/seguro/proposta/view/id/<?=$this->proposta->id?>";
			win=window.open(link, 'proposta', 'height=600,width=800,scrollbars=1');
		});

		$('.transmitir').click(function() {
			$('#div_transmitir').hide();

	  		permitirTransmissao = false;

			$.when(
				$.validarCoordenadas()
			).then( () => {

				if (!permitirTransmissao) {
					return;
				}

				setTimeout(() => {
					$("body").trigger("ajaxStart");
				}, 500);

				$.transmitir();
			})
		});

		$('.novo').click(function() {
			location.href = '/seguro/proposta/produto';
		});

		$('.pesquisar').click(function() {
			location.href = '/seguro/proposta';
		});

    	$('.boleto').click(function () {
			$.ajax({
				url: '/gerarboleto/gerarboleto',
				data: {
					id_proposta : <?=$this->proposta->id?>
				},
				type: 'POST',
				dataType: 'json',
				success: function(response) {

					$('.boleto2').removeClass('hide');
					$('.boleto2').addClass('show');
					$('.boleto').removeClass('show');
					$('.boleto').addClass('hide');
				},
				error: function (xhr, desc, er) {
					alert(xhr.responseText);
				}
			});
    	
    	});
	});

	jQuery.validarCoordenadas = function() {

		return $.ajax({
			url: '/seguro/propostaajax/validarcoordenadasmunicipio',
			data: {
				id : <?=$this->proposta->id?>
			},
			type: 'POST',
			dataType: 'json',
			success: function(response) {

				if (response.status == false) {

					if (!response.confirm) {

						alert(response.message);
						$('#div_transmitir').show()
						return false;
					} else {

						if (!confirm(response.message)) {
							$('#div_transmitir').show();
							return false;
						}
					}
				}

				permitirTransmissao = true;
				return true;
			},
			error: function (xhr, desc, er) {
				alert(xhr.responseText);
			}
		});
	}

	jQuery.transmitir = function() {
		$.ajax({
			url: '/seguro/propostaajax/transmitir',
			data: {
				id : <?=$this->proposta->id?>,
				comercializacao : <?=$comercializacao['id']?>,
                md : '<?=$this->md?>'
			},
			type: 'POST',
			dataType: 'json',
			success: function(response) {
				
				setTimeout(() => {
					$("body").trigger("ajaxStop");
				}, 500);

				if (!response.status && response.validacao_lista) {
					alert(response.message);
					$('#message').text(response.message);
					$('#message').removeClass('success');
					$('#message').addClass('error');
					$('#div_transmitir').hide();
					$('#icon_edit_proposta').hide();
					$('#text_edit_proposta').each(function() {
    					var text = $(this).text();
    					$(this).replaceWith(text);
					});

					return false;
				}

				if (response.message) {
					if (response.confirm == 'confirm') {
					  if (response.modal && response.modal === 'dados_bancarios') {
              if (confirm(response.message)) {
                $('#divAjaxDialog').load('/seguro/proposta/dadosbancarios/id_proposta/<?=$this->proposta->id?>', function(e) {
                  $('#divAjaxDialog').dialog('open');
                });

                $('#divAjaxDialog').dialog({
                  position : 'top',
                  title : 'Informações Bancárias',
                  autoOpen: false,
                  width:800,
                  modal:true,
                  buttons: {
                    Fechar : function() {
                      $(this).dialog('close');
                      $('#divAjaxDialog').html('');
                    },
                    Salvar : function() {
                      if (!$.validarPreenchimentoInformacoesBancarias(true)) {
                        return false;
                      }

                      $.ajax({
                        url: '/sistema/informacaobancaria/salvarinformacoesbancariasproposta',
                        type: 'POST',
                        dataType: 'json',
                        data: {
                          id_proposta: <?=$this->proposta->id?>,
                          id_banco_titular: $('#id_banco_titular').val(),
                          ds_agencia_titular: $('#ds_agencia_titular').val(),
                          nu_digito_agencia_titular: $('#nu_digito_agencia_titular').val(),
                          ds_conta_titular: $('#ds_conta_titular').val(),
                          nu_digito_conta: $('#nu_digito_conta').val(),
                          tipoConta: $('.tipoConta:checked').val(),
                          id_banco_nao_titular: $('#id_banco_nao_titular').val(),
                          ds_agencia_nao_titular: $('#ds_agencia_nao_titular').val(),
                          nu_digito_agencia_nao_titular: $('#nu_digito_agencia_nao_titular').val(),
                          titularConta: $('.titularConta:checked').val(),
                          autorizarCreditoBeneficiario: $('#autorizarCreditoBeneficiario').is(':checked'),
                        },
                        success: (response) => {
                          alert(response.mensagem);

                          if (response.erro === false) {
                            $(this).dialog('close');
                            $('#divAjaxDialog').html('');
                          }
                        },
                        error: () => {
                          alert('Erro ao salvar as informações bancárias.');
                        }
                      });
                    }
                  }
                });
              } else {
                $('#div_transmitir').show();
                return false;
              }
            } else {
              if (confirm('ATENÇÃO\n\n'+response.message+'\n\nDeseja ' + (response.type == 'add' ? 'inserir' : 'editar') + ' croquis?')) {
                var hrefIcon = '/seguro/croqui/form/id_proposta/<?=$this->proposta->id?>';

                $('#divAjaxDialog').load(hrefIcon, function(e) {
                  $('#divAjaxDialog').dialog('open');
                  $.listCroqui(<?=$this->proposta->id?>);
                });

                $('#divAjaxDialog').dialog({
                  position : 'top',
                  title : 'Upload de Croqui',
                  autoOpen: false,
                  width:600,
                  modal:true,
                  buttons: {
                    Fechar : function() { $(this).dialog('close'); }
                  }
                });
              } else {
                $('#div_transmitir').show();
                return false;
              }
            }
					} else {
						alert(response.message);
					}
				}

				//não vai exibir a geração de boleto de o produtor estiver em RT
				if (response.status) {
					if (response.fl_exibir_boleto) {
						$('.boleto').removeClass('hide');
						$('.boleto').addClass('show');

						$('#url_boleto').attr('href','/default/gerarboleto/gerarboleto/id_proposta/'+response.id_proposta);
					}

					if (response.adicionado_fila_docusign) {
						$('#div_aviso_email').show();
					}
				}
				
				if (!response.status) {
					$('#div_transmitir').show();
				}
				
			},
			error: function (xhr, desc, er) {
				alert(xhr.responseText);
			}
		})
	}
</script>
<style>
	.aviso-email {
		margin-top:0.5em;
		padding: 5px;
		border: 1px solid #2DB3FE;
		background-color:#BFE8FF;
		color:#04679F;
		text-align: center;
	}
</style>

<? if ($this->proposta->fora_periodo_renovacao()): ?>
	<p align="center" style="color:#F00;font-size: 14px;font-weight: bold;">Esse orçamento está fora do período de comercialização.</p>
<? else: ?>
	<div id="operacoes" align="center">
		<div align="left">
			<h2 style="font-size:15pt">
				Orçamento gerado número:
				<a href="/seguro/proposta/edit/id/<?=$this->proposta->id?>" style="font-size:15pt" id="text_edit_proposta" class="icon_edit_proposta"><?=$this->proposta->doc()?></a>
				<a href="/seguro/proposta/edit/id/<?=$this->proposta->id?>" id="icon_edit_proposta" class="icon_edit_proposta"><img src="/resources/imagens/mini/edit.png" alt="edit.png" title="Editar" border="0"></a>
			</h2>
		</div>

		<div class="row" id="div_aviso_email" style="display: none;">
			<div class="aviso-email">
				<b>Orientamos que acompanhe e comunique o segurado para verificar a caixa de e-mail, pois o link para assinatura será encaminhado por e-mail. </b>
			</div>
		</div>

		<? if (Agro_Util::checkPermission('seguro:proposta:view')): ?>
		<div class="bloco imprimir">
			<h1>Imprimir Orçamento/Proposta</h1>
		</div>
		<? endif; ?>
		
		<? if(	$this->efetivar &&
		        $atributos['PROD_TRANSMISSAO_HABILITADA'] &&
		        $this->proposta->resposta('QUEST_OUTRO_SEGURO') != 1
		   ):
	    ?>
			<div class="bloco transmitir" id="div_transmitir">
				<h1>Efetivar Seguro</h1>
			</div>
		<? endif ?>

		<? if (Agro_Util::checkPermission('seguro:proposta:produto')): ?>
		<div class="bloco novo">
			<h1>Novo Orçamento</h1>
		</div>
		<? endif; ?>

		<div class="bloco pesquisar">
			<h1>Pesquisar Orçamento/Proposta</h1>
		</div>

		<div class="bloco boleto hide">
			<h1>Gerar Boleto</h1>
		</div>

		<div class="bloco boleto2 hide">
			<a target="_blank" id="url_boleto"><h1>Visualizar Boleto Gerado</h1></a>
		</div>
	</div>
<? endif; ?>