<?php 
include_once('../../../php/sessionStart.php'); 
include_once('../../../php/db/dbExec.php');

# QUERYS
//$sTiposal = "SELECT * FROM tiposal";

# EJECUCION DE QUERYS
$db = new dbExec();
//$select["tiposal"] = $db->query($sTiposal);

?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <style type="text/css">
      .
    </style>
    <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">Modificar Ingresos Fijos</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="true">Buscar Empleados</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-row">
                    <div class="col-12 col-sm-9">
                      <div class="form-group">
                        <div class="form-row align-items-end">
                          <div class="col-sm-2">
                            <label for="numCod">Código</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCod" placeholder="">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-sm-12">
                            <label for="txtNom">Nombre</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtNom" placeholder="" maxlength="100" disabled>
                          </div>
                        </div>
                        <div class="form-row">
<!--                          
                          <div class="col-sm-4 col-md-4">
                            <label for="selTsal">Tipo Salario</label>
                            <select class="form-control form-control-sm form-control-as" name="selTsal" id="selTsal" disabled>
                              <?php
                             //   while ($rec = $db->fetchAssoc($select['tiposal'])) {
                             //     echo  "<option value={$rec['ts_cod']}>".utf8_encode($rec['ts_nom']).'</option>';
                             //   }
                              ?>
                            </select>
                          </div>
--->                          
                          <div class="col-4">
                            <label for="numSueldo">Sueldo Base</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numSueldo" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-4">
                            <label for="numBonil">Boni. de Ley</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numBonil" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-4">
                            <label for="numBonii">Bonificacion Incentivo</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numBonii" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-4">
                            <label for="numBonoe">Bono Extra</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numBonoe" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                        </div>
                        <div class="form-row  align-items-end">
                          <div class="col-4">
                            <label for="numDepre">Depre. Vehiculo</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numDepre" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-4">
                            <label for="numViati">Viaticos</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numViati" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                        </div>
                        <h3 class="text-light"></h3>

                      </div>

                    </div>
                    <div class="col-12 col-lg-3">
                      <div class="form-group position-fixed-sm">
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnModi" type="button">Modificar</button>
                          </div>
                        </div>
                        <div class="form-row">

                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-md-5 col-lg-12 text-center mt-3">
                            <div class="upload-btn-wrapper text-center" style="height: 120px; width: 90%;">
                              <img class="rounded-lg" name="imgArtic" width="100%" height="100%" style="object-fit: cover;" />
                              <input type="file" id="fileImg" name="file" onchange="imgSelect(this, document.thisform.imgArtic, imgPhoto); return false;" />
                            </div>
                          </div>
                        </div>
                      </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('../busEmpleado/index.html');
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputEmple = "numCod";
  var inputProypla = "txtProy";
  const imgPhoto = "../../img/photo.jpg";

  const numCod = document.thisform.numCod;
  const txtNom = document.thisform.txtNom;
  //const selTsal = document.thisform.selTsal;
  const numSueldo = document.thisform.numSueldo;
  const numBonil = document.thisform.numBonil;
  const numBonii = document.thisform.numBonii;
  const numBonoe = document.thisform.numBonoe;
  const numViati = document.thisform.numViati;
  const numDepre = document.thisform.numDepre;


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(numCod.value)) {
        numCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO"}});
        return true;
      }
    } else {
      if (isNullPer(numCod.value)) {
        return true;
      }
    } 
    return false;  
  }

  function restriccionProypla() {
    if (isNullPer($("#"+inputProypla).val())) {
      $("#"+inputProypla+"Nom").val("");
      return true;
    }
    return false;
  }

  function limpiar(){
    $('.limpiar').val('');
    txtNom.value = "";
    numSueldo.value = (0).toFixed(2);
    numBonil.value = (0).toFixed(2);
    numBonii.value = (0).toFixed(2);
    numBonoe.value = (0).toFixed(2);
    numViati.value = (0).toFixed(2);
    numDepre.value = (0).toFixed(2);
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    imgArtic.src = imgPhoto;
    limpiar();

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

    $("#numCod").focus(function() {
      this.value = "";
      imgArtic.src = imgPhoto;
      limpiar();
//      selTsal.disabled = true;
      numSueldo.disabled = true;
      numBonil.disabled = true;
      numBonii.disabled = true;
      numBonoe.disabled = true;
      numViati.disabled = true;
      numDepre.disabled = true;
    })


    // VALID CODIGO
    $("form[name='thisform'] #numCod")
    .focus(function() {
      inputEmple = $(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("numCod", numCod.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) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            limpiar();
            
            if (jsonJS.maestro === null) {
              nuevo = true;
              imgArtic.src = imgPhoto;
              numCod.focus();
              alWarning({"msg":{"title":"NO EXISTE","text":"Este codigo no ha sido registrado"}});
              return true;
            } else {
              nuevo = false;
              txtNom.value = jsonJS.maestro.mae_nom+' '+jsonJS.maestro.mae_ape;
//              selTsal.value = jsonJS.maestro.mae_tiposal;
              numSueldo.value = jsonJS.maestro.mae_sueldo;
              numBonil.value = jsonJS.maestro.mae_bonil;
              numBonii.value = jsonJS.maestro.mae_bonii;
              numBonoe.value = jsonJS.maestro.mae_bonoe;
              numViati.value = jsonJS.maestro.mae_viati;
              numDepre.value = jsonJS.maestro.mae_depre;

              imgExist(imgArtic, jsonJS.imgArtic, imgPhoto);

              //$("#selDepto").trigger("change");
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

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

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

      parametros.append("file", document.thisform.file.files[0]);
      parametros.append("nuevo", nuevo);
      parametros.append("numCod", numCod.value);
//      parametros.append("selTsal", selTsal.value);
      parametros.append("numSueldo", numSueldo.value);
      parametros.append("numBonil", numBonil.value);
      parametros.append("numBonii", numBonii.value);
      parametros.append("numBonoe", numBonoe.value);
      parametros.append("numViati", numViati.value);
      parametros.append("numDepre", numDepre.value);

      numCod.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();
            imgArtic.src = imgPhoto;
            numCod.value = "";
            numCod.focus();
          }
        }
      });
    });

    // CLICK BORRAR
    $("#btnModi").click(function (){
      if (restriccion()) {return};
      const fnT = function(){
//        selTsal.disabled = false;
        numSueldo.disabled = false;
        numBonil.disabled = false;
        numBonii.disabled = false;
        numBonoe.disabled = false;
        numViati.disabled = false;
        numDepre.disabled = false;
      }

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

</script>