<?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');
      ?>

      <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 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="txtCod" class="font-size-lg">Código Cuenta</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" placeholder="" maxlength="14">
                      </div>
                    </div>

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

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="selNiv">Nivel</label>
                        <select class="form-control form-control-sm form-control-as" name="selNiv" id="selNiv">
                          <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>
                          <option value="6">6</option>
                          <option value="7">7</option>
                          <option value="8">8</option>
                          <option value="9">9</option>
                        </select>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtACta">Cuenta donde Acumula</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtACta" placeholder="" maxlength="14">
                      </div>
                      <div class="col-md-9">
                        <label for="txtACtaNom">Nombre de Cuenta donde Acumula</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtACtaNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <h3 class="text-light"></h3>

                    <div class="form-row">
                      <div class="col-12">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbCon" id="cbCon">
                          <label class="custom-control-label" for="cbCon">¿Tiene Sub-Cuentas?</label>
                        </div>
                      </div>
                    </div>

                    <h3 class="text-light"></h3>

                    <div class="form-row">
                      <div class="col-12">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbPresu" id="cbPresu">
                          <label class="custom-control-label" for="cbPresu">¿Es cuenta de presupuesto?</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('../busCuentas/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputCta = "txtCod";

  const txtCod = document.thisform.txtCod;
  const txtNom = document.thisform.txtNom;
  const dtFec = document.thisform.dtFec;
  const txtCon = document.thisform.txtCon;
  const selNiv = document.thisform.selNiv;
  selNiv.value=9;

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtCod.value)) {
        txtCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO"}});
        return true;
      }
      if (isNullPer(selNiv.value)) {
        selNiv.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NIVEL"}});
        return true;
      }
      if (selNiv.value!=1 && isNullPer(txtACta.value)) {
        txtACta.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la CUENTA DONDE ACUMULA"}});
        return true;
      }
    } else {
      if (isNullPer(txtCod.value)) {
        limpiar();
        return true;
      }
    }
    return false;
  }
  
  function restriccionCamposVacios() {
    if (isNullPer(txtCod.value)) {
      txtCod.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar UN NUMERO DE CUENTA"}});
      return true;
    }
    return false;
  }

  function restriccionACtaCod() {
    if (isNullPer(txtACta.value)) {
      txtACtaNom.value = "";
      return true;
    }
    return false;
  }

  function limpiar(){
    txtNom.value = "";
    selNiv.value=9;
    txtACta.value = "";
    txtACtaNom.value = "";
    cbCon.checked = 0;
    cbPresu.checked = 0;
  }

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

    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });

    // FOCUS CODIGO CUENTAS
    $("#txtCod").focus(function (){
      txtCod.value = "";
      limpiar();
    });

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

    // VALID CODIGO
    $("#txtCod")
    .focus(function() {
      inputCta = $(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-1-tab").click(); }
    })
    .change(function (){
      if (restriccion(true)) {return};

      txtNext = txtNom;

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

      parametros.append("txtCod", txtCod.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.cuentas === null) {
              nuevo = true;
            } else {
              txtNom.value = jsonJS.cuentas.cta_nom;
              selNiv.value = jsonJS.cuentas.cta_niv;
              txtACta.value = jsonJS.cuentas.cta_acta;
              txtACtaNom.value = jsonJS.cuentas.cta_actanom;
              cbCon.checked = (jsonJS.cuentas.cta_con == "S") ? 1 : 0;
              cbPresu.checked = (jsonJS.cuentas.cta_presu == "S") ? 1 : 0;
              nuevo = false;
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // VALID ACTA
    $("#txtACta")
    .focus(function() {
      inputCta = $(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-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtACtaNom");
      txtNext = document.getElementById("cbCon");

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

      const parametros = new FormData();
      parametros.append("action", "consultarACta");
      parametros.append("txtACta", 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("txtCod", txtCod.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();
              txtCod.value = "";
              txtCod.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("txtCod", txtCod.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("selNivCod", selNiv.value);
      parametros.append("txtACta", txtACta.value);
      parametros.append("cbCon", cbCon.checked);
      parametros.append("cbPresu", cbPresu.checked);

      txtCod.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) {
          console.log(jsonPhp)
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            limpiar();
            txtCod.value = "";
            txtCod.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(txtCod.value)) || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1" && inputCta == "txtCod") ? txtNom.focus() : 0;
        (relatedTarget == "#pills-1" && inputCta != "txtCod") ? $("#"+inputCta).focus() : 0;
      }
    }
  });

</script>