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

$empCod = $_SESSION['empCod'];
?>
<?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>
              <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 Tipos</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-2-tab" data-toggle="pill" href="#pills-2" role="tab" aria-controls="pills-2" aria-selected="false">Buscar Tipo Venta</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-3-tab" data-toggle="pill" href="#pills-3" role="tab" aria-controls="pills-3" aria-selected="false">Buscar Tipo Poliza</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-12 col-sm-6 col-md-3">
                            <label for="txtCod">Codigo</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" maxlength="10">
                          </div>
                          <div class="col-6">
                            <label for="txtNom">Nombre del Tipo</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNom" maxlength="100">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label class="pr-1">Tipo de Movimiento</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crEoS1" name="crEoS" class="custom-control-input" value="E">
                              <label class="custom-control-label" for="crEoS1">Entrada</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crEoS2" name="crEoS" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crEoS2">Salida</label>
                            </div>
                          </div>
                          <div class="col-3">
                            <label class="pr-1">Afecta Costo</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crAfecos1" name="crAfecos" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crAfecos1">Si Afecta</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crAfecos2" name="crAfecos" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crAfecos2">No Afecta</label>
                            </div>
                          </div>

                          <div class="col-3">
                            <label class="pr-1">Genera Partida</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crGenp1" name="crGenp" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crGenp1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crGenp2" name="crGenp" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crGenp2">No</label>
                            </div>
                          </div>
                          <div class="col-3">
                            <label class="pr-1">Movimiento entre bodegas</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crMovbod1" name="crMovbod" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crMovbod1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crMovbod2" name="crMovbod" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crMovbod2">No</label>
                            </div>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label class="pr-1">Reporte de Ventas</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crRepven1" name="crRepven" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crRepven1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crRepven2" name="crRepven" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crRepven2">No</label>
                            </div>
                          </div>
                          <div class="col-3">
                            <label class="pr-1">Inventario Inicial</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crInveini1" name="crInveini" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crInveini1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crInveini2" name="crInveini" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crInveini2">No</label>
                            </div>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label for="txtTrela">Tipo Venta Relacionado</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtTrela" maxlength="20">
                          </div>
                          <div class="col-md-5">
                            <label for="txtTrelaNom">Nombre Tipo de Venta Relacionado</label>
                            <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtTrelaNom" placeholder="Cuenta no definido" disabled>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label for="txtTrelapol">Tipo Poliza Relacionado</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtTrelapol" maxlength="20">
                          </div>
                          <div class="col-md-5">
                            <label for="txtTrelapolNom">Nombre Tipo Poliza Relacionado</label>
                            <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtTrelapolNom" placeholder="Cuenta no definido" disabled>
                          </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>
                    </div>
                    <div class="col-12 col-lg-3 col-xl-2 text-left mt-5">
                      <div class="form-group position-fixed-lg w-lg-3 w-xl-2">
                        <div class="form-row">
                          <div class="col-11 mt-2">
                            <button class="btn btn-success btn-lg btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-11 mt-2">
                            <button class="btn btn-danger btn-lg btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-11 mt-2">
                            <button class="btn btn-info btn-lg btn-block" id="btnLista" type="button">Listado de Tipos</button>
                          </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('../busTipodoci/index.html')
                ?>
              </div>
              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busTipov/index.html')
                ?>
              </div>
              <div class="tab-pane fade" id="pills-3" role="tabpanel" aria-labelledby="pills-3-tab">
                <?php
                  $a='0';
                  $b='3';
                  include('../busTipoPol/index.html')
                ?>
              </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 inputTipoPol = "txtTrelapol";
  var inputCod = "txtCod"

  const txtCod = document.thisform.txtCod;
  const txtNom = document.thisform.txtNom;
  const txtTrela = document.thisform.txtTrela;
  const txtTrelapol = document.thisform.txtTrelapol;

  const crEos = document.thisform.crEos;
  const crAfecos = document.thisform.crAfecos;
  const crMovbod = document.thisform.crMovbod;
  const crRepven = document.thisform.crRepven;
  const crEoS = document.thisform.crEoS;
  const crGenp = document.thisform.crGenp;
  const crInveini = document.thisform.crInveini;



  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 DEL TIPO DE DOCUMENTO"}});
        return true;
      }
      if (isNullPer(txtNom.value)) {
        txtNom.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nombre del Tipo de documento"}});
        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 EL CODIGO DEL TIPO DE DOCUMENTO"}});
      return true;
    }
    return false;
  }

  function limpiar(){
    txtNom.value = "";
    txtTrela.value = "";
    txtTrelaNom.value = "";
    txtTrelapol.value = "";
    txtTrelapolNom.value = "";
    crEoS.value = "E";
    crAfecos.value = "N";
    crMovbod.value = "N";
    crRepven.value = "N";
    crGenp.value = "N";
    crInveini.value = "N";
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    txtNom.value = "";
    txtTrela.value = "";
    txtTrelaNom.value = "";
    txtTrelapol.value = "";
    txtTrelapolNom.value = "";
    crEoS.value = "E";
    crAfecos.value = "N";
    crMovbod.value = "N";
    crRepven.value = "N";
    crGenp.value = "N";
    crInveini.value = "N";

    // 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 CODIGO
    $("#txtCod")
    .focus(function() {
      txtCod.value = "";
      limpiar();
      inputCod = $(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarTipodoci");
      parametros.append("txtCod", txtCod.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);
            nuevo = true;
          } else {
            if (jsonJS.tipodoci === null) {
              nuevo = true;
            } else {
              txtNom.value = jsonJS.tipodoci.td_nom;
              txtTrela.value = jsonJS.tipodoci.td_relatv;
              txtTrelaNom.value = jsonJS.tipodoci.td_relatvnom;
              txtTrelapol.value = jsonJS.tipodoci.td_relatpol;
              txtTrelapolNom.value = jsonJS.tipodoci.td_relatpolnom;
              crEoS.value = jsonJS.tipodoci.td_eos;
              crAfecos.value = jsonJS.tipodoci.td_afecos;
              crMovbod.value = jsonJS.tipodoci.td_movbod;
              crRepven.value = jsonJS.tipodoci.td_repven;
              crGenp.value = jsonJS.tipodoci.td_partsn;
              crInveini.value = jsonJS.tipodoci.td_inveini;
              nuevo = false;
            }
          }
        }
      });
    });

    // VALID Trela
    $("#txtTrela")
    .focus(function() {
      inputTipov = $(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-2-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtTrelaNom");
      txtNext = document.getElementById("txtTrelapol");

      $(txtThis).off("blur");

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.tipov === null) {
              txtGetValue.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"El tipo "+txtThis.value+" no ha sido registrado", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.tipov.tv_nom;
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // VALID Trela
    $("#txtTrelapol")
    .focus(function() {
      inputTipopol = $(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-3-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtTrelapolNom");
      txtNext = document.getElementById("txtTrelapolNom");

      $(txtThis).off("blur");

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.tipopol === null) {
              txtGetValue.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"El tipo de Poliza "+txtThis.value+" no ha sido registrado", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.tipopol.tp_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);
        parametros.append("txtNom", txtNom.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 = "";
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};
      if (crRepven.value=='S' && isNullPer(txtTrela.value)) {
        txtTrela.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Tipo de Venta Relacionado"}});
        return true;
      }
      if (crGenp.value=='S' && isNullPer(txtTrelapol.value)) {
        txtTrelapol.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Tipo de Poliza Relacionado"}});
        return true;
      }


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

      parametros.append("nuevo", nuevo);
      parametros.append("txtCod", txtCod.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtTrela", txtTrela.value);
      parametros.append("txtTrelapol", txtTrelapol.value);
      parametros.append("crEoS", crEoS.value);
      parametros.append("crAfecos", crAfecos.value);
      parametros.append("crMovbod", crMovbod.value);
      parametros.append("crRepven", crRepven.value);
      parametros.append("crGenp", crGenp.value);
      parametros.append("crInveini", crInveini.value);

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

    // CLICK IMPRIMIR
    $("#btnLista").click(function (){

      //const getselClasi = "?selClasi="+selClasi.value;
      var url = window.location.origin+window.location.pathname+"print.php";

      window.open(url, '_blank');

      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") ? $(target+' input:visible:eq(1)').focus() : 0;
        (relatedTarget == "#pills-2") ? $('#'+inputTipov).focus() : 0;
        (relatedTarget == "#pills-3") ? $('#'+inputTipoPol).focus() : 0;
      }
    }
  });

</script>