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

$dtFec=date("Y-m-d");
$nAnio=date("Y");
$nMes=date("m");

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];
$empNit = $_SESSION['empNit'];

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

      <!-- MODAL DETALLE DEL AGUINALDO -->
      <div class="modal fade" id="modalAguinal" tabindex="-1" role="dialog" aria-labelledby="modalAguinalTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true"></a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-00" role="tabpanel" aria-labelledby="pills-00-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">

                      <div class="form-row">
                        <div class="col-md-2">
                          <label class="font-size-sm text-success" for="numCoddm">Código Empleado</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numCoddm" maxlength="20" disabled>
                        </div>
                        <div class="col-sm-9 col-md-5">
                          <label class="font-size-sm text-success" for="txtNomdm">Nombre:</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtNomdm" maxlength="120" disabled>
                        </div>
                        <div class="col-sm-9 col-md-3">
                          <label class="font-size-sm text-success" for="dtFecing">Fecha Ingreso:</label>
                          <input type="date" class="form-control form-control-sm form-control-as" id="dtFecing" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numDic">Sueldo Diciembre</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numDic">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numEne">Sueldo Enero</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numEne">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numFeb">Sueldo Febrero</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numFeb">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numMar">Sueldo Marzo</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numMar">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numAbr">Sueldo Abril</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numAbr">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numMay">Sueldo Mayo</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numMay">
                        </div>
                      </div>

                      <div class="form-row align-items-end">
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numJul">Sueldo Julio</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numJul">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numAgo">Sueldo Agosto</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numAgo">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numSep">Sueldo Septiembre</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numSep">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numOct">Sueldo Octubre</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numOct">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numNov">Sueldo Noviembre</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numNov">
                        </div>
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numJun">Sueldo Junio</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numJun">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numTot">Sumatoria</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTot" disabled>
                        </div>
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numDias">Dias</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-0" id="numDias">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numAgui">Aguinaldo</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numAgui" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numAnti">Anticipo al Aguinaldo</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numAnti">
                        </div>
                        <div class="col-6 col-sm-2">
                          <label class="font-size-sm text-success" for="numLiqrec">Liquido a Recibir</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numLiqrec" style="font-size:25px; font-weight: bold;"disabled>
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnAgregar">Agregar</button>

                    <button type="button" class="btn btn-warning btn-block" id="btnModificar">Modificar Registro</button>
                  </form>

                </div>
              </div>

            </div>
          </div>
        </div>
      </div>

      <!-- MODAL PARA AGREGAR OTRO EMPLEADO A LA PLANILLA -->
      <div class="modal fade" id="modalAguinalag" tabindex="-1" role="dialog" aria-labelledby="modalAguinalagTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-000-tab" data-toggle="pill" href="#pills-000" role="tab" aria-controls="pills-000" aria-selected="true">Agregar Empleado</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-001-tab" data-toggle="pill" href="#pills-001" role="tab" aria-controls="pills-001" aria-selected="true">Buscar Empleados</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-000" role="tabpanel" aria-labelledby="pills-000-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-3">
                          <label class="font-size-sm text-success" for="numCoddag">Código Empleado</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numCoddag">
                        </div>
                        <div class="col-sm-9 col-md-9">
                          <label class="font-size-sm text-success" for="txtNomdag">Nombre:</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtNomdag" maxlength="120" disabled>
                        </div>
                      </div>

                    </div>
                    <div class="form-row">
                      <div class="col-6 mt-2">
                        <button class="btn btn-success btn-block" id="btnAgregarag" type="button">Agregar</button>
                      </div>
                      <div class="col-6 mt-2">
                        <button class="btn btn-danger btn-block" id="btnCancelarag" type="button">Cancelar</button>
                      </div>
                    </div>
                  </form>
                </div>
                <div class="tab-pane fade" id="pills-001" role="tabpanel" aria-labelledby="pills-001-tab">
                  <?php
                    $a='000';
                    $b='001';
                    include('../busEmpleado/index.html');
                  ?>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>

      <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>
            </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-md-10">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-2.5">
                                <label class="font-size-sm" for="numAno">Año al que corresponde</label>
                                <input type="number" class="form-control form-control-sm form-control-as" id="numAno" placeholder="0">
                          </div>
                        </div>
                        <div class="form-row">
                        </div>
                      </div>

                      <h3 class="text-light"></h3>
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-striped table-sm" id="tblAguinal">
                            <!---    <style>
                                  tr:nth-child(even) {
                                    background-color: #283747;
                                  }  -->
                                </style> 
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="70">CODIGO</th>
                                    <th scope="col" class="text-center" width="250">NOMBRE EMPLEADO</th>
                                    <th scope="col" class="text-center" width="130">PUESTO</th>
                                    <th scope="col" class="text-center" width="80">AGUINALDO</th>
                                    <th scope="col" class="text-center" width="80">ANTICIPO</th>
                                    <th scope="col" class="text-center" width="80">LIQUIDO</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotAgui" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotAnti" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotLiqT" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <h3 class="text-light"></h3>
                      <div class="form-group">
                        <div class="form-row">
                        </div>
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group position-fixed-md">

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-outline-success btn-block" id="btnExcel" type="button">Generar Excel</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-outline-danger btn-block" id="btnBorrar" type="button">Borrar Aguinaldo Completo</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-outline-warning btn-block" id="btnAgregao" type="button">Agregar Otro Empleado</button>
                          </div>
                          <div class="col-3 col-md-12"></div>
                        </div>

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

