<?php include_once("../lib/control.seguridad.php"); ?>
<!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">   
  <!-- JQUERY UI -->  
  <link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />  
  
  <link href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />
  
  <style>
	  .form-text{
		  font-size:12px;	  
	  }  
	  #example{
		  font-size:10px;
	  }
	  #example2{
		  font-size:10px;
	  }	  
	  #example3{
		  font-size:10px;
	  }
   .dataTables_wrapper { font-size: 10px }	 	  
  </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-12">
            <h4>Marcajes Reloj Control</h4>
			<span class="form-text h6">Este m&oacute;dulo permite hacer consultas directas a API de relojcontrol para obtener los marcajes de Trabajador seleccionado</span>			
          </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="form-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">Fecha Inicio</div>
						</div>
						<input type="text" class="form-control" id="txtFecha_inicio" name="txtFecha_inicio" value="<?php echo date("Y-m-d") ?>" 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 T&eacute;rmino</div>
						</div>
						<input type="text" class="form-control" id="txtFecha_termino" name="txtFecha_termino" value="<?php echo date("Y-m-d") ?>" readonly>
					  </div>
					</div>						

					<div class="col-md-3">
						<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>Buscar Marcajes</button>
						<button type='button' class='btn btn-default btn-sm' id='btnLimpiar' name='btnLimpiar'>Limpiar</button>
					</div>					
				</div>	
				<div class="row">	
					<div class="col-md-6">
					  <div class="input-group mb-2 input-group-sm">
						<div class="input-group-prepend">
						  <div class="input-group-text">Nombre </div>
						</div>
						<input type="text" class="form-control" id="txtNombre" name="txtNombre" readonly >
						<input type="hidden" class="form-control" id="txtRut" name="txtRut" readonly >
					  </div>
					</div>	
					<div class="col-md-2">
						<button type="button" class="btn btn-info btn-sm" id="btnBuscar">Buscar Trabajador</button>
					</div>	
					<div class="col-md-4 d-none" id="div-turno"> 
					  <div class="input-group mb-2 input-group-sm">
						<div class="input-group-prepend">
						  <div class="input-group-text">Turno </div>
						</div>
						<input type="text" class="form-control" id="txtTurno" name="txtTurno" readonly >
						<input type="hidden" class="form-control" id="txtId_turno" name="txtId_turno" readonly >
					  </div>
					</div>	
					<div class="col-md-2 d-none" id="div-btn-turno">
						<button type="button" class="btn btn-info btn-sm" id="btnTurno">Horario Turno</button>
					</div>						
				</div>								
            </div>
            <!-- /.card-header -->
            <div class="card-body">
              <table id="example" class="table table-bordered table-striped">
                <thead>
                <tr>	
                  <th>FECHA</th>	
                  <th>HORA</th>								
                  <th>DEPARTAMENTO</th>	
                  <th>SUCURSAL</th>					  
                  <th>TIPO MARCAJE</th>					  
                </tr> 
                </thead>
              </table>
            </div>
			<div class="card-footer">
				<button type="button" class="btn btn-info btn-sm" id="btnImprimir">Imprimir</button>
			</div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  
  <?php include_once("../inc/footer.php"); ?>
  
	<div class="modal fade bd-example-modal-xl" id="modal-buscar" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true">
	  <div class="modal-dialog modal-xl">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">LISTADO DE TRABAJADORES</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-4">
				  <div class="form-group  input-group-sm">
					<input type="text" class="form-control control-text" id="txtCriterio">
					<small class="form-text text-muted">Ingrese criterio de b&uacute;sqeda (Rut / Nombre / Apellido).</small>
				  </div>				
				</div>
				<div class="col-md-4">
				  <div class="form-group">
                     <button type='button' class='btn btn-info btn-sm' id='btnFiltro' name='btnFiltro'>APLICAR FILTRO</button>
				  </div>				
				</div>				
			 </div>		  
			 <div class="row">
				<div class="col-md-12">
				  <table id="example3" class="table table-bordered table-striped">
					<thead>
					<tr>	
					  <th>RUT</th>					
					  <th>NOMBRE</th>
					  <th>DEPARTAMENTO</th>					  
					  <th>TURNO</th>				
					  <th>CARGO</th>	
					  <th></th>			  			  
					</tr>
					</thead>			
				  </table>					
				</div>
			 </div>
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cerrar</button>
		  </div>
		</div>
	  </div>
	</div>  
	
	<div id="modal-turno" class="modal" tabindex="-1" role="dialog">
	  <div class="modal-dialog modal-lg" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">INFORMACION DE TURNO</h5>
			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			  <span aria-hidden="true">&times;</span>
			</button>
		  </div>
		  <div class="modal-body">
			  <table id="example2" class="table table-bordered table-striped">
				<thead>
				<tr>		
				  <th>DIA</th>					
				  <th>HORA INICIO</th>				
				  <th>HORA TERMINO</th>	
				  <th>COLACION</th>					  
				</tr>
				</thead>			
			  </table>	
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
		  </div>
		</div>
	  </div>
	</div>  	
	
	<div class="modal" tabindex="-1" role="dialog"  id="modal-default">
	  <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="div-response"></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>
  <!-- JQUERY UI --> 
