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

$empCod = $_SESSION['empCod'];

# QUERYS
$sClasic = "SELECT *, TRIM(cla_nom) as cla_nom FROM clasic";
$sVendedor = "SELECT *, TRIM(vend_nom) as vend_nom FROM vendedor";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["clasic"] = $db->query($sClasic);
$select["vendedor"] = $db->query($sVendedor);
$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>
              <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 Clientes</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-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="txtCodp">Codigo</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCodp" maxlength="20">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-6">
                            <label for="txtNom">Nombre del Cliente</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNom" maxlength="100">
                          </div>
                          <div class="col-6">
                            <label for="txtNomFac">Nombre para Facturar</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNomFac" maxlength="100">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-6">
                            <label for="txtDir">Dirección Fiscal</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtDir" maxlength="150">
                          </div>
                          <div class="col-6">
                            <label for="txtDirFac">Dirección Facturar</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtDirFac" maxlength="100">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label for="txtNit">Nit</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNit" maxlength="20">
                          </div>
                          <div class="col-3">
                            <label for="txtTel">Telefono</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtTel" maxlength="50">
                          </div>
                          <div class="col-6">
                            <label for="txtCont">Nombre del Contacto</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCont" maxlength="80">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-7">
                            <label for="txtEmail">Correo Electronico</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtEmail" maxlength="100">
                          </div>
                          <div class="col-md-5">
                            <label for="selClasi">Grupo</label>
                            <select class="form-control form-control-sm form-control-as font-size-m" name="selClasi" id="selClasi">
                              <?php
                                while ($rec = $db->fetchAssoc($select['clasic'])) {
                                  echo  '<option value="'.$rec['cla_cod'].'">'.utf8_encode($rec['cla_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-2">
                            <label for="txtCta">Cuenta Contable</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                          </div>
                          <div class="col-md-4">
                            <label for="txtCtaNom">Nombre de Cuenta Clientes</label>
                            <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="Cuenta no definida" disabled>
                          </div>
                          <div class="col-md-2">
                            <label for="txtCtad">Cuenta Anticipos</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCtad" placeholder="">
                          </div>
                          <div class="col-md-4">
                            <label for="txtCtadNom">Nombre de Cuenta Anticipos</label>
                            <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtadNom" placeholder="Cuenta no definida" disabled>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-2">
                            <label for="numDcre">Dias de Crédito</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numDcre" placeholder="">
                          </div>
                          <div class="col-md-5">
                            <label for="selVend">Vendedor</label>
                            <select class="form-control form-control-sm form-control-as font-size-m" name="selVend" id="selVend">
                              <?php
                                while ($rec = $db->fetchAssoc($select['vendedor'])) {
                                  echo  '<option value="'.$rec['vend_cod'].'">'.utf8_encode($rec['vend_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-1">
                            <label> </label>
                          </div>
                          <div class="col-4">
                            <label class="pr-1">Se le hace Retención IVA</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crReti1" name="crReti" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crReti1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crReti2" name="crReti" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crReti2">No</label>
                            </div>
                          </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>
                    </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('../busCliencc/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 inputNumb = "numNumb";
  var inputCtaMov = "txtCta";
  var inputClien = "txtCodp"

  const txtCodp = document.thisform.txtCodp;
  const txtNom = document.thisform.txtNom;
  const txtNomFac = document.thisform.txtNomFac;
  const txtCta = document.thisform.txtCta;
  const txtCtad = document.thisform.txtCtad;
  const txtDir = document.thisform.txtDir;
  const txtDirFac = document.thisform.txtDirFac;
  const txtNit = document.thisform.txtNit;
  const txtTel = document.thisform.txtTel;
  const txtEmail = document.thisform.txtEmail;
  const txtCont = document.thisform.txtCont;
  const selClasi = document.thisform.selClasi;
  const selVend = document.thisform.selVend;
  const numDcre = document.thisform.numDcre;
  const crReti = document.thisform.crReti;



  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtCodp.value)) {
        txtCodp.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO DEL CLIENTE"}});
        return true;
      }
      if (isNullPer(txtNom.value)) {
        txtNom.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nombre del Cliente"}});
        return true;
      }
      if (isNullPer(txtNomFac.value)) {
        txtNomFac.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el nombre para facturar"}});
        return true;
      }
      if (isNullPer(txtDirFac.value)) {
        txtDirFac.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la direecion para facturar"}});
        return true;
      }
      if (isNullPer(txtCta.value)) {
        txtCta.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de la Cuenta Contable del Cliente"}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nit del Cliente"}});
        return true;
      }
    } else {
      if (isNullPer(txtCodp.value)) {
        limpiar();
        return true;
      }
    }
    return false;
  }
  
  function restriccionCamposVacios() {
    if (isNullPer(txtCodp.value)) {
      txtCodp.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar EL CODIGO DEL CLIENTE"}});
      return true;
    }
    return false;
  }

  function restriccionCtadif() {
    if (isNullPer(txtCtad.value)) {
      txtCtadNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionCtac() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function consultarCorr() {
    const parametros = new FormData();
    parametros.append("action", "consultarCorr");

    $.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);
//          nuevoClien = true;
//          nuevo = true;
        } else {
          txtCodp.value = jsonJS.codcorr;
        }
      }
    });
  }

  function limpiar(){
    txtNom.value = "";
    txtDir.value = "";
    txtNomFac.value = "";
    txtDirFac.value = "";
    txtDir.value = "";
    txtNit.value = "";
    txtTel.value = "";
    txtEmail.value = "";
    txtCont.value = "";
    txtCta.value = "";
    txtCtaNom.value = "";
    txtCtad.value = "";
    txtCtadNom.value = "";
    numDcre.value = 0;
    crReti.value = "N";
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    txtNom.value = "";
    txtDir.value = "";
    txtNomFac.value = "";
    txtDirFac.value = "";
    txtDir.value = "";
    txtNit.value = "";
    txtTel.value = "";
    txtEmail.value = "";
    txtCont.value = "";
    txtCta.value = "";
    txtCtaNom.value = "";
    txtCtad.value = "";
    txtCtadNom.value = "";
    numDcre.value = 0;
    crReti.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 NOMBRE
    $("#txtNom")
    .blur(function() {
      if (nuevo) {
        txtNomFac.value = txtNom.value;
      }
    });

    // VALID DIRECCION
    $("#txtDir")
    .blur(function() {
      if (nuevo) {
        txtDirFac.value = txtDir.value;
      }
    });

    // VALID CODIGO
    $("#txtCodp")
    .focus(function() {
//      txtCodp.value = "";
      limpiar();
      inputClien = $(this).attr('id');
     // consultarCorr();
    })
    .init(function() {
    //  consultarCorr();
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarCliencc");
      parametros.append("txtCod", txtCodp.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);
            nuevoClien = true;
            nuevo = true;
          } else {
            if (isNullPer(jsonJS.cliencc)) {
              nuevoClien = true;
              nuevo = true;
              //txtNit.value=txtCodp.value;
              txtCta.value="112101";
              txtCtaNom.value="CLIENTES SERVICIOS";
              txtCtad.value="217102";
              txtCtadNom.value="ANTICIPOS DE CLIENTES QUETZALES";
            } else {
              txtNom.value = jsonJS.cliencc.cli_nom;
              txtNomFac.value = jsonJS.cliencc.cli_nomfac;
              txtDir.value = jsonJS.cliencc.cli_dir;
              txtDirFac.value = jsonJS.cliencc.cli_dirfac;
              txtNit.value = jsonJS.cliencc.cli_nit;
              txtTel.value = jsonJS.cliencc.cli_tel;
              txtEmail.value = jsonJS.cliencc.cli_email;
              txtCont.value = jsonJS.cliencc.cli_cont;
              selClasi.value = jsonJS.cliencc.cli_clas;
              txtCta.value = jsonJS.cliencc.cli_cta;
              txtCtaNom.value = jsonJS.cliencc.cli_ctanom;
              txtCtad.value = jsonJS.cliencc.cli_ctad;
              txtCtadNom.value = jsonJS.cliencc.cli_ctadnom;
              numDcre.value = jsonJS.cliencc.cli_dcre;
              crReti.value = jsonJS.cliencc.cli_reti;
              selVend.value = jsonJS.cliencc.cli_ven;
              nuevoClien = false;
              nuevo = false;
            }
          }
        }
      });
    });

    // VALID CTAC
    $("#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 (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtaNom");
      txtNext = document.getElementById("txtCtad");

      $(txtThis).off("blur");
      if (restriccionCtac()) {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) {
          console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

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

    // VALID CUENTA ANTICIPO
    $("#txtCtad")
    .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 (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtadNom");
      txtNext = document.getElementById("numDcre");

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

      const parametros = new FormData();
      parametros.append("action", "consultarCtad");
      parametros.append("txtCtad", 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 = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.cuentas.cta_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("txtCodp", txtCodp.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();
              txtCodp.value = "";
            }
          }
        });
      }

      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("txtCodp", txtCodp.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtNomFac", txtNomFac.value);
      parametros.append("txtDir", txtDir.value);
      parametros.append("txtDirFac", txtDirFac.value);
      parametros.append("txtNit", txtNit.value);      
      parametros.append("txtTel", txtTel.value);
      parametros.append("txtCont", txtCont.value);
      parametros.append("txtEmail", txtEmail.value);
      parametros.append("selClasi", selClasi.value);
      parametros.append("txtCta", txtCta.value);
      parametros.append("txtCtad", txtCtad.value);
      parametros.append("numDcre", numDcre.value);
      parametros.append("crReti", crReti.value);
      parametros.append("selVend", selVend.value);

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

</script>