<?php include_once("../lib/control.seguridad.php");?>
<?php
$fecha_inicio = date('d-m-Y', mktime(0,0,0, date('m'), 1, date('Y')));
$fecha_termino = date('d-m-Y', mktime(0,0,0, date('m'), date("d", mktime(0,0,0, date('m')+1, 0, date('Y'))), date('Y'))); 
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>POWERTIME</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="../plugins/fontawesome-free/css/all.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="../dist/css/adminlte.min.css">
  <!-- DataTables -->
  <link rel="stylesheet" href="../plugins/datatables-bs4/css/dataTables.bootstrap4.css">   
  <link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />  
  <link href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />   
  <style>
  #example{
	  font-size:11px;
  }
  </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">

  <?php include_once("../inc/header.php"); ?>

  <?php include_once("../inc/menu.php"); ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h4>Listado de Permisos Jur&iacute;dico</h4>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">Listado de Permisos Jur&iacute;dico</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content" id="app">
      <div class="row">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <div class="row">
                <div class="col-md-12">
                  <h3 class="card-title">Listado de Permisos </h3>
                  <button type="button" class="btn btn-outline-info btn-sm float-right ml-1" id="btnExportarPDF"><i class="fas fa-file-pdf"></i> Exportar a PDF</button>
                  <button type="button" class="btn btn-info float-right btn-sm float-right ml-1" id="btnGenerarReporte"><i class="fas fa-file-excel"></i> Exportar a Excel</button>
                </div>
              </div>

              <div class="row mt-4">
                <div class="col-md-3">
                  <div class="input-group mb-2 input-group-sm">
                  <div class="input-group-prepend">
                    <div class="input-group-text">Estado de Firma</div>
                  </div>
                    <select class="form-control" id="idacepta" id="idacepta">
                      <option value="99">TODOS </option>
                      <option value="0">PENDIENTE </option>
                      <option value="1">EN PROCESO DE FIRMA </option>
                      <option value="2">FIRMADO POR TODOS </option>
                      <option value="3">RECHAZADO</option>
                    </select>
                  </div>
                </div>


                <div class="col-md-4">
                  <div class="input-group mb-2 input-group-sm">
                  <div class="input-group-prepend">
                    <div class="input-group-text">Centro</div>
                  </div>
                  <select class="form-control" id="txtDepartamento">
                    <option value="0">Seleccione...</option>
                  </select>
                  </div>
                </div>	                              

                <div class="col-md-3">
                  <div class="input-group mb-2 input-group-sm">
                  <div class="input-group-prepend">
                    <div class="input-group-text">Fecha Inicio</div>
                  </div>
                  <input type="text" class="form-control" id="txtFecha_inicio" value="<?php echo $fecha_inicio ?>" readonly >
                  </div>
                </div>

                <div class="col-md-3">
                  <div class="input-group mb-2 input-group-sm">
                  <div class="input-group-prepend">
                    <div class="input-group-text">Fecha Termino</div>
                  </div>
                  <input type="text" class="form-control" id="txtFecha_termino" value="<?php echo $fecha_termino ?>" readonly >
                  </div>
                </div>
                <div class="col-md-2">
                  <button type="button" class="btn btn-info mb-2 btn-sm btn-block" id="btnBuscar">Buscar</button>
                </div>	                
              </div>

            </div>
            <!-- /.card-header -->
            <div class="card-body">

              <div class="row">
                <div class="col-md-12">
                  <table id="example" class="table table-bordered table-striped">
                  <thead>
                  <tr>		
                    <th>C&oacute;DIGO ACEPTA</th>	
                    <th>N° FOLIO</th>	
                    <th>TIPO PERMISO</th>			
                    <th>FECHA INICIO</th>	
                    <th>FECHA T&Eacute;RMINO</th>	
                    <th>DIAS H&Aacute;BILES</th>			
                    <th>RUT</th>	
                    <th>NOMBRE</th>		
                    <th>ESTADO FIRMA ELECTR&Oacute;NICA</th>	
                    <th></th>		
                    <th></th>		                  					  				  						  		  
                  </tr> 
                  </thead>
                  <tbody></tbody>
                  </table>
                  <div class="div-response"></div>
                </div>
              </div>

				    </div>
			<!-- /.card-body -->
			</div>
			<!-- /.card -->
		</div>
		<!-- /.col -->
	</div>
	<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->

