<script type="text/javascript" src="/resources/javascript/seguro/propostasemailassinaturadocumento.js"></script>
<form class="formAjax" method="post" action="/endosso/ajax/tipoassinaturadocumento">
    <input type="hidden" name="id_proposta" id="id_proposta" value="<? echo $this->proposta->id; ?>" />
    <div class="geral">
        <div class="title-design">
            <div class="title"><span>Tipo de Assinatura de Documento</span></div>
        </div>
        <table>
            <tr>
                <td style="width: 10px;">
                    <?php
                    $tipos = [
                        Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_EMAIL,
                        Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_PRESENCIAL,
                        Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_SMS,
                    ];
                    $checkedAssinatura = in_array($this->tipoAssinatura, $tipos) ? 'checked' : '';
                    ?>
                    <input type="radio" id="tp_assinatura_eletronica" name="tp_assinatura" value="1" <?= $checkedAssinatura ?> />
                </td>
                <td>
                    <label for="tp_assinatura_eletronica" style="display:initial;">Assinatura Eletrônica</label>
                    <span id="helpDispensaComissaoMinima" class="styleHelp" title="Os documentos serão disponibilizados na plataforma da DocuSign para leitura, preenchimento e assinatura.">
                        <img src="/resources/imagens/Help2.jpg" border="0" width="15" />
                    </span>
                </td>
            </tr>
            <tr id="tr_tp_eletronica" style="display: none;">
                <td colspan="4" style="padding-left: 20px;">
                    <table>
                        <tr style="display: none;">
                            <td>
                                <?php
                                $checkedPresencial = $this->tipoAssinatura == Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_PRESENCIAL ? 'checked' : '';
                                ?>
                                <input type="radio" id="assinatura_presencial" name="tp_eletronica" value="<?=Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_PRESENCIAL?>" <?= $checkedPresencial ?> />
                            </td>
                            <td>
                                <label for="assinatura_presencial" style="display:initial; ">Presencial</label>
                                <span id="helpDispensaComissaoMinima" class="styleHelp" title="Será enviado um link de acesso ao corretor, o qual deve disponibilizar um tablet ou celular para o segurado proceder com a assinatura.">
                                    <img src="/resources/imagens/Help2.jpg" border="0" width="15" />
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <?php
                                $checkedEmail = $this->tipoAssinatura == Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_EMAIL ? 'checked' : '';
                                $displayEmail = $this->tipoAssinatura == Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_EMAIL ? '' : 'style="display:none"';
                                ?>
                                <input type="radio" id="assinatura_email" name="tp_eletronica" value="<?=Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_EMAIL?>" <?= $checkedEmail ?> />
                            </td>
                            <td>
                                <label for="assinatura_email" style="display:initial;">Por e-mail</label>
                                <span id="helpDispensaComissaoMinima" class="styleHelp" title="Os links de acesso aos documentos serão enviados aos e-mails cadastrados.">
                                    <img src="/resources/imagens/Help2.jpg" border="0" width="15" />
                                </span>
                            </td>
                        </tr>
                        <tr id="tr_email_proponente" <?= $displayEmail ?>>
                            <td></td>
                            <td>
                                <label for="ds_email_segurado_assinatura"><b>E-mail do Segurado:</b></label>
                                <input type="email" id="ds_email_segurado_assinatura" name="ds_email_segurado_assinatura" class="validarEmail" size="45" value="<?=$this->ds_email_segurado?>">
                            </td>
                        </tr>
                        <?php  $displayJustificativa = !empty($this->proponente['nr_justificativa']) ? '' : 'style="display:none"';?>
                        <tr id="linha_justificativa" <?= $displayJustificativa ?>>
                            <td></td>
                            <td>
                                <div class="row">
                                    <fieldset>
                                        <legend>Justificativa</legend>
                                        <div class="field required">
                                            <label class="optional" for="motivos">Selecione o motivo pelo qual foi informado o e-mail do corretor:</label>
                                            <input type="radio" id="motivo_1" value="1" name="proponente[nr_justificativa]" <?=($this->proponente['nr_justificativa'] == 1 ? 'checked' : '')?> style="margin-top: 5px">Segurado não possui e-mail. 
                                            <br>
                                            <input type="radio" id="motivo_2" value="2" name="proponente[nr_justificativa]" <?=($this->proponente['nr_justificativa'] == 2 ? 'checked' : '')?>  style="margin-top: 5px">Outro.
                                            <input type="text" id="motivo_descrito" name="proponente[ds_justificativa]" class="<?=($this->proponente['nr_justificativa'] == 2 ? 'show' : 'hide')?>" value="<?=$this->proponente['ds_justificativa'] ?>"  size="100">
                                        </div>
                                    </fieldset>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <?php
                                $checkedCelular = $this->tipoAssinatura == Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_SMS ? 'checked' : '';
                                $displayCelular = $this->tipoAssinatura == Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_SMS ? '' : 'style="display:none"';
                                ?>
                                <input type="radio" id="assinatura_sms" name="tp_eletronica" value="<?=Seguro_Model_PropostasTipoAssinaturaDocumento::ELETRONICA_SMS?>" <?= $checkedCelular ?> />
                            </td>
                            <td>
                                <label for="assinatura_sms" style="display:initial;">Por SMS</label>
                                <span id="helpDispensaComissaoMinima" class="styleHelp" title="O link de acesso aos documentos para assinatura do Segurado será enviado para o telefone celular informado neste local.">
                                    <img src="/resources/imagens/Help2.jpg" border="0" width="15" />
                                </span>
                            </td>
                        </tr>
                        <tr id="tr_celular_proponente" <?= $displayCelular ?>>
                            <td>
                            </td>
                            <td>
                                <label for="ds_celular_segurado_assinatura"><b>Telefone Celular do Segurado (Obrigatório que seja do segurado):</b></label>
                                <input type="text" id="ds_celular_segurado_assinatura" name="ds_celular_segurado_assinatura" class="telefone validarTelefone" size="14" value="<?=$this->ds_celular_segurado?>">
                            </td>
                        </tr>
                    </table>
                    <br>
                </td>
            </tr>
            <tr>
                <td>
                    <?php
                    $checkedManual = $this->tipoAssinatura == Seguro_Model_PropostasTipoAssinaturaDocumento::MANUAL ? 'checked' : '';
                    ?>
                    <input type="radio" id="tp_assinatura_manual" name="tp_assinatura" value="2" <?= $checkedManual ?> />
                </td>
                <td>
                    <label for="tp_assinatura_manual" style="display:initial;">Assinatura Manual</label>
                    <span id="helpDispensaComissaoMinima" class="styleHelp" title="Os documentos devem ser impressos, assinados, digitalizados e anexados no Agronet.">
                        <img src="/resources/imagens/Help2.jpg" border="0" width="15" />
                    </span>
                </td>
            </tr>
        </table>
        <div id="dialogMais"></div>
    </div>
    <p>&nbsp;</p>
    <div class="row">
        <button type="button" name="btnSalvar" class="validarLiberacaoSalvar" id="btnSalvar">Salvar</button>
    </div>
