<?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-file-invoice"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.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 Bancos</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-2-tab" data-toggle="pill" href="#pills-2" role="tab" aria-controls="pills-2" aria-selected="false">Buscar Cuentas</a>
              </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">
                <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="numNumb" class="font-size-lg">Código</label>
                        <input type="number" class="form-control form-control-sm form-control-as" id="numNumb" placeholder="">
                      </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="txtCtab">No. Cuenta Bancaria</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtab" placeholder="">
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtac">No. Cuenta Contable</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtac" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtacNom">Nombre de Cuenta Contable</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtacNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtadif">No. Cuenta Conversion</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtadif" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtadifNom">Nombre de Cuenta Conversion</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtadifNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row align-items-end">
                      <div class="col-md-6 mt-1">
                        <div class="form-row align-items-end">
                          <div class="col-4">
                            <label for="numNumi">No. del Primer cheque de la chequera</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNumi" placeholder="">
                          </div>
                          <div class="col-4">
                            <label for="numNumf">No. del Ultimo cheque de la chequera</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNumf" placeholder="">
                          </div>
                          <div class="col-4">
                            <label for="numCorr">Numero de Cheque Actual</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCorr" placeholder="">
                          </div>
                        </div>
                      </div>
                      <div class="col-md-6 mt-1">
                        <div class="form-row align-items-end">
                          <div class="col-3">
                            <label for="selForc">No. Formato para el Cheque</label>
                            <select class="form-control form-control-sm form-control-as" name="selNiv" id="selForc">
                              <option value="0">Seleccionar...</option>
                              <option value="1">1</option>
                              <option value="2">2</option>
                              <option value="3">3</option>
                              <option value="4">4</option>
                              <option value="5">5</option>
                            </select>
                          </div>
                          <div class="col-9">
                            <label for="selMon">Tipo de Cuenta (En moneda Local/Extranjera)</label>
                            <select class="form-control form-control-sm form-control-as" name="selNiv" id="selMon">
                              <option value="0">Seleccionar...</option>
                              <option value="1">Moneda Local</option>
                              <option value="2">Moneda Extranjera</option>
                            </select>
                          </div>
                        </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('../busBancos/index.html')
                ?>
              </div>

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

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

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputNumb = "numNumb";
  var inputCta = "txtCtac";
  var inputCtaMov = "txtCtac";

  const numNumb = document.thisform.numNumb;
  const txtNom = document.thisform.txtNom;
  const txtCtab = document.thisform.txtCtab;
  const txtCtac = document.thisform.txtCtac;
  const txtCtadif = document.thisform.txtCtadif;
  const numNumi = document.thisform.numNumi;
  const numNumf = document.thisform.numNumf;
  const numCorr = document.thisform.numCorr;
  const selForc = document.thisform.selForc;
  const selMon = document.thisform.selMon;

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(numNumb.value)) {
        numNumb.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO DEL BANCO"}});
        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;
      }
      if (isNullPer(selForc.value)) {
        selForc.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar No. de formato"}});
        return true;
      }
      if (isNullPer(selMon.value)) {
        selMon.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Tipo de Moneda de la Cuenta"}});
        return true;
      }
    } else {
      if (isNullPer(numNumb.value)) {
        limpiar();
        return true;
      }
    }
    return false;
  }
  
  function restriccionCamposVacios() {
    if (isNullPer(numNumb.value)) {
      numNumb.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar EL CODIGO DEL BANCO"}});
      return true;
    }
    return false;
  }

  function restriccionCtadif() {
    if (isNullPer(txtCtadif.value)) {
      txtCtadifNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionCtac() {
    if (isNullPer(txtCtac.value)) {
      txtCtacNom.value = "";
      return true;
    }
    return false;
  }

  function limpiar(){
    txtNom.value = "";
    txtCtab.value = "";
    txtCtac.value = "";
    txtCtacNom.value = "";
    txtCtadif.value = "";
    txtCtadifNom.value = "";
    numNumi.value = 0;
    numNumf.value = 0;
    numCorr.value = 1;
    selForc.value = 1;
    selMon.value = 1;
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();

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

    // FOCUS INPUT
    $("form[name='thisform'] input, select").focus(function (){
      if (!($("input:visible:first").is(":focus"))) {
        if (restriccionCamposVacios()) {return};
      }
    });

    // VALID CODIGO
    $("#numNumb")
    .focus(function() {
      inputNumb = "numNumb";
    })
    .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("numNumb", numNumb.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.bancos === null) {
              nuevo = true;
            } else {
              txtNom.value = jsonJS.bancos.ban_nom;
              txtCtab.value = jsonJS.bancos.ban_ctab;
              selForc.value = jsonJS.bancos.ban_forma;
              selMon.value = jsonJS.bancos.ban_mon;
              numNumi.value = jsonJS.bancos.ban_numi;              
              numNumf.value = jsonJS.bancos.ban_numf;              
              numCorr.value = jsonJS.bancos.ban_corr;              
              txtCtac.value = jsonJS.bancos.ban_ctac;
              txtCtacNom.value = jsonJS.bancos.ban_ctacnom;
              txtCtadif.value = jsonJS.bancos.ban_ctadif;
              txtCtadifNom.value = jsonJS.bancos.ban_ctadnom;
              nuevo = false;
            }
            alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // VALID CTAC
    $("#txtCtac")
    .focus(function() {
      inputCtaMov = $(this).attr('id');
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtacNom");
      txtNext = document.getElementById("txtCtadif");

      $(txtThis).off("blur");
      if (restriccionCtac()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCtac");
      parametros.append("txtCtac", txtThis.value);

      $.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 {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.cuentas.cta_nom;
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // VALID CUENTA CONVERSION
    $("#txtCtadif")
    .focus(function() {
      inputCtaMov = $(this).attr('id');
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtadifNom");
      txtNext = document.getElementById("numNumi");

      $(txtThis).off("blur");
      if (restriccionCtadif()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCtadif");
      parametros.append("txtCtadif", txtThis.value);

      $.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 {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.cuentas.cta_nom;
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });


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

        parametros.append("numNumb", numNumb.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();
              numNumb.value = 0;
              numNumb.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("numNumb", numNumb.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtCtab", txtCtab.value);
      parametros.append("txtCtac", txtCtac.value);
      parametros.append("txtCtadif", txtCtadif.value);
      parametros.append("numNumi", numNumi.value);
      parametros.append("numNumf", numNumf.value);
      parametros.append("numCorr", numCorr.value);
      parametros.append("selForc", selForc.value);
      parametros.append("selMon", selMon.value);

      numNumb.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();
            numNumb.value = 0;
            numNumb.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(numNumb.value)) || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? $(target+' input:visible:eq(1)').focus() : 0;
        (relatedTarget == "#pills-2") ? $('#'+inputCtaMov).focus() : 0;
      }
    }
  });

</script>