<script>
  var pressEnter = false;
  var nuevo = true;
  var nuevoArtic = true;
  var mesCerrado = false;
  var inputCtaMov = "txtCta";
  var totant = 0;
  var inputPlani = "numAno";
  var tblNomperAnt;
  var tblPolAnt;
  var btnAddEdit = "00";
  var inputArtic = "txtCodd";
  var unimed = "XXX";
  var ctaInc = false;
  var inputEmple = "numCoddag";
  var sueldobase = 0;

  const numAno = document.thisform.numAno;


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(numAno.value)  || numAno.value == 0) {
        numAno.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE AÑO"}});
        return true;
      }
    } else {
      if (isNullPer(numAno.value)) {
        numAno.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE AÑO"}});
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(numAno.value)) {
      numAno.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE AÑO"}});
      return true;
    }
    return false;
  }

    
  function addRowAguinal(cod, nom, pue, agui, anti, liqrec){
    const row = "<tr>"
                +"<td scope='col' class='ignore'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalAguinal'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCod'>"+cod+"</td>"
                +"<td id='dataNom'>"+nom+"</td>"
                +"<td id='dataPuesto'>"+pue+"</td>"
                +"<td id='dataagui' class='text-right'>"+agui+"</td>"
                +"<td id='dataanti' class='text-right'>"+anti+"</td>"
                +"<td id='dataLiqrec' class='text-right'>"+liqrec+"</td>"
                +"</tr>";
    $("#tblAguinal tbody").append(row);
  }

  function consultarPla(){
    if (restriccion(true)) {return};
    
    if (!isNullPer(numAno.value)) {
      const parametros = new FormData();
      parametros.append("action", "consultarPla");

      parametros.append("numAno", numAno.value);

      //txtNext.focus()

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);
          tblaguinalAnt = JSON.stringify(jsonJS.aguinal);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (isNullPer(jsonJS.aguinal)) {
              numAno.focus();
              alWarning({"msg":{"title":"NO GENERADO","text":"Aun no ha generado Aguinaldo para este año, revise."}});
              return true;
            } else {
            jsonJS.aguinal.forEach(function(i){
               addRowAguinal(i.agui_cod, i.mae_nom+" "+i.mae_ape, i.tpu_nom, i.agui_agui, i.agui_anti, i.agui_liqrec);
            });  
            sumDetao();
            nuevo = false;
          }
        }
      }
    });
    }      
  }

  function consultarNp(){
   
    if (!isNullPer(numCoddm.value)) {

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

      parametros.append("numAno", numAno.value);
      parametros.append("numCod", numCoddm.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (isNullPer(jsonJS.aguinal)) {
            } else {
              dtFecing.value = jsonJS.aguinal.mae_fing;
              sueldobase = Number(jsonJS.bono14.mae_sueldo)+Number(jsonJS.bono14.mae_bonii);
              numEne.value = (Number(jsonJS.aguinal.agui_ene)).toFixed(2);
              numFeb.value = (Number(jsonJS.aguinal.agui_feb)).toFixed(2);
              numMar.value = (Number(jsonJS.aguinal.agui_mar)).toFixed(2);
              numAbr.value = (Number(jsonJS.aguinal.agui_abr)).toFixed(2);
              numMay.value = (Number(jsonJS.aguinal.agui_may)).toFixed(2);
              numJun.value = (Number(jsonJS.aguinal.agui_jun)).toFixed(2); 
              numJul.value = (Number(jsonJS.aguinal.agui_jul)).toFixed(2); 
              numAgo.value = (Number(jsonJS.aguinal.agui_ago)).toFixed(2); 
              numSep.value = (Number(jsonJS.aguinal.agui_sep)).toFixed(2); 
              numOct.value = (Number(jsonJS.aguinal.agui_oct)).toFixed(2); 
              numNov.value = (Number(jsonJS.aguinal.agui_nov)).toFixed(2); 
              numDic.value = (Number(jsonJS.aguinal.agui_dic)).toFixed(2); 
              numTot.value = (Number(jsonJS.aguinal.agui_tot)).toFixed(2); 
              numDias.value = (Number(jsonJS.aguinal.agui_dias)).toFixed(0); 
              numAnti.value = (Number(jsonJS.aguinal.agui_anti)).toFixed(2); 
              numAgui.value = (Number(jsonJS.aguinal.agui_agui)).toFixed(2); 
              numLiqrec.value = (Number(jsonJS.aguinal.agui_liqrec)).toFixed(2); 
            }
          }
        }
      });
    }
  }  

  function guardarNp(){
   
    if (!isNullPer(numCoddm.value)) {

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

      parametros.append("numAno", numAno.value);
      parametros.append("numCod", numCoddm.value);
      parametros.append("numEne", numEne.value);
      parametros.append("numFeb", numFeb.value);
      parametros.append("numMar", numMar.value);
      parametros.append("numAbr", numAbr.value);
      parametros.append("numMay", numMay.value);
      parametros.append("numJun", numJun.value);
      parametros.append("numJul", numJul.value);
      parametros.append("numAgo", numAgo.value);
      parametros.append("numSep", numSep.value);
      parametros.append("numOct", numOct.value);
      parametros.append("numNov", numNov.value);
      parametros.append("numDic", numDic.value);
      parametros.append("numTot", numTot.value);
      parametros.append("numDias", numDias.value);
      parametros.append("numAgui", numAgui.value);
      parametros.append("numAnti", numAnti.value);
      parametros.append("numLiqrec", numLiqrec.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            //alSuccess(jsonJS);
          }
        }
      });
    }
  }  

  function borrarReg(){
   
    if (!isNullPer(numCoddm.value)) {

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

      parametros.append("numAno", numAno.value);
      parametros.append("numCod", numCoddm.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            //alSuccess(jsonJS);
          }
        }
      });
    }
  }  

  function limpiarModalAguinal(){
    numEne.value = "";
    numFeb.value = "";
    numMar.value = "";
    numAbr.value = "";
    numJun.value = "";
    numJul.value = "";
    numAgo.value = "";
    numSep.value = ""; 
    numOct.value = ""; 
    numNov.value = ""; 
    numDic.value = ""; 
    numTot.value = ""; 
    numDias.value = ""; 
    numAgui.value = ""; 
    numAnti.value = ""; 
    numLiqrec.value = ""; 
  } 

  function calcular(){
    numTot.value=round((Number(numEne.value)+Number(numFeb.value)+Number(numMar.value)+Number(numAbr.value)+Number(numMay.value)+Number(numJun.value)+Number(numJul.value)+Number(numAgo.value)+Number(numSep.value)+Number(numOct.value)+Number(numNov.value)+Number(numDic.value)),2).toFixed(2);
/*
    if (numTot.value>0) {
      numAgui.value=round(Number(numTot.value)/12,2).toFixed(2);
    } else {
      numAgui.value=(0).toFixed(2);
    }
*/
    numAgui.value = round((sueldobase*numDias.value/365),2);

    numLiqrec.value=(Number(numAgui.value)-Number(numAnti.value)).toFixed(2);
  } 

  function limpiar(todo = false){
  }


  function sumDetao(){
    $("#tblAguinal #dataTotAgui").text(tblSumCol("tblAguinal", "dataagui").toFixed(2));
    $("#tblAguinal #dataTotAnti").text(tblSumCol("tblAguinal", "dataanti").toFixed(2));
    $("#tblAguinal #dataTotLiqT").text(tblSumCol("tblAguinal", "dataLiqrec").toFixed(2));
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    //document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    //document.thisform.dtFvalida.value = '<?php echo $dtFec; ?>';
    numAno.value = <?php echo $nAnio; ?>;

    // SHOW MODAL
    $('#modalAguinal').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      }
    });

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

    // FOCUS NUMERO DE ORDEN
    $("#numAno")
    .focus(function() {
      tblClear("tblAguinal");
      sumDetao();
      limpiar();
    })
    .blur(function (){
      consultarPla();
    });

    // VALID CODIGO A AGREGAR
    $("#numCoddag")
    .focus(function() {
      inputEmple = $(this).attr('id');
      txtNomdag.value = "";
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-001-tab").click(); }
    })
    .change(function (){
      if (restriccion(true)) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarEmple");
      parametros.append("numAno", numAno.value);
      parametros.append("numCoddag", numCoddag.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) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (!isNullPer(jsonJS.aguinal)) {
//            if (jsonJS.nomper != null ) {
                numCoddag.value="";
                numCoddag.focus();
                alWarning({"msg":{"title":"YA REGISTRADO","text":"Este codigo ya esta agregado en el Aguinaldo, no lo puede agregar dos veces"}});
                return true;
            } else {
              if (isNullPer(jsonJS.maestro)) {
                numCoddag.value="";                
                numCoddag.focus();
                alWarning({"msg":{"title":"NO EXISTE","text":"Este codigo no ha sido registrado"}});
                return true;
              } else {
                txtNomdag.value = jsonJS.maestro.mae_nom+" "+jsonJS.maestro.mae_ape;
                //$("#selDepto").trigger("change");
              }
            }
          }
        }
      });
    });


    // FOCUS ORDEN DE COMPRA
  //  $("#numOrdenc").change(function (){
  //    consultarOrden();
  //  });


    // Valida Cambios
    $("#numEne, #numFeb, #numMar, #numAbr, #numMay, #numJun, #numJul, #numAgo")
    .blur(function (){
      calcular();
    });

    $("#numSep, #numOct, #numNov, #numDic, #numAnti, #numDias")
    .blur(function (){
      calcular();
    });

    // CLICK EXCEL
    $("#btnExcel").click(function (){
      if (restriccion(true)) {return};

      const getnumAno = "?numAno="+numAno.value;

      var url = window.location.origin+window.location.pathname+"excel.php"+getnumAno;

      window.location.href = url;
    });

    // CLICK BORRAR
    $("#btnBorrar").click(function (){

      if (restriccion(true)) {return};

      const numAno = numAno.value;

      numAno.focus();

      const fnT = function(){

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

        $.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 {
              numAno.value = "";
              limpiar();
              tblClear("tblAguinal");
              sumDetao();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }
      admClave(fnT, fnF);
    });

  }); 
    
  // CLICK Agregar otro
  $("#btnAgregao").click(function (){
    if (restriccion(true)) {return};
    numCoddag.value="";
    txtNomdag.value="";
    $('#modalAguinalag').modal('toggle');
//    $('#modalAguinalag').find('input:visible:first').focus();
  });

  // CLICK Cancelar el agregado
  $("#btnAgregarag").click(function (){

    if (isNullPer(numCoddag.value)) {
      numCoddag.value="";
      numCoddag.focus();      
      alWarning({"msg":{"title":"DEBE INGRESAR EL CODIGO","text":"Debe ingresar el codigo del empleado que desea agregar al Aguinaldo."}});
      return true;
    }
    coddag=numCoddag.value;
    nomdag=txtNomdag.value;  

    const parametros = new FormData();
    parametros.append("action", "guardarAg");
    parametros.append("numAno", numAno.value);
    parametros.append("numCoddag", numCoddag.value);
    parametros.append("txtNomdag", txtNomdag.value);
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      async: true,
      //beforeSend: function () {
        //alLoad("Cargando...")
      //},
      success: function (jsonPhp) {
        console.log(jsonPhp);
        const jsonJS = JSON.parse(jsonPhp);
        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          if (isNullPer(jsonJS.puesto)) {
            puesto="";
          } else {
            puesto=jsonJS.puesto;
          }
          totagui=jsonJS.totagui;
          totanti=jsonJS.totanti;
          liqrec=jsonJS.liqrec;
          addRowAguinal(coddag, nomdag, puesto, Number(totagui).toFixed(2), Number(totanti).toFixed(2), Number(liqrec).toFixed(2));
          $('#modalAguinalag').modal('toggle');
        }
      }
    });
  });

  // CLICK Cancelar el agregado
  $("#btnCancelarag").click(function (){
    $('#modalAguinalag').modal('toggle');
  });

  // CLICK DEL
  $("body").on("click", "#btnDel", function() {
    const row = $(this).parents("tr");

    const dataCod = $(this).parents("tr").find("#dataCod");
    numCoddm.value = dataCod.text();
    borrarReg();

    alDelete(function fn(){
      row.remove();
      sumDetao();
    });
  });

  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-00-tab').text("MODIFICAR AGUINALDO AÑO "+numAno.value);
    $('#btnAgregar').hide();
    $('#btnModificar').show();

    numDic.focus();

    const dataCod = $(this).parents("tr").find("#dataCod");
    const dataNom = $(this).parents("tr").find("#dataNom");
  //  const dataPuesto = $(this).parents("tr").find("#dataPuesto");
    const dataagui = $(this).parents("tr").find("#dataagui");
    const dataanti = $(this).parents("tr").find("#dataanti");
    const dataLiqrec = $(this).parents("tr").find("#dataLiqrec");

    numCoddm.value = dataCod.text();
    txtNomdm.value = dataNom.text();
  //  txtPuestodm.value = dataPuesto.text();
    numAgui.value = dataagui.text();
    numAnti.value = dataanti.text();
    numLiqrec.value = dataLiqrec.text();

    consultarNp();

    $("body").on("click", "#btnModificar", function() {
      $('#modalAguinal').modal('toggle');

      dataCod.text(numCoddm.value);
      dataNom.text(txtNomdm.value);
    //  dataPuesto.text(txtPuestodm.value);
      dataagui.text(isNullNumber(numAgui.value).toFixed(2));
      dataanti.text(isNullNumber(numAnti.value).toFixed(2));
      dataLiqrec.text(isNullNumber(numLiqrec.value).toFixed(2));

      guardarNp();

      limpiarModalAguinal();
      sumDetao();
    });
  });

  // MODALDetao HIDDEN
  $('#modalAguinal').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificar");
  });


  // 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") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-00") ? numDic.focus() : 0;
        (relatedTarget == "#pills-000") ? numCoddag.focus() : 0;
      }
    }
  });

</script>