<script src="../plugins/jQueryUI/jquery-ui.js"></script>

<script src="../plugins/toastr/toastr.js"></script>
 
<script>
  $(function () { 
  
    $(document).bind("contextmenu",function(e){
      return false;
    });	   
	
    $(".modal-body-informe").height(parseInt(screen.height) -400);  		
  
	 $.datepicker.regional['es'] = {
	 closeText: 'Cerrar',
	 prevText: '< Ant',
	 nextText: 'Sig >',
	 currentText: 'Hoy',
	 monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
	 monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'],
	 dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
	 dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
	 dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
	 weekHeader: 'Sm',
	 dateFormat: 'yy/mm/dd',
	 firstDay: 1,
	 isRTL: false,
	 showMonthAfterYear: false,
	 yearSuffix: ''
	 };
	 $.datepicker.setDefaults($.datepicker.regional['es']);
	function getDate( element ) {
      var date;
      try {
        date = $.datepicker.parseDate( dateFormat, element.value );
      } catch( error ) {
        date = null;
      }

      return date;
    }
	 
	 $("#txtFecha_inicio").datepicker({
		dateFormat: "yy-mm-dd",
		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: "yy-mm-dd",
		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"
      }	  
    });
	
    $('#example2').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"
      }	  
    });	
	 
    $('#example3').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      }	  
    });
	
	$("#btnEnviar").click(function(){
		
		if( $("#txtRut").val() == null || $("#txtRut").val().length == 0 || /^\s+$/.test($("#txtRut").val()) ) {
		  toastr.warning("Debe Seleccionar Trabajador", "POWERTIME");
		  return false;
		}else{
			listarRegistro();			
		}		
	
	});	
	
	function listarRegistro(){

		$('#example').dataTable().fnClearTable();			
		var parametros = {
			"fecha_inicio" : $("#txtFecha_inicio").val(),
			"fecha_termino" : $("#txtFecha_termino").val(),
			"rut" : $("#txtRut").val()				
		};				
		$.ajax({
			type:'post',
			dataType: 'json',	
			url: "listado.inc.php",
			data : parametros,					
			success: function(dados)
			{ 
				 for (i=0;i<dados.length;i++){
				  if(dados[i].rut != 0){	
					  $('#example').dataTable().fnAddData( [						  
						dados[i].fecha, 
						dados[i].hora, 		
						dados[i].departamento, 	
						dados[i].sucursal,
						dados[i].tipomarcaje							
					  ]);
				  }
				}
			}
		});

	}
		
    $("#btnImprimir").click(function(){
        $('#modal-usuario').modal("toggle");
		$('.div-response').html('<form action="exportar.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
		'<input type="text" class="form-control" id="txtFecha_inicio" name="txtFecha_inicio" value="'+$("#txtFecha_inicio").val()+'" >'+	
		'<input type="text" class="form-control" id="txtFecha_termino" name="txtFecha_termino" value="'+$("#txtFecha_termino").val()+'" >'+	
		'<input type="text" class="form-control" id="txtRut" name="txtRut" value="'+$("#txtRut").val()+'" >'+			
		'</form>');			
		document.forms['form'].submit();
		$('#modal-default').modal('show');				
	});
	
	$('#modal-default').on('hidden.bs.modal', function () {
		$('.div-response').empty();
		$('.div-response').html('<form action="../inc/loading.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
		'</form>');			
		document.forms['form'].submit();		 
	});			
		
	$("#btnBuscar").click(function(){
		$("#modal-buscar").modal("show");		
	});
	
	$('#txtCriterio').keyup(function(e){
		if(e.keyCode == 13){
			buscarpersona();
		}
	});
	
	$("#btnFiltro").click(function(){
		buscarpersona();
	});
	
	function buscarpersona(){
		$('#example3').dataTable().fnClearTable();
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/public/buscarpersona",
			data : JSON.stringify({
				descripcion: $("#txtCriterio").val()			
			}),			
			success: function(dados)
			{
				$('#example3').dataTable().fnClearTable();
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
					  var boton = "<button type='button' class='btn btn-info btn-xs btn-editar'>Seleccionar</button>";
					  $('#example3').dataTable().fnAddData( [
						dados[i][j].rut,						  
						dados[i][j].nombre +" "+dados[i][j].apellido,	
						dados[i][j].departamento,
						dados[i][j].turno,
						dados[i][j].cargo,						
						boton +"<input type='hidden' value ='"+dados[i][j].id+"' />"
					  ]);
					}
				}
			}
		});			
	}

	$("#example3").on('click','.btn-editar', function() {
		var id = $(this).parents("tr").find("td:eq(5)").find("input").val();	
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/public/obtenerpersona",
			data : JSON.stringify({
				id: id			
			}),			
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){					
					$("#txtRut").val(dados[i].rut);
					$("#txtNombre").val(dados[i].nombre + " " +dados[i].apellido);
					$("#modal-buscar").modal("toggle");	
					listarRegistro();	
					turnopersona(dados[i].id)
					$("#div-turno").removeClass("d-none");	 
					$("#div-btn-turno").removeClass("d-none");						
				}
			}
		});			
	});	
	
	function turnopersona(idpersona){
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/public/turnopersona",
			data : JSON.stringify({
				id_persona:idpersona				
			}),			
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){						
					   $("#txtTurno").val(dados[i][j].descripcion);
					   $("#txtId_turno").val(dados[i][j].id_turno);
					}
				}
			}
		});		
	}
	
	$("#btnTurno").click(function(){
		var idTurno = $("#txtId_turno").val();
	 
		$('#example2').dataTable().fnClearTable();
 
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/public/obtenerlistadohorarioturno",
			data : JSON.stringify({
				id_turno: idTurno			
			}),				
			success: function(dados)
			{ 
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
					  $('#example2').dataTable().fnAddData( [
						dados[i][j].dia,
						formatearHora(dados[i][j].hora_inicio),	
						formatearHora(dados[i][j].hora_termino),
						formatearHora(dados[i][j].descanso)					 
					  ]);
					}
				}
			}
		});		
		
		$('#modal-turno').modal("show");		
	});

	function formatearHora(hora){		
		if(hora != null){ hora = hora.replace('-', '');  hora =  hora.substring(0, 5); return hora; } else { return hora; }	
	}

	$("#btnLimpiar").click(function(){
		limpiarFormulario();
	});
	
	function limpiarFormulario(){
		$("#txtRut").val("");
		$("#txtNombre").val("");
		$("#txtFecha_inicio").val(fechaActual());
		$("#txtFecha_termino").val(fechaActual());
		$("#div-turno").addClass("d-none");	 
		$("#div-btn-turno").addClass("d-none");	
        $('#example').dataTable().fnClearTable();		
	}
	
	function fechaActual(){
		
		var f = new Date();
		var dia = f.getDate();
		var mes = f.getMonth();
		var anio = f.getFullYear();
	    if(dia < 10 ) { dia = "0"+dia; }
	    if(mes < 10 ) { mes = "0"+mes; }
		return anio+"-"+mes+"-"+dia;
		
	}
	
});
</script>
</body>
</html>