<?php include_once("../inc/footer.php"); ?>

 

 <!-- Modal -->
<div class="modal fade" id="modalvisor" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"><i class="fas fa-file-pdf"></i> Visor de Documentos</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body modal-body-informe">
        <iframe name="iframe3" width="100%" height="100%" src="../inc/loading.php"></iframe>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"><i class="fas fa-backspace"></i> Cerrar</button>
      </div>
    </div>
  </div>
</div>


<!-- Modal -->
<div class="modal fade" id="modalLoading" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Mensaje de Sistema</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-12 text-center">
            <img src="../img/loading.gif" style="max-width:250px;" />
          </div>
        </div>
      </div>
      <div class="modal-footer">
      <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"><i class="fas fa-backspace"></i> Cerrar</button>
      </div>
    </div>
  </div>
</div>


<!-- Modal -->
<div class="modal fade" id="modalConfirmar" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Mensaje de Sistema</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-12 text-center">
              ¿Desea Marcar Permiso como Revisado?
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-info" id="btnRevisado"><i class="far fa-thumbs-up"></i> Marcar Revisado </button>
        <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"><i class="fas fa-backspace"></i> Cerrar</button>
      </div>
    </div>
  </div>
</div>

</div>
<!-- ./wrapper -->

<!-- jQuery -->
<script src="../plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="../dist/js/adminlte.min.js"></script>
<!-- DataTables -->
<script src="../plugins/datatables/jquery.dataTables.js"></script>
<script src="../plugins/datatables-bs4/js/dataTables.bootstrap4.js"></script>
<script src="https://unpkg.com/pdfobject@2.2.4/pdfobject.min.js"></script>
<script src="../plugins/jQueryUI/jquery-ui.js"></script>
<script src="../plugins/toastr/toastr.js"></script>

