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

# QUERYS
$sTipopol = "SELECT * FROM tipopol";
$sBancos = "SELECT * FROM bancos WHERE ban_emp='".$_SESSION['empCod']."'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipopol"] = $db->query($sTipopol);
$select["bancos"] = $db->query($sBancos);
$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');

        $modalImp = "modalImp";
        include_once('../../../php/includes/modalImp.php');
      ?>

      <!-- MODAL POLIZA -->
      <div class="modal fade" id="modalPol" tabindex="-1" role="dialog" aria-labelledby="modalPolTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="false">Buscar Cuentas</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-00" role="tabpanel" aria-labelledby="pills-00-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtCta">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtaNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebe">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebe" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHaber">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHaber" placeholder="0.00">
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnAgregar">Agregar</button>
                    <button type="button" class="btn btn-success btn-block" id="btnModificar">Modificar</button>
                  </form>

                </div>
                <div class="tab-pane fade" id="pills-01" role="tabpanel" aria-labelledby="pills-01-tab">
                  <?php
                    $a='00';
                    $b='01';
                    include('../busCuentasMov/index.html')
                  ?>
                </div>
              </div>

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

      <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>
            </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-3">
                            <label for="selTipo">Tipo de Poliza</label>
                            <select class="form-control form-control-sm form-control-as" name="selTipo" id="selTipo">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipopol'])) {
                                  echo  '<option value="'.$rec['tp_cod'].'">'.utf8_encode($rec['tp_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-3">
                            <label for="dtFec">Fecha</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-4">
                            <label for="selBan">Banco</label>
                            <select class="form-control form-control-sm form-control-as" name="selBan" id="selBan">
                              <option value="0">Sin Banco</option>
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos'])) {
                                  echo  '<option value="'.$rec['ban_num'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-2">
                            <label for="numNum">No. Poliza</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNum" placeholder="0">
                          </div>
                        </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="3"></textarea>
                          </div>
                        </div>
                      </div>

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

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-md-12">
                            <button type="button" class="btn btn-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                        </div>
                        <h3 class="text-light"></h3>
                        <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" width="50">ACCIONES</th>
                                    <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"></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>
                    <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-info btn-block" id="btnGuardarImprimir" type="button">Guardar/Imprimir</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnImprimir" type="button">Imprimir</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 tblPolAnt;
  var mesCerrado = false;
  var btnAddEdit = "00";
  var inputCtaMov = "txtCta";

  const numNum = document.thisform.numNum;
  const selTipo = document.thisform.selTipo;
  const selBan = document.thisform.selBan;
  const dtFec = document.thisform.dtFec;
  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");
  
  //selTipo.value = 5;

  function restriccion(consultar = false, mes = true){
    if (!consultar) {
      if (isNullPer(selTipo.value)) {
        selTipo.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el TIPO DE POLIZA"}});
        return true;
      }
      if (isNullPer(numNum.value)) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. POLIZA"}});
        return true;
      }
      if ($("#dataTotDebe").text() != $("#dataTotHaber").text()) {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La póliza no cuadra, verifique los valores"}});
        return true;
      }
      if (mes) {
        if (restriccionMesCerrado()) {
          return true;
        }
      }
    } else {
      if (isNullPer(selTipo.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(selTipo.value)) {
      selTipo.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el TIPO DE POLIZA"}});
      return true;
    }
    if (isNullPer(numNum.value)) {
      numNum.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. POLIZA"}});
      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 restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionModal() {
    if (restriccionCta()) {
      txtCta.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la CUENTA","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalPol').modal('toggle');
    return false;
  }

  function addRowPol(Cta, ctaNom, debe, haber){
    const row = "<tr>"
                +"<td scope='col'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalPol'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<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 consultarPolizas(){
    if (restriccion(true)) {return};

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

    parametros.append("numNum", numNum.value);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("selBanCod", selBan.value);
    parametros.append("dtFec", dtFec.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);
        tblPolAnt = JSON.stringify(jsonJS.poli_det);

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          limpiar();
          tblClear("tblPol");
          sumPol();

          if (jsonJS.ciemes === null) {
            mesCerrado = false;
          } else {
            if (jsonJS.ciemes.ciem_stat === "C") {
              mesCerrado = true;
            } else {
              mesCerrado = false;
            }
          }
          
          if (jsonJS.polizas === null) {
            nuevo = true;
          } else {
            txtCon.value = jsonJS.polizas.pol_con;
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            nuevo = false;
          }
          alClose();
          txtCon.focus();

          restriccionMesCerrado();
        }
      }
    });
  }

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

    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", numNum.value);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("selBanCod", selBan.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("txtCon", txtCon.value);
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    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) {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          if (imprimir) {
            imprimirPoliza(true, jsonJS.dtGrabado);
          }
          alSuccess(jsonJS);
          numNum.value = "";
          limpiar();
          tblClear("tblPol");
          sumPol();
        }
      }
    });
  }

  function imprimirPoliza(guardar = true, dtGrabado = ""){
    if (restriccion(false, false)) {return};

    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const getTipoCod = "?selTipoCod="+selTipo.value;
    const getBanCod = "&selBanCod="+selBan.value;
    const getNum = "&numNum="+numNum.value;
    const getFec = "&dtFec="+dtFec.value;
    const getCon = "&txtCon="+txtCon.value;
    const getDtGrabado = "&dtGrabado="+dtGrabado;
    const getTblPol = "&tblPol="+tblToJson(colPol, "tblPol", 0);
    const getBtn = (guardar) ? "&btn=Fecha y hora de Impresión y Grabado:" : "&btn=Fecha y hora de Impresión:";

    var url = window.location.origin+window.location.pathname+"print.php"+getTipoCod+getBanCod+getNum+getFec+getCon+getBtn+getDtGrabado+getTblPol;

    window.open(url, '_blank');
  }

  function limpiarModalPol(){
    txtCta.value = "";
    txtCtaNom.value = "";
    numDebe.value = "";
    numHaber.value = "";
  }

  function limpiar(todo = false){
    if (todo) {
      selTipo.value = "005";
      selBan.value = 0;
      numNum.value = "";
    }
    txtCon.value = "";
  }

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

  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    document.thisform.dtFec.value = dateToday();
    selTipo.value="005";

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

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

    // VALID TIPO
