<?php
$Session = new Zend_Session_Namespace('carrega_proposta');

// Model para preencher os selects
$corretor = $this->proposta->corretor();
$preposto = $this->proposta->preposto();
$questionarios = $this->proposta->questionario();
$respostas = $this->proposta->respostas();
$propriedades = $this->proposta->atributos('PROPRIEDADE');

echo $this->render('produto.phtml');


$dataAux = !empty($this->proposta->dt_transmissao) ? $this->proposta->dt_transmissao : $this->proposta->dt_criacao;
$aplicarNovaLeiSeguro = strtotime($dataAux) >= strtotime(DATA_INICIO_NOVA_LEI_SEGURO)
  || $this->proposta->id_status == Seguro_Enum_PropostaStatus::ID_NAO_ENVIADA;

?>

<style>
    .fontColorRed {
        color: #ff0000;
    }
</style>

<?php
if ($this->proposta->fora_periodo_renovacao()): ?>
  <p align="center" class="fontColorRed" style="font-size: 14px;font-weight: bold;">Esse orçamento está fora do período
    de comercialização.</p>
<?php
endif;
?>

<br/>

<script type="text/javascript" src="/resources/jquery/jquery.agro.js"></script>

<form class="formDefault" id="formDefault" method="post" action="/seguro/proposta/unidades">
  <input type="hidden" id="aplicar-nova-lei-seguro" value="<?php echo $aplicarNovaLeiSeguro ? 1 : 0; ?>">
  <input type="hidden" name="md" value="<?= md5($this->proposta->id . $_SERVER['SERVER_ADDR']) ?>" id="md"/>
  <input type="hidden" name="usuario_logado" value="<?= $this->usuario_logado ?>" id="usuario_logado"/>
  <!-- solicitacao 2849 -->
  <input type="hidden" name="id_produto" value="<?= $this->proposta->id_produto ?>" id="id_produto"/>
  <input type="hidden" name="id_corretor" value="<?= $corretor['id_usuario'] ?>" id="id_corretor"/>
  <input type="hidden" name="id_preposto" value="<?= $preposto['id_usuario'] ?>" id="id_preposto"/>
  <input type="hidden" name="id_proposta_renovada" value="<?= $this->proposta->id_proposta_renovada ?>"
         id="id_proposta_renovada"/>
  <input type="hidden" name="id_proposta" value="<?= $this->proposta->id ?>" id="id_proposta"/>

  <input type="hidden" name="vl_sub_estadual" value="<?= $propriedades['PROD_PERCENT_SUBVENCAO_ESTADUAL'] ?>"
         id="vl_sub_estadual"/>
  <input type="hidden" name="vl_sub_estadual_pr" value="<?= $propriedades['PROD_PERCENT_SUBVENCAO_ESTADUAL_PR'] ?>"
         id="vl_sub_estadual_pr"/>
  <input type="hidden" name="vl_cadpro" value="<?= $propriedades['PROD_CADPRO'] ?>" id="vl_cadpro"/>
  <input type="hidden" name="vl_subvencao_federal" value="<?= $propriedades['PROD_PERCENT_SUBVENCAO_FEDERAL'] ?>"
         id="vl_subvencao_federal"/>

  <div class="abaProposta">
    <ul>
      <li id="segurado" class="current">Dados do Segurado</li>
      <li id="unidades" class="">Unidades Seguradas / Croqui</li>
      <li id="premio" class="">Cálculo do Prêmio</li>
    </ul>
  </div>

  <div class="abaContent">
    <div class="geral">
      <!-- DADOS DO PROPONENTE -->

      <div align="right" style="display: table; padding-bottom: 10px;">
        <label class="required">Campos Obrigatórios</label>
      </div>
        <?php $this->proponente($this->proposta); ?>

      <!-- DADOS DA PROPRIEDADE -->
        <?= $this->title('Identificação da Propriedade') ?>
      <table width="100%" cellpadding="0" cellspacing="0" border="0" id="table_propriedade">
        <tr>
          <td valign="top">
            <fieldset>
              <legend>Endereço da Propriedade</legend>
              <table width="100%" cellpadding="2" cellspacing="1" border="0" class="tb_endereco_propriedade">
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td nowrap="nowrap" width="1%" class="required">
                          <label for="ds_endereco_cep_propriedade" class="optional">CEP</label>
                          <input type="text" name="propriedade[ds_endereco_cep]" id="ds_endereco_cep_propriedade_busca"
                                 value="<?= $this->propriedade['ds_endereco_cep'] ?>" class="cep" maxlength="10"
                                 size="10">
                            <?= $this->form->ds_endereco_cep_propriedade ?>
                        </td>
                        <td id="busca_cep">
                          <br/>Se você não souber o CEP, <a
                            href="/cep/search/n/ds_endereco_cep_propriedade_busca"
                            class="searchCep fontColorRed" rel="ds_endereco_cep_propriedade">
                            <b>Clique aqui</b></a> para buscar.
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr>
                  <td>
                    <input type="hidden" name="propriedade[id_estado]" value="<?= $this->propriedade['id_estado'] ?>"
                           id="id_estado_propriedade">
                    <input type="hidden" name="propriedade[id_municipio]"
                           value="<?= $this->propriedade['id_municipio'] ?>" id="id_municipio_propriedade">

                    <table>
                      <tr>
                        <td class="required">
                          <label for="ds_nome_estado_propriedade" class="optional">UF</label>
                          <input type="text" name="propriedade[ds_nome_estado]" id="ds_nome_estado_propriedade"
                                 value="<?= ($this->propriedade['ds_sigla'] != 'NL' ? $this->propriedade['ds_sigla'] : '') ?>"
                                 disabled maxlength="2" class="upper" size="2">
                        </td>
                        <td class="required">
                          <label for="ds_nome_municipio_propriedade" class="optional">Município</label>
                          <input type="text" name="propriedade[ds_nome_municipio]" id="ds_nome_municipio_propriedade"
                                 value="<?= ($this->propriedade['ds_nome_municipio'] != 'NULO' ? $this->propriedade['ds_nome_municipio'] : '') ?>"
                                 maxlength="255" disabled class="upper" size="103">
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td>
                          <label for="ds_endereco_bairro_propriedade" class="optional">Bairro</label>
                          <input type="text" name="propriedade[ds_endereco_bairro]" id="ds_endereco_bairro_propriedade"
                                 value="<?= $this->propriedade['ds_endereco_bairro'] ?>" maxlength="30" class="upper"
                                 size="30">
                        </td>
                        <td class="required">
                          <label for="ds_endereco_propriedade" class="optional">Endereço</label>
                          <input type="text" name="propriedade[ds_endereco]" id="ds_endereco_propriedade"
                                 value="<?= $this->propriedade['ds_endereco'] ?>" maxlength="100" class="upper"
                                 size="75">
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td class="required">
                          <label for="ds_endereco_nro_propriedade" class="optional">Número</label>
                          <input type="text" name="propriedade[ds_endereco_nro]" id="ds_endereco_nro_propriedade"
                                 value="<?= $this->propriedade['ds_endereco_nro'] ?>" maxlength="8" class="integer"
                                 size="25">
                        </td>
                        <td>
                          <label for="ds_endereco_complemento_propriedade" class="optional">Complemento</label>
                          <input type="text" name="propriedade[ds_endereco_complemento]"
                                 id="ds_endereco_complemento_propriedade"
                                 value="<?= $this->propriedade['ds_endereco_complemento'] ?>" maxlength="100"
                                 class="upper" size="25">
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td class="required">
                          <label for="ds_coordenadas" class="optional">Coordenadas Geográficas</label>
                          <input type="text" name="propriedade[ds_coordenadas]" id="ds_coordenadas"
                                 value="<?= $this->propriedade['ds_coordenadas'] ?>" class="coordenadas" maxlength="128"
                                 size="32">
                            <?
                            if ($this->propriedade['ds_coordenadas']) {
                                $stCoordenada = str_replace(" ,", "", $this->propriedade['ds_coordenadas']);
                                $stCoordenada = str_replace(",", "", $stCoordenada);
                                $stCoordenada = str_replace("-", "", $stCoordenada);
                                $arCoordenada = explode(" ", $stCoordenada);
                            }
                            ?>
                        </td>
                        <td>
                          <br/><i><b>Exemplo: </b>-99 99 99 -99 99 99</i>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td class="required">
                          <label for="ds_nome_propriedade" class="optional">Nome Propriedade</label>
                          <input type="text" name="propriedade[ds_nome_propriedade]" id="ds_nome_propriedade"
                                 value="<?= $this->propriedade['ds_nome_propriedade'] ?>" maxlength="60" class="upper"
                                 size="109">
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>

                <tr>
                  <td>
                    <div class="padding-5">
                      <a href="#" class="fontColorRed" id="cliqueDicaAquiAcessoSede">
                        <strong>Clique aqui</strong>
                      </a> se desejar incluir "Dica de Acesso à Sede"
                    </div>
                  </td>
                </tr>

                <tr id="trDicaAcessoSede" class="hide">
                  <td>
                    <table>
                      <tr>
                        <td>
                          <label for="ds_referencia_localizacao" class="optional">Dica de Acesso à Sede</label>
                          <textarea name="propriedade[ds_referencia_localizacao]" id="ds_referencia_localizacao"
                                    maxlength="255" cols="106" class="upper"
                                    rows="5"><?= $this->propriedade['ds_referencia_localizacao'] ?></textarea>
                          <div align="right">
                            Restam <input type="text" id="charlimitinfo-ds_referencia_localizacao" size="3"
                                          class="integer"/> Caracteres
                          </div>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td>
                          <label for="ds_pessoa_autorizada" class="optional">
                            Há representante(s) do proponente a acompanhar a(s) vistoria(s)?
                          </label>
                          <select name="propriedade[ds_pessoa_autorizada]" id="ds_pessoa_autorizada">
                            <option value="N"
                                    label="NÃO" <?= ($this->propriedade['ds_pessoa_autorizada'] == 'N' ? 'selected' : '') ?>>
                              NÃO
                            </option>
                            <option value="S"
                                    label="SIM" <?= ($this->propriedade['ds_pessoa_autorizada'] == 'S' ? 'selected' : '') ?>>
                              SIM
                            </option>
                          </select>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                  <?php
                  $class = ($this->propriedade['ds_pessoa_autorizada'] == 'S' ? 'show' : 'hide');
                  ?>
                <tr class="<?= $class ?>" id="div_outra_pessoa">
                  <td>
                    <table>
                        <?php
                        if ($this->pessoa_autorizada) {
                            foreach ($this->pessoa_autorizada as $key => $pessoa) {
                                ?>
                              <tr id="tr_pessoa_autorizada" class="tr_pessoa_autorizada">
                                <td>
                                  <input type="hidden" name="propriedade[ds_dados_pessoa_autorizada][<?= $key ?>][id]"
                                         value="<?= $pessoa['id'] ?>"/>
                                  <label for="ds_nome_outra_pessoa" class="required">Nome da outra pessoa</label>
                                  <input type="text"
                                         name="propriedade[ds_dados_pessoa_autorizada][<?= $key ?>][ds_nome_outra_pessoa]"
                                         id="ds_nome_outra_pessoa" value="<?= $pessoa['ds_pessoa_autorizada'] ?>"
                                         maxlength="100" class="upper" size="50">
                                </td>
                                <td>
                                  <label for="ds_cpf_outra_pessoa" class="required">CPF</label>
                                  <input type="text"
                                         name="propriedade[ds_dados_pessoa_autorizada][<?= $key ?>][ds_cpf_outra_pessoa]"
                                         id="ds_cpf_outra_pessoa" class="cpf_outra_pessoa"
                                         value="<?= $pessoa['cpf_cnpj'] ?>" onblur="validarProponenteCPF(this)"
                                         maxlength="18" size="19">
                                </td>
                                <td>
                                  <label for="ds_grau_parentesco" class="required">
                                    Parentesco e/ou Grau de Relacionamento
                                  </label>
                                  <input type="text"
                                         name="propriedade[ds_dados_pessoa_autorizada][<?= $key ?>][ds_grau_parentesco]"
                                         id="ds_grau_parentesco" value="<?= $pessoa['ds_grau_parentesco'] ?>"
                                         class="upper" maxlength="100" size="40">
                                </td>
                                <td>
                                  <label for="ds_telefone_outra_pessoa" class="required">Telefone</label>
                                  <input type="text"
                                         name="propriedade[ds_dados_pessoa_autorizada][<?= $key ?>][ds_telefone_outra_pessoa]"
                                         id="ds_telefone_outra_pessoa" value="<?= $pessoa['ds_telefone'] ?>"
                                         class="telefone" maxlength="20" size="14">
                                </td>
                                <td>
                                    <?php
                                    if ($key == 0) {
                                        ?>
                                      <a href="#">
                                        <img src="/resources/imagens/mini/add.png" id="addAutorizado"/>
                                      </a>
                                      <span id="cliqueAqui">Adicionar Pessoa Autorizada</span>
                                        <?php
                                    } else {
                                        ?>
                                      <a href="#">
                                        <img src="/resources/imagens/icon/delete2.png" id="delAutorizado"/>
                                      </a>
                                      <span id="cliqueAqui">Remover Pessoa Autorizada</span>
                                        <?
                                    } ?>
                                </td>
                              </tr>
                                <?php
                            }
                        } else {
                            ?>

                          <tr id="tr_pessoa_autorizada" class="tr_pessoa_autorizada">
                            <td>
                              <input type="hidden" name="propriedade[ds_dados_pessoa_autorizada][0][id]" value=""/>
                              <label for="ds_nome_outra_pessoa" class="optional">Nome da outra pessoa</label>
                              <input type="text" name="propriedade[ds_dados_pessoa_autorizada][0][ds_nome_outra_pessoa]"
                                     id="ds_nome_outra_pessoa" value=""
                                     maxlength="100" class="upper element_required" size="50"
                                     title="Nome da Pessoa Autorizada">
                            </td>
                            <td>
                              <label for="ds_cpf_outra_pessoa" class="optional">CPF</label>
                              <input type="text" name="propriedade[ds_dados_pessoa_autorizada][0][ds_cpf_outra_pessoa]"
                                     id="ds_cpf_outra_pessoa" value=""
                                     class="cpf element_required" maxlength="18" size="19"
                                     title="CPF da Pessoa Autorizada" onblur="validarProponenteCPF(this)">
                            </td>
                            <td>
                              <label for="ds_grau_parentesco" class="optional">
                                Parentesco e/ou Grau de Relacionamento
                              </label>
                              <input type="text" name="propriedade[ds_dados_pessoa_autorizada][0][ds_grau_parentesco]"
                                     id="ds_grau_parentesco" value=""
                                     class="upper element_required" maxlength="100" size="40"
                                     title="Grau de Parentesco da Pessoa Autorizada">
                            </td>
                            <td>
                              <label for="ds_telefone_outra_pessoa" class="optional">Telefone</label>
                              <input type="text"
                                     name="propriedade[ds_dados_pessoa_autorizada][0][ds_telefone_outra_pessoa]"
                                     id="ds_telefone_outra_pessoa" value=""
                                     class="telefone element_required" maxlength="20" size="14"
                                     title="Telefone da Pessoa Autorizada">
                            </td>
                            <td>
                              <a href="#">
                                <img src="/resources/imagens/mini/add.png" id="addAutorizado"/>
                              </a>
                              <span id="cliqueAqui">Adicionar outra Pessoa Autorizada</span>
                            </td>
                          </tr>
                            <?php
                        }
                        ?>
                    </table>
                  </td>
                </tr>
              </table>
            </fieldset>
          </td>
        </tr>
      </table>

      <!-- QUESTIONARIO -->
      <div id="questionario">
          <?= $this->title('Questionário') ?>
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
          <?php if ($aplicarNovaLeiSeguro) {?>
            <tr>
              <td>
                <fieldset>
                  <legend>
                    <b style="color:red; font-size:12px;">Atenção</b>
                  </legend>
                  <div style="text-align:center;">
                    <p style="font-size:12px; font-weight:bold; width:50%; margin: auto;">
                      É fundamental que todas as informações fornecidas na formação do contrato de seguro sejam completas e precisas. O descumprimento do dever de informar pode resultar na perda de direitos ou na anulação do contrato de seguro. Caso tenha dúvidas sobre quais informações são relevantes, consulte nosso atendimento.
                    </p>
                  </div>
                </fieldset>
              </td>
            </tr>
          <?php }?>
          <tr>
            <td valign="top">
                <?= $this->montaQuetionario(
                  $questionarios,
                  $respostas,
                    Atendimento_Enum_Questionario::PERGUNTAS_IGNORAR,
                  $preposto,
                  $propriedades
                ) ?>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
  <input type="hidden" name="bttProximo">
  <fieldset id="fieldset-buttons">
      <?php
      if ($this->proposta->fora_periodo_renovacao() && $this->proposta->id_proposta_renovada != ''): ?>
        <p>Esse orçamento está fora do período de comercialização.</p>
      <?php
      else: ?>
        <button id="salvar" type="button" onclick="isCoordenadasSedeMunicipio();">Próximo</button>
      <?php
      endif; ?>
  </fieldset>
