<?php 
include_once('../../../php/sessionStart.php'); 
include_once('../../../php/db/dbExec.php');
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-stream"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
        $modalImp = "modalImp";
        include_once('../../../php/includes/modalImp.php');
      ?>

      <div class="container-as">
        <div class="row">
          <div class="col">

            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="false">Buscar Tipos Poliza</a>
              </li>
              <li class="nav-item">
                <button class="nav-link btn btn-link" id="btnILista" type="button">Listado de Tipos</button>
              </li>
            </ul>

            <div class="tab-content bg-transparent border-0" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-0" role="tabpanel" aria-labelledby="pills-0-tab">
                
                <li class="nav-item ml-auto">
                  <div class="text-center">
                    <span class="badge text-light">Usuario que modificó</span><br>
                    <span class="badge badge-warning" id="badgeUlcam"></span>
                  </div>
                </li>

                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-group">
                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="numTipoPol" class="font-size-lg">Código</label>
                        <input type="text" maxlength="3" class="form-control form-control-sm form-control-as" id="numTipoPol" placeholder="" maxlength="3">
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-7">
                        <label for="txtNom">Nombre</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtNom" placeholder="">
                      </div>
                      <div class="col-md-5">
                        <label for="txtAbrev">Abreviatura</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtAbrev" placeholder="">
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-6">
                        <label for="numCorr">Correlativo</label>
                        <input type="number" class="form-control form-control-sm form-control-as" id="numCorr"placeholder="">
                      </div>
                      <div class="col-6">
                        <label class="pr-1">Afectara Bancos</label><br>
                        <div class="custom-control custom-radio custom-control-inline">
                          <input type="radio" id="crBansn1" name="crBansn" class="custom-control-input" value="S">
                          <label class="custom-control-label" for="crBansn1">Si</label>
                        </div>
                        <div class="custom-control custom-radio custom-control-inline">
                          <input type="radio" id="crBansn2" name="crBansn" class="custom-control-input" value="N">
                          <label class="custom-control-label" for="crBansn2">No</label>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="form-row">
                      <div class="form-group col">
                        <button class="btn btn-success btn-lg btn-block" id="btnGuardar" type="button">Guardar</button>
                      </div>
                      <div class="form-group col">
                        <button class="btn btn-danger btn-lg btn-block" id="btnBorrar" type="button">Borrar</button>
                      </div>
                    </div>
                  </div>
                </form>

              </div>

              <div class="tab-pane fade" id="pills-1" role="tabpanel" aria-labelledby="pills-1-tab">
                <?php
                  $a='0';
                  $b='1';
                  include('../busTipoPol/index.html')
                ?>
              </div>

            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputTipoPol = "numTipoPol";
  //var inputCta = "txtCtac";

  const numTipoPol = document.thisform.numTipoPol;
  const txtNom = document.thisform.txtNom;
  const txtAbrev = document.thisform.txtAbrev;
  const numCorr = document.thisform.numCorr;
  const crBansn = document.thisform.crBansn;

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(numTipoPol.value)) {
        numTipoPol.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO DEL TIPO"}});
        return true;
      }
      if (isNullPer(txtNom.value)) {
        txtNom.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nombre del Tipo"}});
        return true;
      }
    } else {
      if (isNullPer(numTipoPol.value)) {
        limpiar();
        return true;
      }
    }
    return false;
  }
  
  function restriccionCamposVacios() {
    if (isNullPer(numTipoPol.value)) {
      numTipoPol.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar EL CODIGO DEL TIPO"}});
      return true;
    }
    //if (isNullPer(txtNom.value)) {
    //  txtNom.focus();
    //  alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nombre de la Cuenta Bancaria"}});
    //  return true;
    //}
    //if (isNullPer(txtCtac.value)) {
    //  txtCtac.focus();
    //  alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de la Cuenta Contable"}});
    //  return true;
    //}
    //if (isNullPer(numCorr.value)) {
    //  numCorr.focus();
    //  alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de Cheque Actual"}});
    //  return true;
    //}    

    return false;
  }

  function limpiar(){
    txtNom.value = "";
    txtAbrev.value = "";
    numCorr.value = 1;
    $("#badgeUlcam").text(textUlcam);
  }

  $(document).ready(function() {
    $("#badgeUlcam").text(textUlcam);
    $(this).find('input:visible:first').focus();

    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });
    
    // FOCUS CODIGO TIPO
    $("#numTipoPol").focus(function (){
      numTipoPol.value = "";
      limpiar();
    });

    // FOCUS INPUT
    $("form[name='thisform'] input, select").focus(function (){
      if (!($("input:visible:first").is(":focus"))) {
        if (restriccionCamposVacios()) {return};
      }
    });
    
    // VALID CODIGO
    $("#numTipoPol")
    .focus(function() {
      inputTipoPol = "numTipoPol";
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      if (restriccion(true)) {return};

      txtNext = txtNom;

      const parametros = new FormData();
      parametros.append("action", "consultar");
      parametros.append("numTipoPol", numTipoPol.value);

      txtNext.focus()

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
          alLoad("Consultando...")
        },
        success: function (jsonPhp) {
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            limpiar();
            
            if (jsonJS.tipopol === null) {
              nuevo = true;
            } else {
              txtNom.value = jsonJS.tipopol.tp_nom;
              txtAbrev.value = jsonJS.tipopol.tp_Abrev;
              numCorr.value = jsonJS.tipopol.tp_corr;
              crBansn1.checked = (jsonJS.tipopol.tp_bansn == "S") ? 1 : 0;
              crBansn2.checked = (jsonJS.tipopol.tp_bansn != "S") ? 1 : 0;
              $("#badgeUlcam").text(jsonJS.tipopol.tp_ulcam);
              nuevo = false;
            }
            alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "borrar");

        parametros.append("numTipoPol", numTipoPol.value);
        
        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Cargando...")
          },
          success: function (jsonPhp) {
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              alSuccess(jsonJS);
              limpiar();
              numTipoPol.value = "";
              numTipoPol.focus();
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};

      const parametros = new FormData();
      parametros.append("action", "guardar");

      parametros.append("nuevo", nuevo);
      parametros.append("numTipoPol", numTipoPol.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtAbrev", txtAbrev.value);
      parametros.append("numCorr", numCorr.value);
      parametros.append("crBansn1", crBansn1.checked);
      parametros.append("crBansn2", crBansn2.checked);

      numTipoPol.focus();
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
          alLoad("Cargando...")
        },
        success: function (jsonPhp) {
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            limpiar();
            numTipoPol.value = "";
            numTipoPol.focus();
          }
        }
      });
    });
  });

   // CLICK IMPRIMIR
   $("#btnILista").click(function (){
     $('#modalImp').modal('show');
     var url = window.location.origin+window.location.pathname+"print.php";

     document.getElementById("objView").data = url;
     $('#ifrView').attr('src', url);
     $('#notSupportPDF').attr('href', url);
   });

  $('#modalImp').on('hidden.bs.modal', function (e) {
    numTipoPol.focus();
  })

  // FOCUS PILL
  $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
    if (!isMobile()) {
      const target = e.target.attributes.href.value;
      const relatedTarget = e.relatedTarget.attributes.href.value;

      if ((target == "#pills-0" && isNullPer(numTipoPol.value)) || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? $(target+' input:visible:eq(1)').focus() : 0;
      }
    }
  });

</script>