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

$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));
?>
<?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">Cargar Archivos de Ventas</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 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-6">
                      <div class="custom-file">
                        <input type="file" class="custom-file-input" id="customFile" name="customFile" lang="es">
                        <label class="custom-file-label" for="customFile">Seleccionar Archivo</label>
                      </div>
                    </div>
                  </div>
                  <div class="form-row">
                    <div class="col-6">
                      <label> </label>
                    </div>
                  </div>
                  <div class="form-row">
<!---                    
                    <div class="col-1.5">
                      <label for="txtCtac">Asignar Cuenta de Ventas</label>
                      <input type="text" class="form-control form-control-sm form-control-as" id="txtCtac" placeholder="">
                    </div>
                    <div class="col-3">
                      <label for="txtCtacNom"> </label>
                      <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtacNom" placeholder="Cuenta no definida" disabled>
                    </div>
                    <div class="col-3">
                      <label class="pr-1"></label><br>
                      <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="crTipov1" name="crTipov" class="custom-control-input" value="V">
                        <label class="custom-control-label" for="crTipov1">Venta</label>
                      </div>
                      <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="crTipov2" name="crTipov" class="custom-control-input" value="S">
                        <label class="custom-control-label" for="crTipov2">Servicios</label>
                      </div>
                      <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="crTipov3" name="crTipov" class="custom-control-input" value="E">
                        <label class="custom-control-label" for="crTipov3">Exporta.</label>
                      </div>
                      <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="crTipov4" name="crTipov" class="custom-control-input" value="X">
                        <label class="custom-control-label" for="crTipov4">Exento</label>
                      </div>
                    </div>
---->                    
                  </div>

                  <div class="form-row">
                    <div class="col-6">
                      <label> </label>
                    </div>
                  </div>
                  <div class="form-row">
                    <div class="col-3">
                      <button class="btn btn-warning btn-block" id="btnCargar" type="button">Carga Masiva</button>
                    </div>
                    <div class="col-3">
                      <button class="btn btn-primary btn-block" id="btnRevierte" type="button">Revertir Carga</button>
                    </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('../busCuentasMov/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var tblPolAnt;
  var mesCerrado = false;
  var btnAddEdit = "00";
  var inputCtaMov = "txtCta";
  var tblErrores;
//  const ctaven = <?php echo $_SESSION['empCtaserv']; ?>;

//  const txtCtac = document.thisform.txtCtac;
//  const crTipov = document.thisform.crTipov;

  const customFile = document.getElementById("customFile");

  function restriccion(consultar = false, mes = true){
    if (!consultar) {
      if (isNullPer(txtCtac.value)) {
        txtCtac.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Debe ingresar el numero de Cuenta de Ventas"}});
        return true;
      }
    } else {
      if (isNullPer(txtCtac.value)) {
        return true;
      }
    }
    return false;
  }


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

  function CargarVenta(imprimir = false){
    if (restriccion()) {return};

    const parametros = new FormData();
    parametros.append("action", "cargarArchivo");
//    parametros.append("txtCtac", txtCtac.value);
//    parametros.append("crTipov", crTipov.value);

    txtCtac.focus();
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"cargaexcel.php",
      type:  "post",
      contentType: false,
      processData: false,
      beforeSend: function () {
        alLoad("Procesando...")
      },
      success: function (jsonPhp) {
        console.log(jsonPhp);
        const jsonJS = JSON.parse(jsonPhp);
        tblErrores = JSON.stringify(jsonJS.arrayErrores);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          imprimirDocumento();
          console.log("aqui si paso");
          alSuccess(jsonJS);
        }
      }
    });
  }

  $(document).ready(function() {
    $(this).find('input:enabled:first').focus();
//    txtCtac.value = ctaven;
//    txtCtacNom.value="";
//    crTipov.value = "V";

    // SHOW MODAL
    $('#modalPol').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      }
    });

    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });

    $('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        $('.custom-file-label').html(fileName);
    });

    // CLICK PILLS-1
    $('#pills-1-tab').click(function (){
      if (isNullPer(txtCtac.value)) {
        document.getElementById('pills-0-tab').click();
        txtCtac.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la Cuenta de Ventas"}});
        return true;
      }
    });

/*
    // VALID CTAC
    $("#txtCtac")
    .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-1-tab").click(); }
    })
    .change(function (){

      if (restriccionCtac()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCtac");
      parametros.append("txtCtac", txtCtac.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) {
              txtCtac.value = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtCtac.value+" no ha sido registrada", "ok":"Aceptar"}}, txtCtac);
            } else {
              txtCtacNom.value = jsonJS.cuentas.cta_nom;
              //alSuccess(jsonJS);
            }
          }
        }
      });
    });
*/
    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNum").is(":focus")) && !($("#txtNit").is(":focus"))) {
      }
    });


    // CLICK CARGAR ARCHIVO
    $("#btnCargar").click(function (){
      const fnT = function(){
//        customFile.value = "";
        carborr="C";
        if (customFile.value == '') {
          alWarning({"msg":{"title":"NO HA SELECCIONADO","text":"No ha selecionado ningun archivo para hacer la carga"}});
          return true;
        }
        const parametros = new FormData();
        parametros.append("action", "guardarCarga");
//        parametros.append("txtCtac", txtCtac.value);
//        parametros.append("crTipov", crTipov.value);
   //     parametros.append("file", document.thisform.customFile.files[0]);
        parametros.append("file", document.getElementById("customFile").files[0]);

        $.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);
            tblErrores = JSON.stringify(jsonJS.Errores);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              imprimirDocumento(tblErrores);
              alWarning({"msg":{"title":"SE CARGO LA INFORMACION SELECCIONADA","text":""}});
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    function imprimirDocumento(Errores){
      console.log(Errores);
      colErr = ["Linea", "Tipo", "NumDoc", "Mensaje"];
      const getTblErrores = "?TblErrores="+Errores;
      var url = window.location.origin+window.location.pathname+"printErrores.php"+getTblErrores;
      window.open(url, '_blank');
    }

    // CLICK REVIERTE CARGAR ARCHIVO
    $("#btnRevierte").click(function (){
      const fnT = function(){
//        customFile.value = "";
        carborr="B";
        if (customFile.value == '') {
          alWarning({"msg":{"title":"NO HA SELECCIONADO","text":"No ha selecionado ningun archivo para hacer la carga"}});
          return true;
        }
        const parametros = new FormData();
        parametros.append("action", "borrarCarga");
   //     parametros.append("file", document.thisform.customFile.files[0]);
        parametros.append("file", document.getElementById("customFile").files[0]);

        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Procesando ...")
          },
          success: function (jsonPhp) {
            console.log(jsonPhp);
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              alWarning({"msg":{"title":"SE ELIMINO LA INFORMACION SELECCIONADA","text":""}});
            }
          }
        });
      }
      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

  });


  // 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") {
        $(target+' input:visible:first').focus();
      } else if (target == "#pills-0") {
        btnCargar.focus();
      }
/*      
       else {
        (relatedTarget == "#pills-1") ? txtCtac.focus() : 0;
      }
*/      
      //$(target+' input:visible:first').focus();
    }
  });

</script>