</form>
<?= $this->montaJsQuetionario($questionarios, $respostas);

if ($this->proposta->id_proposta_renovada != ''): ?>
  <script>
    $.bloqueiaRenovacao();
  </script>
<?php
endif;

// SE FOR PROPOSTA DEVOLVIDA
if ($this->proposta->id_status == 59): ?>
  <script>
    $.bloqueiaProponente();
  </script>
<?php
endif;
?>

<script>
  
  var cadpro_click = function () {
    if ($("input[name='questionario[QUEST_SUBVENCAO_ESTADUAL]']:checked").val() == 1) {
      $('.q-QUEST_CADPRO_VALOR').attr('style', 'display:block');
      
    } else {
      $('.q-QUEST_CADPRO_VALOR').attr('style', 'display:none');
      $("input[name='questionario[QUEST_CADPRO_VALOR]']").val('');
    }
  }

  <?php
  if ($this->proposta->atributos('PROPRIEDADE', 'PROD_NUMERO_MAXIMO_PENCAS')): ?>
    $('input[name="questionario[QUEST_PENCAS_HASTE]"]').blur(function () {
      if ($(this).val() > <?=$this->proposta->atributos('PROPRIEDADE', 'PROD_NUMERO_MAXIMO_PENCAS')?>) {
        alert('O Valor não pode ultrapassar <?=$this->proposta->atributos('PROPRIEDADE', 'PROD_NUMERO_MAXIMO_PENCAS')?>');
        $(this).val('');
        return false;
      }
    });
  <?php
  endif;

  $subvencao = $this->proposta->subvencaoCultura();

  if ($subvencao['liberado']):
      if ($subvencao['usado'] < $subvencao['liberado']): ?>
          $('.QUEST_SUBVENCAO_FEDERAL').attr('disabled', false);
      <?php
      else:
      ?>
          $('.QUEST_SUBVENCAO_FEDERAL').attr('disabled', true);
      <?php
      endif;
  else:
      ?>
      $('.QUEST_SUBVENCAO_FEDERAL').attr('disabled', true);
  <?php
  endif;

  $subvencaoGrupo = $this->proposta->subvencaoCulturaGrupoCorretores();

  if ($subvencaoGrupo['liberado'] && $subvencaoGrupo['usado'] < $subvencaoGrupo['liberado']): ?>
          $('.QUEST_SUBVENCAO_FEDERAL').attr('disabled', false);
  <?php
  endif;
  ?>

  $('.QUEST_ENQUADRADO_PRONAMP').attr('disabled', true);
  $('.QUEST_PRODUTOR_ORGANICO').attr('disabled', true);
  $('.QUEST_ENQUADRADO_PIN').attr('disabled', true);
  $('.QUEST_ZONEAMENTO_ENQUADRADO_MAPA').attr('disabled', true);

  $(window).bind('load', function () {



    $("input[name='questionario[QUEST_CADPRO_VALOR]']").live('focus', function() {
      $(this).attr('maxLength', 10);
    }
  );
  $("input[name='questionario[QUEST_CADPRO_VALOR]']").live('blur', function() {
    const regex = /0000000000/;
      if(($(this).val().replace(/ /g,'').length < 10) || regex.test($(this).val())){
        alert('Necessário informar 10 dígitos no campo Cadastro do Produtor Rural (CADPRO). ');
      }
    }
  );

    if (($('#vl_cadpro').val() == 1) && ($('#ds_nome_estado_propriedade').val() == 'PR')) {
      $('.QUEST_SUBVENCAO_ESTADUAL').bind('click', cadpro_click);
      if ($("input[name='questionario[QUEST_SUBVENCAO_ESTADUAL]']:checked").val() == 1) {
        $('.q-QUEST_CADPRO_VALOR').attr('style', 'display:block');
        
      }
    } else {
      $('.QUEST_SUBVENCAO_ESTADUAL').unbind('click');
      $('.q-QUEST_CADPRO_VALOR').attr('style', 'display:none');
      $("input[name='questionario[QUEST_CADPRO_VALOR]']").val('');
    }
  });

  <?php
  $produto = $this->proposta->produto();

  if ($produto["ds_nome_cultura"] == "Pastagem"): ?>
      $('#tp_pessoa option:not(:selected)').attr('disabled', true);
      $('#cpf_cnpj').attr('readonly', true);
      $('#ds_nome_proponente').attr('readonly', true);

      $('#q-QUEST_PASTAGEM_TIPO_REBANHO option:not(:selected)').attr('disabled', true);
      $('#q-QUEST_PASTAGEM_TIPO_PASTO option:not(:selected)').attr('disabled', true);
      $('#q-QUEST_PASTAGEM_TIPO_FINALIDADE_REBANHO option:not(:selected)').attr('disabled', true);
      $("input[name='questionario[QUEST_PASTAGEM_LOTACAO_HA]']").attr('readonly', true);
  <?php
  endif;
  ?>
</script>