/*    $("#selTipo").blur(function (){
      consultarPolizas();
    }); */

    // VALID BANCO
/*    $("#selBan").change(function (){
      consultarPolizas();
    });  */

    // VALID NUMERO
    $("#numNum").blur(function (){
      consultarPolizas();
    });

    // VALID FECHA
/*    $("#dtFec").blur(function (){
      consultarPolizas();
    });  */

    // FOCUS NUMERO
    $("#numNum").focus(function (){
//      numNum.value = "";
      txtCon.value="";
      tblClear("tblPol");
      sumPol();

      const parametros = new FormData();
      parametros.append("action", "consultarCorrPol");
      parametros.append("selTipo", selTipo.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.corrpol === null) {
                numNum.value=1;
            } else {
              numNum.value=jsonJS.corrpol.cp_num;
            }
          }
        }
      });
    });

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

    // VALID CUENTA
    $("#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-01-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtaNom");
      txtNext = document.getElementById("numDebe");

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

      const parametros = new FormData();
      parametros.append("action", "consultarCta");
      parametros.append("txtCod", 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 = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.cuentas.cta_con != "N") {
                txtGetValue.value = "";
                alErrorFocusTimer({"msg":{"type":"error","title":"No puede usar esta cuenta","text":"La cuenta "+txtThis.value+" no es de movimiento, no la puede usar", "ok":"Aceptar", "timer":timeOutErrorSm}}, 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(){
        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

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

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      guardarPoliza();
    });

    // CLICK IMPRIMIR
    $("#btnImprimir").click(function (){
      imprimirPoliza(false);
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarPoliza(true);
    });
    
    // CLICK AGREGAR
    $("#btnAgregar").click(function () {
      if (restriccionModal()) {return};
      addRowPol(txtCta.value, txtCtaNom.value, isNullNumber(numDebe.value).toFixed(2), isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
      $("#tblPol").tableDnD();
      $("#btnAdd").focus();
    });
  });

  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    $('#modalPol').modal('toggle');
    $("#pills-00-tab").text("Agregar");
    $("#btnAgregar").show();
    $("#btnModificar").hide();
    limpiarModalPol();
  });

  // CLICK DEL
  $("body").on("click", "#btnDel", function() {
    const row = $(this).parents("tr");
    alDelete(function fn(){
      row.remove();
      sumPol();
    });
  });

  // 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 PILL
  $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
    if (!isMobile()) {
      const target = e.target.attributes.href.value;
      if ($(target+' select:visible:first').length) {
        $(target+' select:visible:first').focus();
      } else {
        $(target+' input:visible:first').focus();
      }
    }
  });

</script>