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

$empCod = $_SESSION['empCod'];

# QUERYS
$sClasi = "SELECT *, TRIM(cla_nom) as cla_nom FROM clasi";
$sCodtel = "SELECT *, TRIM(ctp_nom) as ctp_nom FROM codtelpais";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["clasi"] = $db->query($sClasi);
$select["codtelpais"] = $db->query($sCodtel);
$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 Cliente</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-1">
                            <label class="font-size-md" for="numIdPed">Codigo</label>
                            <input type="number" class="form-control form-control-md form-control-as limpiar" id="numIdPed">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md" for="txtCel">Celular</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtCel" maxlength="20">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-8">
                            <label class="font-size-md" for="txtNom">Nombre del Cliente</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtNom" maxlength="150">
                          </div>
                          <div class="col-4">
                            <label class="font-size-md" for="txtNit">Nit</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtNit" maxlength="20">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-7">
                            <label class="font-size-md" for="txtDir">Dirección</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtDir" maxlength="150">
                          </div>
                          <div class="col-5">
                            <label class="font-size-md" for="txtTel">telefono</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtTel" maxlength="60">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-10">
                            <label class="font-size-md" for="txtEmail">email</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtEmail" maxlength="150">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md" for="txtZona">Zona</label>
                            <input type="number" class="form-control form-control-md form-control-as" id="txtZona" maxlength="5">
                          </div>
                        </div> 
                        <div class="form-row">
                          <div class="col-6">
                            <label class="font-size-md" for="txtNomfac">Nomombre para Factura</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtNomfac" maxlength="150">
                          </div>
                          <div class="col-6">
                            <label class="font-size-md" for="txtDirfac">Direccion para Factura</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtDirfac" maxlength="150">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-10">
                            <label class="font-size-md" for="txtObsPed">Observaciones</label>
                            <textarea class="form-control form-control-md form-control-as" id="txtObsPed" rows="2"></textarea>
                          </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('../busClienPedId/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputIdPed = "numIdPed";
  
  const numIdPed = document.thisform.numIdPed;
  const txtCel = document.thisform.txtCel;
  const txtNom = document.thisform.txtNom;
  const txtNit = document.thisform.txtNit;
  const txtDir = document.thisform.txtDir;
  const txtTel = document.thisform.txtTel;
  const txtEmail = document.thisform.txtEmail;
  const txtZona = document.thisform.txtZona;
  const txtNomfac = document.thisform.txtNomfac;
  const txtDirfac = document.thisform.txtDirfac;
  const txtObsPed = document.thisform.txtObsPed;

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtNom.value)) {
        txtNom.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nombre 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(txtCel.value)) {
        limpiar();
        return true;
      }
    }
    return false;
  }
  
  function restriccionCamposVacios() {
  }

 

  function limpiar(){
    txtCel.value = "";
    txtNom.value = "";
    txtNit.value = "";
    txtDir.value = "";
    txtTel.value = "";
    txtEmail.value = "";
    txtZona.value = "";
    txtNomfac.value = "";
    txtDirfac.value = "";
    txtObsPed.value = "";
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    txtCel.value = "";
    txtNom.value = "";
    txtNit.value = "";
    txtDir.value = "";
    txtTel.value = "";
    txtEmail.value = "";
    txtZona.value = "";
    txtNomfac.value = "";
    txtDirfac.value = "";
    txtObsPed.value = "";

    // 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
    $("#numIdPed")
    .focus(function() {
      numIdPed.value = "";
      limpiar();
      inputIdPed = $(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", "consultarClienped");
      parametros.append("numIdPed", numIdPed.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 (jsonJS.clien_ped === null) {
              nuevoClien = true;
              nuevo = true;
              if (numIdPed.value>0) {
                numIdPed.focus();
                alWarning({"msg":{"title":"Este Codigo no existe","text":"Si va a registrar un cliente nuevo coloque 0 en el codigo"}});
                return true;
              }
            } else {
              txtCel.value = jsonJS.clien_ped.clip_cel;              
              txtNom.value = jsonJS.clien_ped.clip_nom; //encode_utf8();
              txtNit.value = jsonJS.clien_ped.clip_nit;
              txtDir.value = jsonJS.clien_ped.clip_dir; //encode_utf8();
              txtTel.value = jsonJS.clien_ped.clip_tel;
              txtEmail.value = jsonJS.clien_ped.clip_email; //encode_utf8();
              txtZona.value = jsonJS.clien_ped.clip_zona;
              txtNomfac.value = jsonJS.clien_ped.clip_nomfac; //encode_utf8();
              txtDirfac.value = jsonJS.clien_ped.clip_dirfac; //encode_utf8();
              txtObsPed.value = jsonJS.clien_ped.clip_obs; //encode_utf8();
              nuevoClien = false;
              nuevo = false;
            }
          }
        }
      });
    });

    
    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "borrar");

        parametros.append("numIdPed", numIdPed.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();
              numIdPed.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("numIdPed", numIdPed.value);
      parametros.append("txtCel", txtCel.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtNit", txtNit.value);
      parametros.append("txtDir", txtDir.value);
      parametros.append("txtTel", txtTel.value);
      parametros.append("txtEmail", txtEmail.value);      
      parametros.append("txtZona", txtZona.value);
      parametros.append("txtNomfac", txtNomfac.value);
      parametros.append("txtDirfac", txtDirfac.value);
      parametros.append("txtObsPed", txtObsPed.value);

      numIdPed.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();
            numIdPed.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(txtCel.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>