<?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;
  }
  .dataTables_wrapper { font-size: 10px; } 
  .badge-danger { 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>Importar Hora Extra</h4>
          </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">Autoriza</div>
				</div>
				<input type="text" class="form-control control-text" id="txtNombre_autoriza" value="<?php echo $nombreAuroriza ?>" readonly>
				<input type="hidden" class="form-control control-text" id="txtId_autoriza" value="<?php echo $id_autoriza ?>">
			  </div>
			</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-body">						  			  
				  <label>Listado de Trabajadores</label>
				  <table id="example" class="table table-bordered table-striped">
					<thead>
					<tr>	
					  <th>RUT</th>		
					  <th>NOMBRE</th>					  
					  <th>FECHA</th>
					  <th>CANTIDAD</th>								  
					  <th></th>						  
					</tr>
					</thead>			
				  </table>					  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">					
					<input type="hidden" class="form-control control-text" id="txtCargo" value="<?php echo $_SESSION['LOGIN']['CARGOUSUARIO'] ?>">
					<button type='button' class='btn btn-info btn-sm' id='btnAdjuntar' name='btnAdjuntar'>Adjuntar Planilla</button>
					<button type='button' class='btn btn-default btn-sm' id='btnLimpiar' name='btnLimpiar'>Limpiar Formulario</button>
					<button type='button' class='btn btn-info btn-sm' id='btnIngresar' name='btnIngresar' disabled>Procesar Planilla</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>
          </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>
<!-- ./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 () {
	   
     $('#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"
		  } 	
     });		 
	 $("#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();
			
			var fd = new FormData();
			var files = $('#file')[0].files[0];
			fd.append('file',files);
			$.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>";
					  $('#example').dataTable().fnAddData( [
						response[i].rut,
						response[i].nombre +"<br /> "+ response[i].mensaje,					
						response[i].fecha,
						response[i].cantidad,					
						boton + "<input type='hidden' value ='"+response[i].id+"' /> ", 
					  ]);
					}
				  }
			});
			if($('#example').dataTable().fnGetData().length == 0){
				$("#btnIngresar").attr("disabled", false);
			}
			
			$('#file').val(null);
			$('#modal-default').modal('toggle');				
		}
			
	});
	
	$("#example").on('click','.btn-eliminar', function() {			
		$('#example').dataTable().fnDeleteRow($(this).closest("tr"));
	});		
	
	$("#btnIngresar").click(function(){
		if($('#example').dataTable().fnGetData().length == 0){
			toastr.warning("Debe Seleccionar Planilla", "POWERTIME");
			return false;
		}else{
			
        $('#modal-confirma').modal("toggle");		
		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(4)").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/ingresarhoraextra",
				data : JSON.stringify({
					fecha:$(this).find("td:eq(2)").html(),
					cantidad:$(this).find("td:eq(3)").html(),		
					id_persona:id,	
					id_autoriza:$("#txtId_autoriza").val(),	
					observacion:"Hora Extra Masiva"				
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){ 
						contador++; i++;
						if(i == cantidad_trabajador) {
							toastr.success("Se han procesado : ("+contador+") Solicitudes de Horas Extras a Trabajadores", "POWERTIME");
							limpiarFormulario();							
						}							
					}			
				}
			})		 			
		}); 			
			
		}
	});
	
	$("#btnLimpiar").click(function(){
		limpiarFormulario();
	});
	
	function limpiarFormulario(){
		$('#example').dataTable().fnClearTable();
		$("#btnIngresar").attr("disabled", true);		
	}
		
	
});	 	
  
</script>

</body>
</html>
