<?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'))); 

	
	$id = "";
	$rut = "";
	$pasaporte = "";		
	$nombre = "";
	$apellido = "";	
	$telefono = "";	
	$email = "";	
	$marca = "";	
	$hide = "d-none";
	
    if($_POST){
        
		$hide = "";
		$url = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpersona';
		$ch = curl_init($url); //create a new cURL resource
		$payload = json_encode(array('id' => $_POST["txtId"]));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);//attach encoded JSON string to the POST fields
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
		$result = curl_exec($ch); //execute the POST request
        $array = json_decode($result);

		$id = $array[0]->id;
		$rut = $array[0]->rut;
		$pasaporte = $array[0]->pasaporte;		
		$nombre = $array[0]->nombre;	
		$apellido = $array[0]->apellido;			
		$telefono = $array[0]->telefono;
		$email = $array[0]->email;		
		$marca = $array[0]->marca;		
		curl_close($ch); 

	}

?>
<!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">
 
  <link href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />
  <!-- DataTables -->
  <link rel="stylesheet" href="../plugins/datatables-bs4/css/dataTables.bootstrap4.css">   
  <!-- JQUERY UI -->  
  <link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />  
  <style>
	  .content-header h4{ 
		  font-size: 20px
	  }  
      .badge-success{
		  font-size:11px;		  
	  }	 	  
	  #example{
		  font-size:11px;
	  }
	  #example2{
		  font-size:11px;
	  } 
	  #example3{
		  font-size:11px;
	  }
	  #example4{
		  font-size:11px;
	  }	  
	  }
	  #example5{
		  font-size:11px;
	  }	  	  
      label{
		  font-size:11px;		  
	  } 	  
      .dataTables_wrapper { font-size: 10px }

	.nav-item .nav-link{
		padding:5px 10px 5px 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">
          <div class="col-sm-6">
            <h4>Informaci&oacute;n de Usuario</h4>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content" id="app">
      <div class="container-fluid">
        <div class="row">
          <!-- left column -->
          <div class="col-md-6">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header d-flex p-0">
				</div>
				<div class="card-body">
					<div class="row">
						<div class="col-md-6">
						  <div class="form-group input-group-sm">
							<label>Rut :</label>
							<input type="text" class="form-control control-rut" id="txtRut" value="<?php echo $rut ?>" maxlength="13" readonly>
					        <input type="hidden" class="form-control control-text" id="txtId" value="<?php echo $id ?>" readonly>									
						  </div>						
						</div>
						<div class="col-md-6">
						  <div class="form-group input-group-sm">
							<label>Pasaporte :</label>
							<input type="text" class="form-control control-number" id="txtPasaporte" value="<?php echo $pasaporte ?>" maxlength="20" readonly>
						  </div>						
						</div>						
						<div class="col-md-12">
						  <div class="form-group input-group-sm">
							<label>Nombres:</label>
							<input type="text" class="form-control control-text txtToUpper" id="txtNombre" value="<?php echo $nombre ." ".$apellido ?>" maxlength="50" readonly>
						  </div>							
						</div>	 
						<div class="col-md-12">
						  <div class="form-group input-group-sm">
							<label>Marcaje Laboral :</label>
							<select class="form-control" id="txtMarca" disabled>
								<option value="1">Si, marca turno laboral</option>
								<option value="2">Art&iacute;culo 22, C&oacute;digo del trabajo</option>						
							</select>
						  </div>							
						</div>	 						
						<div class="col-md-6">
						  <div class="form-group input-group-sm">
							<label>Tel&eacute;fono :</label>
							<input type="text" class="form-control control-number" id="txtTelefono" value="<?php echo $telefono ?>" readonly >
						  </div>					
						</div>
						<div class="col-md-6">
						  <div class="form-group input-group-sm">
							<label>E-mail:</label>
							<input type="text" class="form-control control-text" id="txtEmail" value="<?php echo $email ?>" readonly>
						  </div>							
						</div>						
					</div>									  					  					  				
			  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">					  
				</div>
            </div>
          </div>
          <div class="col-md-6">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header d-flex p-0">			
				</div>
				<div class="card-body">			  					
				  <input class="form-control" type="hidden" id ="txtTurno" value="0" />					  
				  <table id="example" class="table table-bordered table-striped">
					<thead>
					<tr>			
					  <th>TURNO</th>				
					  <th></th>					  
					</tr>
					</thead>			
				  </table>					  	
				  <table id="example2" class="table table-bordered table-striped">
					<thead>
					<tr>			
					  <th>Centro</th>		
					  <th></th>							  
					</tr>
					</thead>			
				  </table>							  			  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">		  			
				</div>
            </div>
          </div>
        </div>
		
        <div class="row">
          <!-- left column -->
          <div class="col-md-12">
            <!-- Horizontal Form -->
            <div class="card">
			    <div class="card-header">
					 <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">Fecha Inicio</div>
							</div>
							<input type="text" class="form-control" id="txtFecha_inicio_permiso" 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 T&eacute;rmino</div>
							</div>
							<input type="text" class="form-control" id="txtFecha_termino_permiso" value="<?php echo $fecha_termino ?>" readonly >
						  </div>
						</div>	
						<div class="col-md-1">
						  <button type="button" class="btn btn-info mb-2 btn-sm" id="btnBuscar_permiso">Buscar</button>
						</div>				
					 </div>					
				</div>
				<div class="card-body">
					<ul class="nav nav-tabs ml-auto p-2  justify-content-center" id="menu-turno">
					  <li class="nav-item">
						<a class="nav-link nav-marcaje active" href="#marcaje" data-toggle="tab">Marcajes</a>
					  </li>
					  <li class="nav-item">
						<a class="nav-link nav-permiso" href="#permiso" data-toggle="tab">Permisos</a>
					  </li>				  
					</ul>					
					<div class="tab-content p-0">
					  <div class="tab-pane active" id="marcaje">
						 <div class="row">
							<div class="col-md-12">				
								  <table id="example5" class="table table-bordered table-striped">
									<thead>			
									<tr>			
									  <th>D&Iacute;A</th>	
									  <th>ENTRADA</th>	
									  <th>SALIDA</th>	
									  <th>ENT. ANT</th>	
									  <th>ATRASO</th>		
									  <th>SAL. ANT.</th>	
									  <th>SAL. DESP.</th>	
									  <th>HORAS. PERM.</th>						  
									  <th>HE. AUT.</th>		
									  <th>OBSERVACI&Oacute;N</th>										  
									</tr> 
									</thead>			
								  </table>
							</div>
						 </div>				 	 			  
					  </div>
					  <div class="tab-pane" id="permiso">
						 <div class="row">
							<div class="col-md-12">
							  <table id="example4" class="table table-bordered table-striped">
								<thead>
								<tr>	
								  <th>FECHA INICIO</th>	
								  <th>FECHA T&Eacute;RMINO</th>						  
								  <th>TIPO DE PERMISO</th>
								  <th>MOTIVO</th>					  				  
								</tr>
								</thead>			
							  </table>					
							</div>
						 </div>					  
					  </div>  					  
					</div>			
											  					  					  							  
				</div>
            </div>
          </div>

        </div>		
		
        <!-- /.row -->
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  
  <?php include_once("../inc/footer.php"); ?>

	<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="example3" class="table table-bordered table-striped">
				<thead>
				<tr>		
				  <th>D&Iacute;A</th>					
				  <th>HORA INICIO</th>				
				  <th>HORA T&Eacute;RMINO</th>	
				  <th>COLACI&Oacute;N</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>
<!-- ./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>

<script src="../plugins/toastr/toastr.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>

  $(function () {
	  
	 $.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_permiso").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		onSelect: function(dateText, inst) {
		var lockDate = new Date($('#txtFecha_inicio_permiso').datepicker('getDate'));
		$('#txtFecha_termino_permiso').datepicker('option', 'minDate', lockDate);
		}		
	 }) 
	
	 $("#txtFecha_termino_permiso").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		minDate: $("#txtFecha_inicio_permiso").val() 
	 }) 	
	  
    $('#example').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"
      } 		  
    });	  
		
    $('#example2').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"
      } 		  
    });		
		
    $('#example3').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": false,
      "info": true,
      "autoWidth": false,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      } 		  
    });
		
    $('#example4').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": true,
      "ordering": true,
      "info": true,
      "autoWidth": false,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      } 		  
    });	
		
    $('#example5').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"
      } 		  
    });		
	$("#txtMarca").val(<?php echo $marca ?>);
	
    $(document).bind("contextmenu",function(e){
      return false;
    });	  
	  	
	listarRegistro();
	function listarRegistro(){

		$('#example').dataTable().fnClearTable();

		$.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/turnopersona",
			data : JSON.stringify({
				id_persona:$("#txtId").val()					
			}),			
			success: function(dados)
			{
				 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'>Ver Informaci&oacute;n</button>";
					  $('#example').dataTable().fnAddData( [
						dados[i][j].descripcion,	
						boton  + "<input type='hidden' value ='"+dados[i][j].id_turno+"' />"
					  ]);
					}
				}
			}
		});

	}
	
 	$("#example").on('click','.btn-editar', function() {
		var idTurno = $(this).parents("tr").find("td:eq(1)").find("input").val();
		
		$('#example3').dataTable().fnClearTable();

		$.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/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++){
 
					  $('#example3').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; }	
	}		
		
	listarRegistroDep();
	function listarRegistroDep(){

		$('#example2').dataTable().fnClearTable();

		$.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/departamentopersona",
			data : JSON.stringify({
				id_persona:$("#txtId").val()					
			}),			
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){		

                      var mensaje = "";
					  if(dados[i][j].primario == 1) { mensaje = "<span class='badge badge-success'>Primario</span>"; }
					
					  var boton = "<button type='button' class='btn btn-info btn-xs btn-editar'>Ver Informaci&oacute;n </button>";
					  $('#example2').dataTable().fnAddData( [
						dados[i][j].departamento,
						mensaje
					  ]);
					}
				}
			}
		});

	}	
	
	$("#btnBuscar_permiso").click(function(){
		listarPermisoTrabajador();
		listarRegistroMarcaje();
	});
	
	listarPermisoTrabajador();
	function listarPermisoTrabajador(){

		$('#example4').dataTable().fnClearTable();

		$.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/listarpermisostrabajadorgeneral",	
			data : JSON.stringify({
				fecha_inicio: $("#txtFecha_inicio_permiso").val(),
				fecha_termino: $("#txtFecha_termino_permiso").val(),
				id_persona: $("#txtId").val(),		
			}),				
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){						
					  $('#example4').dataTable().fnAddData( [
						dados[i][j].fecha_inicio,	
						dados[i][j].fecha_termino,
						dados[i][j].tipo,	
						dados[i][j].observacion						
					  ]);
					}
				}
			}
		});

	}

	listarRegistroMarcaje();
	function listarRegistroMarcaje(){

		$('#example5').dataTable().fnClearTable();

		$.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/informemarcatrabajador",		
			data : JSON.stringify({
				fecha_inicio: $("#txtFecha_inicio_permiso").val(),
				fecha_termino: $("#txtFecha_termino_permiso").val(),
				id_persona: $("#txtId").val()				
			}),			
			success: function(dados)
			{
				$('#example5').dataTable().fnClearTable();				
				var dias = ["Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom"];
				
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){

                      var fecha  = new Date(dados[i][j].fecha);
                      var observacion = dados[i][j].obs;
 				  
					  $('#example5').dataTable().fnAddData( [						  
						dias[fecha.getDay()]+" "+convertDateFormat(dados[i][j].fecha),						
						formatearHora(dados[i][j].entradar),	
						formatearHora(dados[i][j].salidar),
						formatearHora(dados[i][j].trabajoreal),						
						formatearHora(dados[i][j].entradaanticipada),	
						formatearHora(dados[i][j].atraso),		
						formatearHora(dados[i][j].salidaanticipada),	
						formatearHora(dados[i][j].salidadespues),	
						formatearHora(dados[i][j].permanencia),					
						formatearHora(dados[i][j].hora_extra),
						observacion						
					  ]);
					}
				}
			}
		});

	}	
	
	function formatearHora(hora){		
		if(hora != null){ hora = hora.replace('-', '');  hora =  hora.substring(0, 5); return hora; } else { return hora; }	
	    return hora;
	}
	
	function convertDateFormat(string) {
        var info = string.split('-').reverse().join('-').split('-');
        return info[0]+"-"+info[1];
    }	
			

	
});	 	
  
</script>

</body>
</html>
