<?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 Proveedor</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="txtProv">Nombre del Proveedor</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtProv" maxlength="100">
                          </div>
                          <div class="col-6">
                            <label for="txtRazon">Razón Social</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtRazon" maxlength="100">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-7">
                            <label for="txtDir">Dirección</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtDir" maxlength="150">
                          </div>
                          <div class="col-5">
                            <label for="txtRegimen">Regimen ISR</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtRegimen" maxlength="100">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2.5">
                            <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-2.5">
                            <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-2.5">
                            <label for="txtFax">Fax</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtFax" maxlength="20">
                          </div>
                          <div class="col-4">
                            <label for="txtTel2">Telefono 2</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtTel2" maxlength="20">
                          </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['clasi'])) {
                                  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 Proveedores</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="selCodtel">Codigo de Area</label>
                            <select class="form-control form-control-sm form-control-as font-size-m" name="selCodtel" id="selCodtel">
                              <?php
                                while ($rec = $db->fetchAssoc($select['codtelpais'])) {
                                  echo  '<option value="'.$rec['ctp_cod'].'">'.utf8_encode($rec['ctp_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-1">
                            <label> </label>
                          </div>
                          <div class="col-4">
                            <label class="pr-1">Se le hace Retención ISR</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crRet1" name="crRet" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crRet1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crRet2" name="crRet" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crRet2">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('../busProvcp/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 inputProvee = "txtNit"

  const txtCodp = document.thisform.txtCodp;
  const txtProv = document.thisform.txtProv;
  const txtCta = document.thisform.txtCta;
  const txtCtad = document.thisform.txtCtad;
  const txtRazon = document.thisform.txtRazon;
  const txtDir = document.thisform.txtDir;
  const txtRegimen = document.thisform.txtRegimen;
  const txtNit = document.thisform.txtNit;
  const txtTel = document.thisform.txtTel;
  const txtFax = document.thisform.txtFax;
  const txtEmail = document.thisform.txtEmail;
  const txtTel2 = document.thisform.txtTel2;
  const selClasi = document.thisform.selClasi;
  const selCodtel = document.thisform.selCodtel;
  const numDcre = document.thisform.numDcre;
  const crRet = document.thisform.crRet;



  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 PROVEEDOR"}});
        return true;
      }
      if (isNullPer(txtProv.value)) {
        txtProv.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nombre del Proveedor"}});
        return true;
      }
      if (isNullPer(txtRazon.value)) {
        txtRazon.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la razon social"}});
        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 Proveedor"}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Nit del Proveedor"}});
        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 PROVEEDOR"}});
      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 limpiar(){
    txtProv.value = "";
    txtDir.value = "";
    txtRazon.value = "";
    txtRegimen.value = "";
    txtDir.value = "";
    txtNit.value = "";
    txtTel.value = "";
    txtFax.value = "";
    txtEmail.value = "";
    txtTel2.value = "";
    txtCta.value = "2110101";
    txtCtaNom.value = "PROVEEDORES LOCALES";
    txtCtad.value = "";
    txtCtadNom.value = "";
    numDcre.value = 0;
    crRet.value = "N";
    selCodtel.value = "502";
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    txtProv.value = "";
    txtDir.value = "";
    txtRegimen.value = "";
    txtDir.value = "";
    txtNit.value = "";
    txtTel.value = "";
    txtFax.value = "";
    txtEmail.value = "";
    txtTel2.value = "";
    txtCta.value = "2110101";
    txtCtaNom.value = "PROVEEDORES LOCALES";
    txtCtad.value = "";
    txtCtadNom.value = "";
    numDcre.value = 0;
    crRet.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
    $("#txtCodp")
    .focus(function() {
      txtCodp.value = "";
      limpiar();
      inputProvcp = $(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", "consultarProvcp");
      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);
            nuevoProvee = true;
            nuevo = true;
          } else {
            if (jsonJS.provcp === null) {
              nuevoProvee = true;
              nuevo = true;
              txtNit.value=txtCodp.value;
            } else {
              txtProv.value = jsonJS.provcp.pro_nom;
              txtRazon.value = jsonJS.provcp.pro_razon;
              txtRegimen.value = jsonJS.provcp.pro_regimen;
              txtDir.value = jsonJS.provcp.pro_dir;
              txtNit.value = jsonJS.provcp.pro_nit;
              txtTel.value = jsonJS.provcp.pro_tel;
              txtFax.value = jsonJS.provcp.pro_fax;
              txtEmail.value = jsonJS.provcp.pro_email;
              txtTel2.value = jsonJS.provcp.pro_tel2;
              selClasi.value = jsonJS.provcp.pro_clas;
              txtCta.value = jsonJS.provcp.pro_cta;
              txtCtaNom.value = jsonJS.provcp.pro_ctanom;
              txtCtad.value = jsonJS.provcp.pro_ctad;
              txtCtadNom.value = jsonJS.provcp.pro_ctadnom;
              numDcre.value = jsonJS.provcp.pro_dcre;
              crRet.value = jsonJS.provcp.pro_retsn;
              selCodtel.value = jsonJS.provcp.pro_codtelpais;
              nuevoProvee = 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 CONVERSION
    $("#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("txtProv", txtProv.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("txtProv", txtProv.value);
      parametros.append("txtRazon", txtRazon.value);
      parametros.append("txtDir", txtDir.value);
      parametros.append("txtRegimen", txtRegimen.value);
      parametros.append("txtNit", txtNit.value);      
      parametros.append("txtTel", txtTel.value);
      parametros.append("txtFax", txtFax.value);
      parametros.append("txtTel2", txtTel2.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("crRet", crRet.value);
      parametros.append("selCodtel", selCodtel.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>