<?php include_once("../lib/control.seguridad.php"); ?>
<?php

	$fecha_inicio = date('Y-m-d', mktime(0,0,0, date('m'), 1, date('Y')));
	$fecha_termino = date('Y-m-d', mktime(0,0,0, date('m'), date("d", mktime(0,0,0, date('m')+1, 0, date('Y'))), date('Y'))); 

	$boton = "<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>INGRESAR</button>";
	
	$fecha_inicio = date("Y-m-d");
	$fecha_termino = date("Y-m-d");
	$hora_inicio = "08:00";
	$hora_termino = "08:00";
	$id_autoriza = $_SESSION['LOGIN']['CODIGO'];
	$nombreAuroriza = $_SESSION['LOGIN']['NOMBRE'];	

?>
<!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 href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />
  
  <!-- JQUERY DATEPICKER -->  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">
  <!-- JQUERY UI -->  
  <link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />
  
  <style>
  #example{
	  font-size:10px;
  }
  #example2{
	  font-size:10px;
  }  
  .content-header h4{ 
	  font-size: 20px
  }  
  .dataTables_wrapper { font-size: 10px; } 
  .badge-danger, .badge-info { 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-8">
            <h4>Justificaci&oacute;n de Faltas</h4>
			<input type="hidden" class="form-control control-text" id="txtId_autoriza" value="<?php echo $id_autoriza ?>">
          </div>		  
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content" id="app">
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-12">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header">						  			  
					<button type='button' class='btn btn-info btn-sm' id='btnAdjuntar' name='btnAdjuntar'>Adjuntar Planilla</button>
					<button type='button' class='btn btn-info btn-sm' id='btnIngresar' name='btnIngresar' disabled>Procesar Planilla</button> 
					<button type='button' class='btn btn-default btn-sm' id='btnLimpiar' name='btnLimpiar'>Limpiar Formulario</button>						
					<a type='button' href="descargar.php" class='btn btn-info btn-sm float-right' id='btnDescargar' name='btnDescargar'>Descargar Plantilla Ejemplo</a>							
				</div>			
				<div class="card-body">						  			  
					<div class="row">
						<div class="col-md-12">
						  <p>Faltas a Procesar :</p>
						  <table id="example" class="table table-bordered table-striped">
							<thead>
							<tr>	
							  <th>RUT</th>		
							  <th>NOMBRE</th>					  
							  <th>FECHA</th>							  
							  <th></th>						  
							</tr>
							</thead>			
						  </table>	
						</div>
						<div class="col-md-6">
						  <p>Faltas Justificadas :</p>
						  <table id="example2" class="table table-bordered table-striped">
							<thead>
							<tr>	
							  <th>RUT</th>		
							  <th>NOMBRE</th>					  
							  <th>FECHA</th>	
							  <th>OBSERVACION</th>								  
							  <th></th>						  
							</tr>
							</thead>			
						  </table>							
						</div>
					</div>
                   <div class="div-response"></div>	
				</div>
				<!-- /.card-body -->
				<div class="card-footer">	
				  <div class="row">
					<div class="col-md-3">
					  <div class="input-group mb-2 input-group-sm">
						<div class="input-group-prepend">
						  <div class="input-group-text">Cantidad</div>
						</div>
						<input type="text" class="form-control" id="txtCantidad" value="0" 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">Justificado</div>
						</div>
						<input type="text" class="form-control" id="txtJustificado" value="0" readonly>
					  </div>
					</div>											
				  </div>				
				</div>
            </div>
          </div>
        </div>
        <!-- /.row -->
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  
  <?php include_once("../inc/footer.php"); ?>
  
	<div class="modal" tabindex="-1" role="dialog"  id="modal-default">
	  <div class="modal-dialog" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">Planilla de Hora Extra</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="custom-file">
				<input type="file" class="custom-file-input"  name='file' id='file' >
				<label class="custom-file-label" for="customFile"><i class="nav-icon fas fa-book"></i>  Buscar Documento</label>
			  </div>		  
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-info btn-sm" id="btnProcesar" name="btnProcesar">Procesar Planilla</button>		  
			<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button>
		  </div>
		</div>
	  </div>
	</div>  
  
	<div class="modal" tabindex="-1" role="dialog"  id="modal-default2">
	  <div class="modal-dialog modal-xl" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">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-secondary btn-sm" data-dismiss="modal">Close</button>
		  </div>
		</div>
	  </div>
	</div>   
  
  
	<div class="modal" tabindex="-1" role="dialog"  id="modal-eliminar">
	  <div class="modal-dialog" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">POWERTIME</h5>
			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			  <span aria-hidden="true">&times;</span>
			</button>
		  </div>
		  <div class="modal-body text-center">
			<p>&iquest; Desea Excluir a trabajador de listado ?</p>
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-info btn-sm" id="btnEliminar">Eliminar</button>		  
			<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</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="../plugins/toastr/toastr.js"></script>

  <!-- JQUERY UI --> 
<script src="../plugins/jQueryUI/jquery-ui.js"></script>
  <!-- JQUERY DATEPICKER -->  
<script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>

<script>

  $(function () {
  
     $(".modal-body-informe").height(parseInt(screen.height) -400);  
	
     $('#example').DataTable({
		  "paging": true,
		  "lengthChange": false,
		  "searching": false,
		  "ordering": true,
		  "info": false,
		  "autoWidth": false,
		  "pageLength": 7,
		  "language": {
			"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
		  } 	
     });	

     $('#example2').DataTable({
		  "paging": true,
		  "lengthChange": false,
		  "searching": false,
		  "ordering": true,
		  "info": false,
		  "autoWidth": false,
		  "pageLength": 7,
		  "language": {
			"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
		  } 	
     });	
	 
	 $("#btnAdjuntar").click(function(){
		$('#modal-default').modal('show');
     });	

	$("#btnProcesar").click(function(){
		
		if($('#file')[0].files.length == 0){
			toastr.warning("Debe Seleccionar Planilla Excel", "POWERTIME");
		}else{
			$('#example').dataTable().fnClearTable();
			$("#txtCantidad").val(0);
			$("#txtJustificado").val(0);
			
			var fd = new FormData();
			var files = $('#file')[0].files[0];
			fd.append('file',files);
			
			var cantidad = 0;
			var justificado = 0;			
			$.ajax({
				  url: 'importar.php',
				  type: 'post',
				  data: fd,
				  dataType: 'json',
				  contentType: false,  
				  processData: false,
				  success: function(response){
					for(var i=0;response.length>i;i++){
					  var boton = "<button type='button' class='btn btn-info btn-xs btn-eliminar'>Eliminar</button>";
					  var boton2 ="";			  
					  if(response[i].codigo == 1) { boton2 = "<button type='button' class='btn btn-info btn-xs btn-justifica'>Ver Documento Falta</button>"; }
					  if(response[i].codigo == 2) { boton2 = "<button type='button' class='btn btn-info btn-xs btn-justifica'>Ver Justificaci&oacute;n</button>"; }
					  if(response[i].codigo == 3) { boton2 = "<button type='button' class='btn btn-info btn-xs btn-justifica'>Ver Permiso</button>"; }					  
					  
					  if(response[i].cantidad == 0){
						  $('#example').dataTable().fnAddData( [
							response[i].rut,
							response[i].nombre,		
							response[i].fecha,				
							boton  + "<input type='hidden' value ='"+response[i].id+"' /> ", 
						  ]);						  
					  }else{
						  $('#example2').dataTable().fnAddData( [
							response[i].rut + "<input type='hidden' value ='"+response[i].codigo+"' /> ", 
							response[i].nombre, 
						    response[i].fecha,								
							response[i].mensaje,						
							boton2 + "<input type='hidden' value ='"+response[i].id+"' /> ", 
						  ]);							  
					  }

					  
					  if(response[i].cantidad == 0) { cantidad++; } else { justificado++; }
					  
					}
					$("#txtCantidad").val(cantidad);
					$("#txtJustificado").val(justificado);
				  }
			});
			if($('#example').dataTable().fnGetData().length == 0){
				$("#btnIngresar").attr("disabled", false);
			}
			
			$('#file').val(null);
			$('#modal-default').modal('toggle');				
		}
			
	});
	
	$("#example2").on('click','.btn-justifica', function() {
		var fecha = $(this).parents("tr").find("td:eq(2)").html();
		var id = $(this).parents("tr").find("td:eq(4)").find("input").val();

		alert($(this).parents("tr").find("td:eq(0)").find("input").val());

		if(parseInt($(this).parents("tr").find("td:eq(0)").find("input").val()) == 1){
			$('.div-response').html('<form action="falta.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
			'<input type="text" class="form-control" id="txtId" name="txtId" value="'+id+'" >'+
			'<input type="text" class="form-control" id="txtFecha" name="txtFecha" value="'+fecha+'" >'+		
			'</form>');				
		}
		else if(parseInt($(this).parents("tr").find("td:eq(0)").find("input").val()) == 2){
			$('.div-response').html('<form action="justificacion.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
			'<input type="text" class="form-control" id="txtId" name="txtId" value="'+id+'" >'+
			'<input type="text" class="form-control" id="txtFecha" name="txtFecha" value="'+fecha+'" >'+		
			'</form>');						
		}
		else{
			$('.div-response').html('<form action="permiso.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
			'<input type="text" class="form-control" id="txtId" name="txtId" value="'+id+'" >'+
			'<input type="text" class="form-control" id="txtFecha" name="txtFecha" value="'+fecha+'" >'+		
			'</form>');									
		}
		

		document.forms['form'].submit();
		$('#modal-default2').modal('show');	
	});		
	
	var idEliminar;
	$("#example").on('click','.btn-eliminar', function() {	
		idEliminar = $(this).closest("tr");
		$('#modal-eliminar').modal("show");
	});

    $("#btnEliminar").click(function(){
		$('#example').dataTable().fnDeleteRow(idEliminar);
		$('#modal-eliminar').modal("toggle");
		$("#txtCantidad").val($('#example').dataTable().fnGetData().length);		
	});	
	
 
	$("#btnIngresar").click(function(){
		if($('#example').dataTable().fnGetData().length == 0){
			toastr.warning("Debe Seleccionar Planilla", "POWERTIME");
			return false;
		}else{
				
		var contador = 0;
        var cantidad_trabajador = parseInt($('#example').dataTable().fnGetData().length);
		var i= 0;
		jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
			var id = $(this).find("td:eq(3)").find("input").val();
			$.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/ingresarfalta",
				data : JSON.stringify({
					fecha:$(this).find("td:eq(2)").html(),
					id_persona:id,	
					id_autoriza:$("#txtId_autoriza").val()			
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){ 
						contador++; i++;
						if(i == cantidad_trabajador) {
							toastr.success("Se han procesado : ("+contador+") Faltas a Trabajadores", "POWERTIME");	
							limpiarFormulario();
						}							
					}			
				}
			})		 			
		}); 			
			
		}
	});
	
	$("#btnLimpiar").click(function(){
		limpiarFormulario();
	});
	
	function limpiarFormulario(){
		$('#example').dataTable().fnClearTable();
		$('#example2').dataTable().fnClearTable();		
		$("#btnIngresar").attr("disabled", true);
		$("#txtCantidad").val(0);
		$("#txtJustificado").val(0);		
	}
		
	
});	 	
  
</script>

</body>
</html>