<script type="text/javascript">
    $(document).ready(function () {


      function departamento(){
        $('#txtDepartamento').empty();	
        $.ajax({
          type:'POST',
          contentType: 'application/json',
          dataType: "json",
                crossDomain: true,
          headers: {
            'Content-Type': 'application/json'
          },
          url: "http://200.24.13.60/~program1/power-time-api/public/listargrupo",
          success: function(dados)
          {
            for (i=0;i<dados.length;i++){
              for (j=0;j<dados[i].length;j++){
                $('#txtDepartamento').append($('<option>', {
                  value: dados[i][j].id,
                  text : dados[i][j].descripcion
                }));
              }
            }
          }
        });			
      }	 
      departamento();     

      $("#txtFecha_inicio").datepicker({
        dateFormat: "dd-mm-yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "1900:2100",
        onSelect: function(dateText, inst) {
        var lockDate = new Date($('#txtFecha_inicio').datepicker('getDate'));
        $('#txtFecha_termino').datepicker('option', 'minDate', lockDate);
        }		
      }) 
      
      $("#txtFecha_termino").datepicker({
        dateFormat: "dd-mm-yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "1900:2100",
        minDate: $("#txtFecha_inicio").val() 
      })       

        $('#example').DataTable({
            "paging": true,
            "lengthChange": false,
            "searching": true,
            "ordering": false,
            "info": true,
            "autoWidth": false,
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
            } 	  
        });  

        $(".modal-body-informe").height(parseInt(screen.height) -400);  


        function invertirCadena(numeros) { 
          return numeros.split('-').reverse().join('-')
        }	

        $("#btnExportarPDF").click(function(){
            PDFObject.embed("informepdf.php?fechainicio="+invertirCadena($("#txtFecha_inicio").val())+"&fechatermino="+invertirCadena($("#txtFecha_termino").val())+"&idacepta="+document.getElementById("idacepta").value+"&departamento="+document.getElementById("txtDepartamento").value, ".modal-body-informe"); 
            $("#modalvisor").modal("show");
        });       


        document.getElementById("btnGenerarReporte").onclick = async() =>{

        $('.div-response').html('<form action="excel.php" target="this" name="form" method="post" style="display:none;">'+
        '<input type="text" class="form-control" id="fechainicio" name="fechainicio" value="'+ invertirCadena($("#txtFecha_inicio").val()) +'" >'+
        '<input type="text" class="form-control" id="fechatermino" name="fechatermino" value="'+ invertirCadena($("#txtFecha_termino").val()) +'" >'+
        '<input type="text" class="form-control" id="idacepta" name="idacepta" value="'+ document.getElementById("idacepta").value +'" >'+
        '<input type="text" class="form-control" id="departamento" name="departamento" value="'+ document.getElementById("txtDepartamento").value +'" >'+
        '</form>');

        document.forms['form'].submit();

  
}        

        const listado = async() =>{

            var formData = new FormData();
        
            formData.append('fechainicio', invertirCadena($("#txtFecha_inicio").val()));
            formData.append('fechatermino', invertirCadena($("#txtFecha_termino").val()));
            formData.append('idacepta', document.getElementById("idacepta").value);
            formData.append('departamento', document.getElementById("txtDepartamento").value);

            const resultado = await fetch('sincronizacion.php',{
                method: "POST",
                body: formData, 
            });
            const data = await resultado.json();
            $('#example').dataTable().fnClearTable();
            const map = await data.map((res) =>{

              var boton  = "<button type='button' class='btn btn-info btn-xs btn-ver-permiso'><i class='far fa-file-pdf'></i> Ver Permiso</button>";
					    var boton2  = "<button type='button' class='btn btn-primary btn-xs btn-permiso-digital'><i class='far fa-file-pdf'></i> Ver Permiso Digital</button>";
              var boton3  = "<button type='button' class='btn btn-info btn-xs btn-revisado'><i class='far fa-thumbs-up'></i> Marcar Revisado</button>";

              if(res.revisado == 1){
                boton3 = "<span class='badge badge-success' style='font-size:13px;'><i class='far fa-thumbs-up'></i> Permiso Revisado</span>";
              }

                $('#example').dataTable().fnAddData( [ 
                    res.pdfacepta,
                    res.idpermiso,
                    res.tipo,
                    invertirCadena(res.fechainicio),
                    invertirCadena(res.fechatermino),
                    res.cantidad,
                    res.rut,
                    res.nombre,
                    res.estado,
                    boton2,
                    boton3
                ]);        

            }) 


        }
        listado();


        $("#btnBuscar").click(function(){
          listado();
        });

        $("#example").on('click','.btn-ver-permiso', function() {
            $('.div-response').html('<form action="../formatopermiso/permiso.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
          '<input type="text" class="form-control" id="txtId_permiso" name="txtId_permiso" value="'+$(this).parents("tr").find("td:eq(1)").html()+'" >'+
          '</form>');			
          document.forms['form'].submit();
          $('#modalvisor').modal('show');		
        });	
        
        $("#example").on('click','.btn-permiso-digital', function() {
        
          $('.div-response').html('<form action="verdocumento.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
          '<input type="text" class="form-control" id="codigo" name="codigo" value="'+$(this).parents("tr").find("td:eq(0)").html()+'" >'+
          '</form>');			
          document.forms['form'].submit();
          $('#modalvisor').modal('show');		
        });	

        let idpermiso = 0;
        $("#example").on('click','.btn-revisado', function() {
        
          idpermiso = $(this).parents("tr").find("td:eq(1)").html();
          $('#modalConfirmar').modal('show');		

        });	

        document.getElementById("btnRevisado").onclick = async() =>{
           $.ajax({
                type:'POST',
                contentType: 'application/json',
                dataType: "json",
                crossDomain: true,
                headers: {
                  'Content-Type': 'application/json'
                },
                url: "http://200.24.13.60/~program1/power-time-api/public/marcarpermisorevisado",
                data : JSON.stringify({
                  id:idpermiso,		
                }),
                success: function(data, textStatus, xhr) {
                  if(parseInt(xhr.status) == 200){
                    toastr.warning(data.error, "POWERTIME");
                  }					
                  if(parseInt(xhr.status) == 201){
                    toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
                    $('#modalConfirmar').modal('toggle');	
                  }
                }
            })          
        }
    
    });    
</script>