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

$dtFec=date("Y-m-d");
$nAnio=date("Y");
$nMes=date("m");

$empCod = $_SESSION['empCod'];

# QUERYS
$sMeses = "SELECT * FROM meses";
$sTipopol = "SELECT * FROM tipopol";
$sBancos = "SELECT *, 
              TRIM(ban_nom) as ban_nom,
              TRIM(ban_ctab) as ban_ctab,
              TRIM(ban_ctac) as ban_ctac
            FROM bancos WHERE ban_emp='$empCod'";
$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["meses"] = $db->query($sMeses);
$select["tipopol"] = $db->query($sTipopol);
$select["bancos"] = $db->query($sBancos);
$select["bancos2"] = $db->query($sBancos);
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";
$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">Anular/Borrar Depositos de Clientes</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-10">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-md-6">
                            <label for="selBan">Banco</label>
                            <select class="form-control form-control-sm form-control-as font-size-lg" name="selBan" id="selBan">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos'])) {
                                  echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-3">
                            <label for="numNum">No. Deposito</label>
                            <input type="number" class="form-control form-control-sm form-control-as font-size-lg" id="numNum" placeholder="0">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-md-3">
                            <label for="dtFec">Fecha Deposito</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="" disabled>
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="numTot">Valor del Deposito</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTot" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numTcam" disabled>
                          </div>
                        </div>
                        <div class="form-row">
                        </div>
                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtCon">Concepto</label>
                            <textarea class="form-control form-control-sm form-control-as" id="txtCon" rows="2" disabled></textarea>
                          </div>
                        </div>
                      </div>

                      <h3 class="text-light"></h3>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblPol">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center">CUENTA</th>
                                    <th scope="col" class="text-center">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center">DEBE</th>
                                    <th scope="col" class="text-center">HABER</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotDebe" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotHaber" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-2">
                      <div class="form-group position-fixed-sm">

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnAnular" type="button">Anular</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </form>

              </div>

            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var totant = 0;
  var nuevoiva = true;
  var rfecAntI = "0000-00-00";
  var inputDepo = "numNum";
  var tblPolAnt;
  var mesCerrado = <?php echo $mesCerrado ?>;
  var mesCerradoI = <?php echo $mesCerrado ?>;
  var btnAddEdit = "00";
  var nuevoClien = true;
  var inputCtaMov = "txtCta";
  var inputClien = "txtNit"

  var sumcta=0;
  var falcta=0;

  const numNum = document.thisform.numNum;
  const selBan = document.thisform.selBan;
  const dtFec = document.thisform.dtFec;
  const numTot = document.thisform.numTot;
  const numTcam = document.thisform.numTcam;
  const txtCon = document.thisform.txtCon;

  const txtCta = document.getElementById("txtCta");
  const txtCtaNom = document.getElementById("txtCtaNom");
  const numDebe = document.getElementById("numDebe");
  const numHaber = document.getElementById("numHaber");


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(selBan.value)) {
        selBan.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Banco"}});
        return true;
      }
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DEPOSITO"}});
        return true;
      }
    } else {
      if (isNullPer(selBan.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }


  function restriccionCamposVacios() {
    if (isNullPer(selBan.value)) {
      selBan.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el BANCO"}});
      return true;
    }
    if (isNullPer(numNum.value)) {
      numNum.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DEPOSITO"}});
      return true;
    }
    return false;
  }

  function restriccionMesCerrado() {
    if (mesCerrado) {
      alError({"msg":{"type":"error","title":"Mes Cerrado","text":"No puede trabajar con este mes porque ya fue cerrado", "ok":"Aceptar"}});
      return true;
    }
    return false;
  }

  function addRowPol(cta, ctaNom, debe, haber){
    const row = "<tr>"
                +"<td id='dataCta'>"+cta+"</td>"
                +"<td id='dataCtaNom'>"+ctaNom+"</td>"
                +"<td id='dataDebe' class='text-right'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }


  function consultarT(){
    if (restriccion(true)) {return};
    
    //txtNext = dtFec;

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

    parametros.append("numNum", numNum.value);
    parametros.append("selBanCod", selBan.value);

    //txtNext.focus()

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

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          limpiar();
          tblClear("tblPol");
          sumPol();
          if (jsonJS.movi === null) {
            nuevo = true;
            totant = 0;
            alWarning({"msg":{"title":"NO EXISTE EL DEPOSITO","text":"Este deposito no ha sido registrado"}});
            return true;
            chmod='cxp';
          } else {
            dtFec.value = jsonJS.movi.mov_fec;
            numTot.value = jsonJS.movi.mov_tot;
            numTcam.value = jsonJS.movi.mov_tcam;
            txtCon.value = jsonJS.movi.mov_con;
            chmod = jsonJS.movi.mov_mod;
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            totant = jsonJS.movi.mov_tot;            
            nuevo = false;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }


  function limpiar(todo = false){
    dtFec.value= '<?php echo $dtFec; ?>';    
  //  numTcam.value = (1).toFixed(5);
    numTot.value = (0).toFixed(2);
    txtCon.value = "";
  }

  function sumPol(){
    $("#tblPol #dataTotDebe").text(tblSumCol("tblPol", "dataDebe").toFixed(2));
    $("#tblPol #dataTotHaber").text(tblSumCol("tblPol", "dataHaber").toFixed(2));
  }


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    selBan.value = 1;


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

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

    // FOCUS NUMERO DE CHEQUE
    $("#selBan").focus(function() {
      limpiar();
      tblClear("tblPol");
      sumPol();
    });

    // FOCUS NUMERO DE CHEQUE
    $("#numNum").focus(function() {
      numNum.value="";
      limpiar();
      tblClear("tblPol");
      sumPol();
    });

    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      setTimeout(function(){
        if (!$('#selBan').is(':focus') && $("#tblPol tbody").children().length == 0) {
          consultarT();
        }
      },0);
    })
    .change(function (){
      consultarT();
    });

    // VALID FECHAS
    $("#dtFec")
    .blur(function (){
      if (restriccionCamposVacios()) {return};
        txtThis = dtFec;

        const parametros = new FormData();
        parametros.append("action", "mCerrado");
        parametros.append("dtFec", txtThis.value);

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

            if(jsonJS.error == true){
              alError(jsonJS);
            } else {
              if (jsonJS.ciemes === null) {
                mesCerrado = false;
              } else {
                if (jsonJS.ciemes.ciem_stat == "C") {
                  mesCerrado = true;
                  setTimeout(function(){
                    if (!$('#numNum').is(':focus') && !$('#selBan').is(':focus')) {
                      if ($('input, textarea').is(':focus')) {
                        restriccionMesCerrado();
                      }
                    }
                  },0);
                } else {
                  mesCerrado = false;
                }
              }
            }
          }
        });
    }); 

    // FOCUS FECHA
    $("#dtFec").focus(function (){
      if (restriccionCamposVacios()) {return};
    });

    // FOCUS VALOR TRANSF, CONCEPTO
    $("#numTot,  #txtCon").focus(function (){
      if (restriccionCamposVacios()) {return};
    });


    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      if (chmod != 'cxc') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"EstE Deposito no fue registrado en Cuentas por Cobrar, intente borrarla desde bancos"}});
        return true;
      }
      if (nuevo) {
        numNum.focus();
        alWarning({"msg":{"title":"NO REGISTRADO","text":"Este Deposito no ha sido registrado."}});
        return true;
      }
      const fnT = function(){
        colPol = ["cta", "ctaNom", "debe", "haber"];

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

        parametros.append("selBanCod", selBan.value);
        parametros.append("numNum", numNum.value);
        parametros.append("dtFec", dtFec.value);
        parametros.append("tblPolAnt", tblPolAnt);
        
        numNum.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);
              numNum.value = "";
              limpiar();
              tblClear("tblPol");
              sumPol();
              numNum.focus();
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      admClave(fnT, fnF);
    });

    // CLICK ANULAR
    $("#btnAnular").click(function (){
     // if (restriccion()) {return};
      if (nuevo) {
        numNum.focus();
        alWarning({"msg":{"title":"NO REGISTRADO","text":"Este Deposito no ha sido registrado."}});
        return true;
      }

      if (chmod != 'cxc') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este Deposito  no fue registrado en Cuentas por Cobrar, intente borrarla desde bancos"}});
        return true;
      }
      
      const fnT = function(){
        colPol = ["cta", "ctaNom", "debe", "haber"];

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

        parametros.append("selBanCod", selBan.value);
        parametros.append("numNum", numNum.value);
        parametros.append("dtFec", dtFec.value);
        parametros.append("tblPolAnt", tblPolAnt);
        
        numNum.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);
              numNum.value = "";
              limpiar();
              tblClear("tblPol");
              sumPol();
              numNum.focus();
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      admClave(fnT, fnF);
    });

    
  });


  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-00-tab').text("Modificar");
    $('#btnAgregar').hide();
    $('#btnModificar').show();

    const dataCta = $(this).parents("tr").find("#dataCta");
    const dataCtaNom = $(this).parents("tr").find("#dataCtaNom");
    const dataDebe = $(this).parents("tr").find("#dataDebe");
    const dataHaber = $(this).parents("tr").find("#dataHaber");

    txtCta.value = dataCta.text();
    txtCtaNom.value = dataCtaNom.text();
    numDebe.value = dataDebe.text();
    numHaber.value = dataHaber.text();

    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataCta.text(txtCta.value);
      dataCtaNom.text(txtCtaNom.value);
      dataDebe.text(isNullNumber(numDebe.value).toFixed(2));
      dataHaber.text(isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
    });
  });

  // MODALPOL HIDDEN
  $('#modalPol').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificar");
  });

