<!DOCTYPE html>
<html lang="es">
<head>
  {{> head }}
  <title>{{ title }}</title>
</head>

<body>

  <div class="d-flex" id="wrapper">
    <div id="sidebar-wrapper">
      <div class="sidebar-heading">{{ title }} </div>
      {{> navbar }}
    </div>

    <div id="page-content-wrapper">
      <nav class="navbar navbar-expand-lg navbar-light border-bottom">
        {{> topbar }}
      </nav>
      <div class="container-fluid">
        <div class="row">
          <div class="card col-md-12">
             <div class="pd-15">
                <h1 class="title">Reportes Control Diario</h1>
                <div class="my-4" style="display:inline-flex">
                  <a class="btn btn-green" href="/reportes">
                    Volver
                  </a>
                  <form class="form-inline" id="form-submit">
                    <input type="hidden" name="modulo" value="control_diario">
                    <div class="form-group mx-sm-3 mb-2">
                      <label for="dateInicio" class="sr-only">Fecha</label>
                      <input type="date" required class="form-control" name="fechaInicio" placeholder="Fecha">
                    </div>
                    <div class="form-group mx-sm-3 mb-2">
                      <label for="dateFinal" class="sr-only">Fecha</label>
                      <input type="date" required class="form-control" name="fechaFinal"  placeholder="Fecha">
                    </div>
                    <button type="submit" class="btn btn-primary mb-2">Buscar</button>
                    <button type="button" class="btn btn-success mb-2 ml-2" style="display: none;" id="btn-excel">Generar Excel</button>
                    <a href="" class="btn btn-info mb-2 ml-2" style="display: none;" id="btn-descargar" download>Descargar Archivo</a>
                  </form>
                </div>
                <div class="table-responsive">
                  <table class="table table-bordered table-hover table-style table-sm">
                    <thead id="thead">
                      <tr>
                        <th>Id</th>
                        <th>Fecha</th>
                        <th>Vehículo</th>
                        <th>Kilometraje</th>
                        <th>Usuario</th>
                      </tr>
                    </thead>
                    <tbody id="tbody">
                    </tbody>
                  </table>
              </div>
             </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- javascrips imports -->
  {{> scripts }}
</body>
<script>
  //Filtrar Reporte
  $(document).ready(function(){
    var dataReporte = new Array();

    inicializarFecha = function (){
      var now = new Date();

      var day = ("0" + now.getDate()).slice(-2);
      var month = ("0" + (now.getMonth() + 1)).slice(-2);

      var inicio = now.getFullYear()+"-"+(month)+"-01" ;
      var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

      $("input[name='fechaInicio']").val(inicio);
      $("input[name='fechaFinal']").val(today);
      
    }
    
    //inicializarFecha();



    $('form').submit(function(e){
      dataReporte = [];
      $("input[type=submit]").attr('disabled','disabled');
      $("#btn-excel").attr('style','display:none');
      $("#btn-excel").removeAttr('disabled');
      $("#btn-descargar").attr('style','display:none');
      e.preventDefault();
      fetch('/api/reportes/generate',{
        method: 'POST',
        headers:{
          'Content-Type': 'application/json'
        },
        body: JSON.stringify($("#form-submit").serializeJSON())
      })
      .then(res => res.json())
      .then(data => {
        $("input[type=submit]").removeAttr('disabled');
        $('#tbody').empty();
        if(data.data.length > 0){
          $("#btn-excel").attr('style','display:block');
          dataReporte = data.data;
        }
        data.data.forEach(element => {
          $('#tbody').append(`
            <tr>
              <td>${element.id}</td>
              <td>${element.fecha_registro} ${element.hora}</td>
              <td>${element.vehiculo.placa} - ${element.vehiculo.alias}</td>
              <td>${element.kmReporta}</td>
              <td>${element.usuario_asignado}</td>
            </tr>
          `);
        });
      })
      .catch(err => {
        console.log(err);
        dataReporte = [];
        $("input[type=submit]").removeAttr('disabled');
        $("#btn-excel").attr('style','display:none');
      });
    });

    //Exportar Excel
    $("#btn-excel").click(function(){
      $("#btn-excel").attr('disabled','disabled');
      fetch('/api/reportes/xlsx',{
          method: 'POST',
          headers:{
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(dataReporte)
        })
        .then(res => res.json())
        .then(data => {
          console.log(data); //URL XLSX
          if(data.data){
            $("#btn-excel").attr('style','display:none');
            $("#btn-descargar").attr('href',data.data);
            $("#btn-descargar").attr('style','display:block');
          } else{
            Swal.fire({
              title: 'Excel no generado',
              text: "No se pudo generar el archivo excel",
              type: 'warning',
            });
            $("#btn-excel").removeAttr('disabled');
            $("#btn-excel").attr('style','display:block');
            $("#btn-descargar").attr('style','display:none');
          }
        })
        .catch(err => {
          console.log(err);
          $("#btn-excel").removeAttr('disabled');
          $("#btn-excel").attr('style','display:block');
          $("#btn-descargar").attr('style','display:none');
        });
    });
    //
  });


</script>
</html>
