<?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">Nomenclaturas</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 Empresa</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 align-items-end">
                      <div class="col-md-2">
                        <label for="txtCodo" class="font-size-lg">Empresa Origen</label>
                        <input type="text" class="form-control form-control-sm form-control-as font-size-lg" id="txtCodo" placeholder="" maxlength="3">
                      </div>
                      <div class="col-md-9">
                        <input type="text" class="form-control form-control-sm form-control-as form-info text-warning font-size-lg" id="txtCodoNom" placeholder="" disabled>
                      </div>
                    </div>

                    
                    <div class="form-row align-items-end mt-4">
                      <div class="col-md-2">
                        <label for="txtCodd" class="font-size-lg">Empresa Destino</label>
                        <input type="text" class="form-control form-control-sm form-control-as font-size-lg" id="txtCodd" placeholder="" maxlength="3">
                      </div>
                      <div class="col-md-9">
                        <input type="text" class="form-control form-control-sm form-control-as font-size-lg form-info text-warning" id="txtCoddNom" placeholder="" disabled>
                      </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">Copiar Nomenclatura</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('../busEmpresas/index.html')
                ?>
              </div>

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

<script>
  var pressEnter = false;
  var inputEmpresas = "txtCodo";

  const txtCodo = document.thisform.txtCodo;
  const txtCodoNom = document.thisform.txtCodoNom;
  const txtCodd = document.thisform.txtCodd;
  const txtCoddNom = document.thisform.txtCoddNom;
  
  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtCodo.value)) {
        txtCodo.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar EL CODIGO DE LA EMPRESA ORIGEN"}});
        return true;
      }
      if (isNullPer(txtCodd.value)) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar EL CODIGO DE LA EMPRESA DESTINO"}});
        return true;
      }
    }
    return false;
  }

  function restriccionCodo() {
    if (isNullPer(txtCodo.value)) {
      txtCodoNom.value = "";
      return true;
    }
    return false;
  }
  
  function restriccionCodd() {
    if (isNullPer(txtCodd.value)) {
      txtCoddNom.value = "";
      return true;
    }
    return false;
  }

  function limpiar(){
    txtCodo.value = <?php echo $_SESSION["empCod"] ?>;
    txtCodoNom.value = '<?php echo $_SESSION["empNom"] ?>';
    txtCodd.value = "";
    txtCoddNom.value = "";
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    txtCodo.value = <?php echo $_SESSION["empCod"] ?>;
    txtCodoNom.value = '<?php echo $_SESSION["empNom"] ?>';

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

    // VALID EMPRESA ORIGEN
    $("#txtCodo")
    .focus(function() {
      inputEmpresas = $(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 = txtCodoNom;
      txtNext = txtCodd;

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

      const parametros = new FormData();
      parametros.append("action", "consultarEmp");
      parametros.append("txtCod", txtCodo.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.empresas === null) {
              txtGetValue.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"La Empresa "+txtThis.value+" no ha sido registrada", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.empresas.emp_nom;
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });
    

    // VALID EMPRESA DESTINO
    $("#txtCodd")
    .focus(function() {
      inputEmpresas = $(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 = txtCoddNom;
      txtNext = btnGuardar;

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

      const parametros = new FormData();
      parametros.append("action", "consultarEmp");
      parametros.append("txtCod", txtCodd.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.empresas === null) {
              txtGetValue.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"La Empresa "+txtThis.value+" no ha sido registrada", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.empresas.emp_nom;
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });


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

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

        parametros.append("txtCodo", txtCodo.value);
        parametros.append("txtCodoNom", txtCodoNom.value);
        parametros.append("txtCodd", txtCodd.value);
        parametros.append("txtCoddNom", txtCoddNom.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();
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });
  });

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