/*
    // FOCUS INPUT
    $("form[name='thisformfac'] input, select, textarea").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNumI").is(":focus")) && !($("#txtNitI").is(":focus"))) {
        if (restriccionCamposVaciosiva()) {return};
      }
    });
*/

  // FOCUS PILL SHOW
  $('a[data-toggle="pill"]').on('show.bs.tab', function (e) {
      const target = e.target.attributes.href.value;
      const relatedTarget = e.relatedTarget.attributes.href.value;

      if (target == "#pills-11" && (isNullPer(txtSerieI.value) || isNullPer(numNumI.value))) {
        if(restriccionCamposVaciosiva(false)) {return false}
      } else if (target == "#pills-12" && (isNullPer(txtSerieI.value) || isNullPer(numNumI.value) || isNullPer(txtNitI.value))) {
        if(restriccionCamposVaciosiva()) {return false}
      }
  });

  // FOCUS PILL SHOWN
  $('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(numNum.value)) || target != "#pills-0") {
        if (target == "#pills-10" && isNullPer(txtSerieI.value)) { txtSerieI.focus();
        } else if (target == "#pills-10" && isNullPer(numNumI.value)) { numNumI.focus();
        } else if (target == "#pills-10" && isNullPer(txtNitI.value)) { txtNitI.focus();
        } else if (relatedTarget == "#pills-12") { $("#"+inputCtaMov).focus();
        } else {
          ($(target+' select:visible:first').length) ? $(target+' select:visible:first').focus() : $(target+' input:visible:first').focus();
        }
      } else {
        (target == "#pills-2") ? dtFec.focus() : 0;
      }
    }
  });
</script>