</form>
<script>
    $(document).ready(function() {
        $('#tp_assinatura_eletronica').click(function() {
            $('#tr_email_proponente').hide();
            $('#tr_celular_proponente').hide();
            $('#tr_tp_eletronica').show();
            $('#assinatura_presencial').prop('checked', false);
            $('#assinatura_email').prop('checked', false);
            $('#assinatura_sms').prop('checked', false);
            $.resetLinhaJustificativa();
        });

        $('#tp_assinatura_manual').click(function() {
            $('#tr_email_proponente').hide();
            $('#tr_celular_proponente').hide();
            $('#tr_tp_eletronica').hide();
            $('#assinatura_presencial').prop('checked', false);
            $('#assinatura_email').prop('checked', false);
            $('#assinatura_sms').prop('checked', false);
            $.resetLinhaJustificativa();
        });

        $('#assinatura_presencial').click(function() {
            $('#tr_email_proponente').hide();
            $.resetLinhaJustificativa();
        });

        $('#assinatura_email').click(function() {
            $('#tr_email_proponente').show();
            $('#tr_celular_proponente').hide();
            
            $.ajax({
                url: '/seguro/propostaajax/getemailproponente',
                data: {
                    id_proposta: $('#id_proposta').val()
                },
                dataType: 'json',
                type: 'POST',
                success: function (response) {
                    $.resetLinhaJustificativa();
                    $('#ds_email_segurado_assinatura').val('');
				
                    if (response.valid && response.email != '' && response.email != null) {
                        if (confirm('Confirma que o seguinte e-mail corresponde ao e-mail do segurado: ' + response.email + '?')) {
                            $('#ds_email_segurado_assinatura').val(response.email);
                            return;
                        }
                    }

                    // BLOCO COMENTADO COM A LÓGICA DE QUANDO A OPÇÃO "ASSINATURA ELETRÔNICA > PRESENCIAL" ESTIVER IMPLEMENTADA
                    /*
                    if (response.email != '' && response.email != null) {
                        if (confirm('Confirma que o seguinte e-mail corresponde ao e-mail do segurado: ' + response.email + '?')) {
                            $('#ds_email_segurado_assinatura').val(response.email);
                            
                            if (!response.valid) {
                                $('#linha_justificativa').show();
                                $("input[name='proponente[nr_justificativa]'][value=" + response.nr_justificativa + "]").click();
                                $('#motivo_descrito').val(response.ds_justificativa);
                            }
                            return;
                        }
                    }

                    $('#ds_email_segurado_assinatura').val('');
                    */
                }
            });
        });

        $('#assinatura_sms').click(function() {
            $('#ds_celular_segurado_assinatura').val('');
            $('#tr_email_proponente').hide();
            $('#tr_celular_proponente').show();

            $.ajax({
                url: '/seguro/propostaajax/getcelularproponente',
                data: {
                    id_proposta: $('#id_proposta').val()
                },
                dataType: 'json',
                type: 'POST',
                success: function (response) {

                    $.resetLinhaJustificativa();

                    if (response.valid && response.celular != '' && response.celular != null) {
                        if (confirm('Confirma que o seguinte telefone celular corresponde ao telefone celular do segurado: ' + response.celular + '?')) {
                            $('#ds_celular_segurado_assinatura').val(response.celular);
                            return;
                        }
                    }
                }
            });
	    });

        $('#btnSalvar').click(function() {
            let tpAssinatura = 4;
            let idPropostas = [];
            idPropostas.push($('#id_proposta').val());

            if ($('#tp_assinatura_eletronica').is(':checked') && 
                !$('#assinatura_presencial').is(':checked') && 
                !$('#assinatura_email').is(':checked') &&
                !$('#assinatura_sms').is(':checked')
            ) {
                alert("Quando selecionado tipo de assinatura eletrônica,  deve ser informado se a mesma é por e-mail ou por SMS.");
                $('#bttConcluir').button("enable");
                return false;
            }


            if ($('#assinatura_email').is(':checked')) {
                tpAssinatura = 1;
            } else if ($('#assinatura_presencial').is(':checked')) {
                tpAssinatura = 2;
            } else if ($('#tp_assinatura_manual').is(':checked')) {
                tpAssinatura = 3;
            } else if ($('#assinatura_sms').is(':checked')) {
                tpAssinatura = 5;
            }

            if (tpAssinatura == 1) {
                if ($('#ds_email_segurado_assinatura').val() == '') {
                    alert('E-mail do Segurado não informado.');
                    $("#ds_email_segurado_assinatura").focus();
                    return false;
                }

                if ($('#ds_email_segurado_assinatura').val() != '' && !$.validarEmail($("#ds_email_segurado_assinatura").val())) {
                    alert('Formato do e-mail do Segurado é inválido.');
                    $("#ds_email_segurado_assinatura").val('');
                    $("#ds_email_segurado_assinatura").focus();
                    return false;
                }

                if (!$.validarObrigatoriedadeJustificativa()) {
                    alert('Selecione a justificativa pelo qual foi informado o e-mail do corretor.');
                    return false;
                }
        
                if (!$.validarObrigatoriedadeMotivoDescrito()) {
                    alert('Descreva a justificativa pelo qual foi informado o e-mail do corretor, quando selecionada a opção Outro.');
                    return false;
                }
            }

            if (tpAssinatura == 5) {
                if ($("#ds_celular_segurado_assinatura").val() == '') {
                    alert('Telefone Celular do Segurado não informado.');
                    $("#ds_celular_segurado_assinatura").focus();
                    $('#bttConcluir').button("enable");
                    return false;
                }

                if (!$.validarCelular($("#ds_celular_segurado_assinatura").val())) {
                    alert('Formato do Telefone Celular do Segurado é inválido.');
                    $("#ds_celular_segurado_assinatura").val('');
                    $("#ds_celular_segurado_assinatura").focus();
                    $('#bttConcluir').button("enable");
                    return false;
                }
            }

            $.ajax({
                url: '/seguro/propostastipoassinaturadocumento/editar',
                data: {
                    id_propostas: idPropostas,
                    tipo_assinatura: tpAssinatura,
                    ds_email_proponente: $("#ds_email_segurado_assinatura").val(),
                    ds_celular_proponente: $("#ds_celular_segurado_assinatura").val(),
                    proponente: {nr_justificativa: $("input[name='proponente[nr_justificativa]']:checked").val(), ds_justificativa: $('#motivo_descrito').val()}
                },
                type: 'POST',
                dataType: 'json',
                success: function(response) {

                    alert(response.message);

                    if (response.status == false) {
                        return;
                    }
                },
                error: function(xhr, desc, er) {
                    alert(xhr.responseText);
                }
            });
        });

        if ($('#tp_assinatura_eletronica').is(':checked')) {
            $('#tr_tp_eletronica').show();
        }
    });
</script>
