<?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-cog"></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="false">Buscar Empresas</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 Cuentas</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">
                      <div class="col-md-3">
                        <label for="txtCod">Código</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" placeholder="" maxlength="3">
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-6">
                        <label for="txtNom">Nombre</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtNom" placeholder="">
                      </div>
                      <div class="col-md-6">
                        <label for="txtNomc">Nombre Comercial</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtNomc" placeholder="">
                      </div>
                    </div>

                    <div class="form-row align-items-end">
                      <div class="col-md-4">
                        <label for="txtNit">NIT</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtNit" placeholder="">
                      </div>
                      <div class="col-md-4">
                        <div class="form-row align-items-end">
                          <div class="col-6">
                            <label for="dtFinie">Fecha Inicio Periodo</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFinie" placeholder="">
                          </div>
                          <div class="col-6">
                            <label for="dtFciee">Fecha Final Periodo</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFciee" placeholder="">
                          </div>
                        </div>
                      </div>
                      <div class="col-md-4">
                        <div class="form-row align-items-end">
                          <div class="col-6">
                            <label for="dtFtrab">Fecha en la que trabajara</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFtrab"placeholder="">
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtMoneda">Moneda Local:</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtMoneda" placeholder="">
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtaic">Cuenta IVA Compras</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtaic" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtaicNom">Nombre de Cuenta IVA Compras</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaicNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtaiv">Cuenta IVA Ventas</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtaiv" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtaivNom">Nombre de Cuenta IVA Ventas</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaivNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtarisr">Cuenta Retención de ISR</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtarisr" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtarisrNom">Nombre de Cuenta Retención de ISR</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtarisrNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtariva">Cuenta Retención de IVA</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtariva" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtarivaNom">Nombre de Cuenta Retención de IVA</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtarivaNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtacaj">Cuenta Caja</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtacaj" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtacajNom">Nombre de Cuenta Caja</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtacajNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtacomb">Cuenta Impuesto Combustible</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtacomb" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtacombNom">Nombre de Cuenta Impuesto Combustible</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtacombNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtaven">Cuenta de Ventas</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtaven" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtavenNom">Nombre de Cuenta de Ventas</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtavenNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtaserv">Cuenta de Servicios Prestados</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtaserv" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtaservNom">Nombre de Cuenta de Servicios</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaservNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtCtaexport">Cuenta de Exportaciones</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCtaexport" placeholder="">
                      </div>
                      <div class="col-md-9">
                        <label for="txtCtaexportNom">Nombre de Cuenta de Exportaciones</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaexportNom" placeholder="Cuenta no definida" disabled>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="col-md-3">
                        <label for="txtConso">Código Empresa que Consolida</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtConso" placeholder="">
                      </div>
                      <div class="col-md-6">
                        <label for="txtConsoNom">Nombre Empresa que Consolida</label>
                        <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtConsoNom" placeholder="Empresa no definida" maxlength="3" disabled>
                      </div>
                    </div>

                    <div class="form-row mt-1">
                      <div class="col-12">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbExensn" id="cbExensn">
                          <label class="custom-control-label" for="cbExensn">Exento</label>
                        </div>
                      </div>
                      <div class="col-12">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbPequesn" id="cbPequesn">
                          <label class="custom-control-label" for="cbPequesn">Pequeño Contribuyente</label>
                        </div>
                      </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">Guardar</button>
                      </div>
                      <div class="form-group col">
                        <button class="btn btn-danger btn-lg btn-block" id="btnBorrar" type="button">Borrar</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 class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busCuentasMov/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputCtaMov = "txtCtaic";
  var inputEmpresas = "txtCod";

  const txtCod = document.thisform.txtCod;
  const txtNom = document.thisform.txtNom;
  const txtNomc = document.thisform.txtNomc;
  const txtNit = document.thisform.txtNit;
  const dtFinie = document.thisform.dtFinie;
  const dtFciee = document.thisform.dtFciee;
  const dtFtrab = document.thisform.dtFtrab;
  const txtMoneda = document.thisform.txtMoneda;
  const txtCtaic = document.thisform.txtCtaic;
  const txtCtaicNom = document.thisform.txtCtaicNom;
  const txtCtaiv = document.thisform.txtCtaiv;
  const txtCtaivNom = document.thisform.txtCtaivNom;
  const txtCtarisr = document.thisform.txtCtarisr;
  const txtCtarisrNom = document.thisform.txtCtarisrNom;
  const txtCtariva = document.thisform.txtCtariva;
  const txtCtarivaNom = document.thisform.txtCtarivaNom;
  const txtCtacaj = document.thisform.txtCtacaj;
  const txtCtacajNom = document.thisform.txtCtacajNom;
  const txtCtacomb = document.thisform.txtCtacomb;
  const txtCtacombNom = document.thisform.txtCtacombNom;
  const txtCtaven = document.thisform.txtCtaven;
  const txtCtavenNom = document.thisform.txtCtavenNom;
  const txtCtaserv = document.thisform.txtCtaserv;
  const txtCtaservNom = document.thisform.txtCtaservNom;
  const txtCtaexport = document.thisform.txtCtaexport;
  const txtCtaexportNom = document.thisform.txtCtaexportNom;

  const txtConso = document.thisform.txtConso;
  const txtConsoNom = document.thisform.txtConsoNom;

  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"}});
        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 CÓDIGO"}});
      return true;
    }
    return false;
  }

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

  function restriccionConso() {
    if (isNullPer(txtConso.value)) {
      txtConsoNom.value = "";
      return true;
    }
    return false;
  }

  function limpiar(){
    const date = new Date();

    txtNom.value = "";
    txtNomc.value = "";
    txtNit.value = "";
    dtFinie.value = date.getFullYear()+"-01-01";
    dtFciee.value = date.getFullYear()+"-12-31";

    const ultimoDia = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    dtFtrab.value = dateToYMD(ultimoDia);
    //numTasa.value = "7.80000";
    txtMoneda.value="QUETZALES";
    $("input[id*='txtCta']").val("");
    txtConso.value = "";
    txtConsoNom.value = "";
    cbExensn.checked = 0;
    cbPequesn.checked = 0;
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();

    // 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() {
      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 (){
      if (restriccion(true)) {return};

      txtNext = txtNom;

      const parametros = new FormData();
      parametros.append("action", "consultar");
      parametros.append("txtCod", txtCod.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 {
            limpiar();
            
            if (jsonJS.empresas === null) {
              txtConso.value = txtCod.value;
              nuevo = true;
            } else {
              txtNom.value = jsonJS.empresas.emp_nom;
              txtNomc.value = jsonJS.empresas.emp_nomc;
              txtNit.value = jsonJS.empresas.emp_nit;
              dtFinie.value = jsonJS.empresas.emp_finie;
              dtFciee.value = jsonJS.empresas.emp_fciee;
              dtFtrab.value = jsonJS.empresas.emp_ftrab;
              txtMoneda.value = jsonJS.empresas.emp_moneda;
              txtCtaic.value = jsonJS.empresas.emp_ctaic;
              txtCtaicNom.value = jsonJS.empresas.emp_ctaicnom;
              txtCtaiv.value = jsonJS.empresas.emp_ctaiv;
              txtCtaivNom.value = jsonJS.empresas.emp_ctaivnom;
              txtCtarisr.value = jsonJS.empresas.emp_ctarisr;
              txtCtarisrNom.value = jsonJS.empresas.emp_ctarisrnom;
              txtCtariva.value = jsonJS.empresas.emp_ctariva;
              txtCtarivaNom.value = jsonJS.empresas.emp_ctarivanom;
              txtCtacaj.value = jsonJS.empresas.emp_ctacaj;
              txtCtacajNom.value = jsonJS.empresas.emp_ctacajnom;
              txtCtacomb.value = jsonJS.empresas.emp_ctacomb;
              txtCtacombNom.value = jsonJS.empresas.emp_ctacombnom;
              txtCtaven.value = jsonJS.empresas.emp_ctaven;
              txtCtavenNom.value = jsonJS.empresas.emp_ctavennom;
              txtCtaserv.value = jsonJS.empresas.emp_ctaserv;
              txtCtaservNom.value = jsonJS.empresas.emp_ctaservbnom;
              txtCtaexport.value = jsonJS.empresas.emp_ctaexport;
              txtCtaexportNom.value = jsonJS.empresas.emp_ctaexportnom;
              txtConso.value = jsonJS.empresas.emp_conso;
              txtConsoNom.value = jsonJS.empresas.emp_consonom;
              cbExensn.checked = (jsonJS.empresas.emp_exensn == "S") ? 1 : 0;
              cbPequesn.checked = (jsonJS.empresas.emp_pequesn == "S") ? 1 : 0;
              nuevo = false;
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // VALID CUENTAS
    $("input[id*='txtCta']")
    .focus(function() {
      inputCtaMov = $(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 (){
      var inputs = $(this).closest('form').find(':input');

      txtThis = this;
      txtGetValue = document.getElementById($(this).attr('id')+"Nom");
      txtNext = inputs.eq(inputs.index(this)+2);

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

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.cuentas.cta_con != "N") {
                txtGetValue.value = "";
                alErrorFocusTimer({"msg":{"type":"error","title":"No puede usar esta cuenta","text":"La cuenta "+txtThis.value+" no es de movimiento, no la puede usar", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cuentas.cta_nom;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // VALID CONSOLIDADO
    $("#txtConso")
    .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 = txtConsoNom;
      txtNext = $("#btnGuardar");

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

      const parametros = new FormData();
      parametros.append("action", "consultarEmp");
      parametros.append("txtCod", 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) {
          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 BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "borrar");

        parametros.append("txtCod", txtCod.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 = "";
              txtCod.focus();
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

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

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

      parametros.append("nuevo", nuevo);
      parametros.append("txtCod", txtCod.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtCod", txtCod.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtNomc", txtNomc.value);
      parametros.append("txtNit", txtNit.value);
      parametros.append("dtFinie", dtFinie.value);
      parametros.append("dtFciee", dtFciee.value);
      parametros.append("dtFtrab", dtFtrab.value);
      parametros.append("txtMoneda", txtMoneda.value);
      parametros.append("txtCtaic", txtCtaic.value);
      parametros.append("txtCtaiv", txtCtaiv.value);
      parametros.append("txtCtarisr", txtCtarisr.value);
      parametros.append("txtCtariva", txtCtariva.value);
      parametros.append("txtCtacaj", txtCtacaj.value);
      parametros.append("txtCtacomb", txtCtacomb.value);
      parametros.append("txtCtaven", txtCtaven.value);
      parametros.append("txtCtaserv", txtCtaserv.value);
      parametros.append("txtCtaexport", txtCtaexport.value);
      parametros.append("txtConso", txtConso.value);
      parametros.append("cbExensn", cbExensn.checked);
      parametros.append("cbPequesn", cbPequesn.checked);

      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) {
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            limpiar();
            txtCod.value = "";
            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") ? $('#'+inputEmpresas).focus() : 0;
        (relatedTarget == "#pills-2") ? $('#'+inputCtaMov).focus() : 0;
      }
    }
  });

</script>