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

$empCod = $_SESSION['empCod'];
# QUERYS
$sDeptosi = "SELECT *, TRIM(dep_cod) AS dep_codc FROM deptosi";
$sSubdeptosi = "SELECT *, TRIM(sdep_cod) AS sdep_codc FROM subdeptosi";
$sPordesc = "SELECT * FROM pordesc ORDER BY pd_cod";
# EJECUCION DE QUERYS
$db = new dbExec();
$select["deptosi"] = $db->query($sDeptosi);
$select["subdeptosi"] = $db->query($sSubdeptosi);
$select["pordesc"] = $db->query($sPordesc);
$db->close();
?>
<?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>
            </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">
                          <div class="col-sm-6 col-md-3">
                            <label class="font-size-md" for="selDepto">Familia</label>
                            <select class="form-control form-control-md form-control-as" name="selDepto" id="selDepto">
                              <?php
                                while ($rec = $db->fetchAssoc($select['deptosi'])) {
                                  echo  '<option value="'.$rec['dep_cod'].'" data-codc="'.$rec['dep_codc'].'">'.utf8_encode($rec['dep_nom']).'</option>';

                                  //echo  "<option value={$rec['dep_cod']}>".utf8_encode($rec['dep_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-sm-6 col-md-3">
                            <label class="font-size-md" for="selSubDepto">Sub-Familia</label>
                            <select class="form-control form-control-md form-control-as" name="selSubDepto" id="selSubDepto">
                              <?php
                                while ($rec = $db->fetchAssoc($select['subdeptosi'])) {
                                  echo  '<option value="'.$rec['sdep_cod'].'" data-scodc="'.$rec['sdep_codc'].'">'.utf8_encode($rec['sdep_nom']).'</option>';
                                //  echo  "<option data-dep={$rec['sdep_dep']} value={$rec['sdep_cod']}>".utf8_encode($rec['sdep_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label for="dtDel" class="font-size-md">Desde que Fecha</label>
                            <input type="date" class="form-control form-control-md form-control-as font-size-md" id="dtDel" placeholder="">
                          </div>
                          <div class="col-1">
                            <label > </label>
                          </div>
                          <div class="col-3">
                            <label for="dtAl" class="font-size-md">Hasta que Fecha</label>
                            <input type="date" class="form-control form-control-md form-control-as font-size-md" id="dtAl" placeholder="">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label class="font-size-md" for="numDescud">Descuento a Aplicar</label>
                            <select class="form-control form-control-md form-control-as" name="numDescud" id="numDescud">
                              <?php
                                while ($rec = $db->fetchAssoc($select['pordesc'])) {
                                  echo  '<option value="'.TRIM($rec['pd_cod']).'">'.utf8_encode($rec['pd_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>
                      </div>
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <button class="btn btn-success btn-lg btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-3">
                            <button class="btn btn-danger btn-lg btn-block" id="btnBorrar" type="button">Borrar</button>
                          </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 inputNumb = "numNumb";
  var inputTipov = "txtTrela";
  var inputCod = "txtCod"

  const selDepto = document.thisform.selDepto;
  const selSubDepto = document.thisform.selSubDepto;
  const dtDel = document.thisform.dtDel;
  const dtAl = document.thisform.dtAl;



  function restriccion(consultar = false){
  }
  
  function restriccionCamposVacios() {
  }

  function limpiar(){
    numDescud.value = "";
  }

  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    dtDel.value = dateToday();
    dtAl.value = dateToday();

    var subDepcur = $("#selSubDepto");

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

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

    // VALID SUBDEPARTAMENTOS CUANDO ABANDONA DEPARTAMENTO
    $("#selDepto")
    .blur(function() {
      var subDepcur = $("#selSubDepto");
      // Limpiamos el select
      subDepcur.find('option').remove();
      const parametros = new FormData();
      parametros.append("action", "consultarSubdep");
      parametros.append("selDepto", $('#selDepto').find('option:selected').data('codc'));

      $.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 {
            jsonJS.subdeptosi.forEach(function(i){
                $cod=i.sdep_cod;
                $scod=i.sdep_cod;
                $nom=i.sdep_nom;
                subDepcur.append('<option value="'+$cod+'"data-scodc="'+$cod+'">'+$nom+'</option>');
            });
          }
        }
      });
    });

    // VALID SUBDEPARTAMENTOS CUANDO ABANDONA DEPARTAMENTO
    $("#dtAl")
    .blur(function() {
      //console.log($('#selDepto').find('option:selected').data('codc'), "  ",$('#selSubDepto').find('option:selected').data('scodc'));
      const parametros = new FormData();
      parametros.append("action", "consultar");
      parametros.append("selDepto", $('#selDepto').find('option:selected').data('codc'));
      parametros.append("selSubDepto", $('#selSubDepto').find('option:selected').data('scodc'));
      parametros.append("dtDel", dtDel.value);
      parametros.append("dtAl", dtAl.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){
            nuevo=true;
            alError(jsonJS);
          } else {
            if (!isNullPer(jsonJS.ofertas)){
              nuevo=false;
              numDescud.value=jsonJS.ofertas.of_porc;
            } else {
              nuevo=true;
            }
          }
        }
      });
    });


    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "borrar");
        parametros.append("selDepto", $('#selDepto').find('option:selected').data('codc'));
        parametros.append("selSubDepto", $('#selSubDepto').find('option:selected').data('scodc'));
        parametros.append("dtDel", dtDel.value);
        parametros.append("dtAl", dtAl.value);
        parametros.append("numDescud", numDescud.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();
              location.reload(true);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      espClave(fnT, fnF);
    });

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

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

      parametros.append("nuevo", nuevo);
      parametros.append("selDepto", $('#selDepto').find('option:selected').data('codc'));
      parametros.append("selSubDepto", $('#selSubDepto').find('option:selected').data('scodc'));
      parametros.append("dtDel", dtDel.value);
      parametros.append("dtAl", dtAl.value);
      parametros.append("numDescud", numDescud.value);

      selDepto.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 = "";
          }
        }
      });
    });

  });

  // 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") ? $(target+' input:visible:eq(1)').focus() : 0;
      }
    }
  });

</script>