<?php 
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("../lib/control.seguridad.php"); 
?>
<?php

	$boton = "<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>INGRESAR</button>";
	
	$id = "";
	$descripcion = "";
	$diurno = "1";	
	$hide = "d-none";	
    if($_POST){
		
        $hide = "";
		$ch = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerturno'); //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;
		$descripcion = $array[0]->descripcion;	
		$diurno = $array[0]->diurno;			
		curl_close($ch); 

		$boton = "<button type='button' class='btn btn-info btn-sm' id='btnEditar' name='btnEditar'>EDITAR</button>";
	}

?>
<!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" />
  

<style>
  #example{
	  font-size:10px;
  } 
  #example2{
	  font-size:10px;
  }   
  label{
	  font-size:11px;
  }    
   .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-6">
            <h1>Turno</h1>
          </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">
					<h3 class="card-title">Formulario Turnos</h3>
				</div>
				<div class="card-body">
				  <div class="form-group input-group-sm">
					<label>Descripci&oacute;n :</label>
					<input type="text" class="form-control control-text" id="txtDescripcion" value="<?php echo $descripcion; ?>">
				  </div>	
				  <div class="form-group input-group-sm">
					<label>Tipo de Turno :</label>
					<select class="form-control" id="txtDiurno">
						<option value="1" >Turno Diurno</option>
						<option value="2" >Turno Vespertino</option>						
					</select>
				  </div>					  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
					<input type="hidden" class="form-control control-text" id="txtId" value="<?php echo $id ?>" readonly>
					<?php echo $boton  ?>
					<button type='button' class='btn btn-default btn-sm' id='btnListadoUsuario' name='btnListadoUsuario'>LISTADO DE USUARIOS EN TURNO</button>	
					<button type="button" class="btn btn-default btn-sm float-right">Limpiar</button>
				</div>
            </div>
          </div>
          <div class="col-md-6 <?php echo $hide ?>" id="div-horario-turno">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header">
					<h3 class="card-title">Horario Turno</h3>
				</div>
				<div class="card-body">
				  <div class="row">
					<div class="col-md-6">
					  <div class="form-group input-group-sm">
						<label>Hora Inicio :</label>
						<input type="time" class="form-control" id="txtHora_inicio" value="00:00" >
					  </div>						
					</div>
					<div class="col-md-6">
					  <div class="form-group input-group-sm">
						<label>Hora T&eacute;rmino:</label>
						<input type="time" class="form-control" id="txtHora_termino" value="00:00" >
					  </div>					
					</div>					
				  </div>
				  <div class="row">
					<div class="col-md-6">
					  <div class="form-group input-group-sm">
						<label>Descanso:</label>
						<input type="time" class="form-control" id="txtDescanso" value="00:00" >
					  </div>					
					</div>
					<div class="col-md-6">
					  <div class="form-group input-group-sm">
						<label>D&iacute;a:</label>
						<select class="form-control" id="txtDia">
							<option value="2">Lunes</option>
							<option value="3">Martes</option>
							<option value="4">Mi&eacute;rcoles</option>
							<option value="5">Jueves</option>
							<option value="6">Viernes</option>
							<option value="7">Sabado</option>
							<option value="1">Domingo</option>						
						</select>
					  </div>						
					</div>					
				  </div>
					<button type='button' class='btn btn-info btn-sm' id='btnEnviarHTurno' name='btnEnviarHTurno'>INGRESAR HORARIO TURNO</button>				  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
				  <table id="example" class="table table-bordered table-striped">
					<thead>
					<tr>							
					  <th>DIA</th>	
					  <th>HORA INICIO</th>				
					  <th>HORA TERMINO</th>	
					  <th></th>					  
					</tr>
					</thead>			
				  </table>					
				</div>
            </div>
          </div>
		  
        </div>
        <!-- /.row -->
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  
  <?php include_once("../inc/footer.php"); ?>
  
	<div id="modal-delete" class="modal" tabindex="-1" role="dialog">
	  <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">
			<p>&iquest; Desea Eliminar Registro ?</p>
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-secondary btn-xs" data-dismiss="modal">Cerrar</button>
			<button type="button" class="btn btn-info btn-xs" id="btn-confirmar">Confirmar</button>
		  </div>
		</div>
	  </div>
	</div>   

	<div id="modal-usuario" 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">LISTADO DE TRABAJADORES EN 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>TRABAJADOR</th>	
				  <th>SUCURSAL</th>				
				  <th>DEPARTAMENTO</th>					  
				</tr>
				</thead>			
			  </table>	
		  </div>
		  <div class="modal-footer">
		  <button type="button" class="btn btn-info btn-sm" id="btnImprimir">Imprimir</button>
			<button type="button" class="btn btn-secondary btn-sm" 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>

<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>


<script>

  $(function () {
	  
    $(".modal-body-informe").height(parseInt(screen.height) -400);  	  
	  
	$("#btnListadoUsuario").click(function(){
		$('#modal-usuario').modal("show");
        listarPersonaTurno();		
	});
	  
	$("#txtDiurno").val(<?php echo $diurno ?>);  
	  
	    
    $('#example').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": false,
      "info": false,
      "autoWidth": false,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      }	 	  
    });
	    
    $('#example2').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": false,
      "info": false,
      "autoWidth": false,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      }	 	  
    });	
	
	$("#btnEnviarHTurno").click(function(){

		if( $("#txtHora_inicio").val() == null || $("#txtHora_inicio").val().length == 0 || /^\s+$/.test($("#txtHora_inicio").val()) ){
			toastr.warning("Debe ingresar Hora Inicio Turno", "POWERTIME");
            return false;
		}
        else if($("#txtHora_inicio").val() == "00:00"){
			toastr.warning("Debe ingresar Hora Inicio Turno", "POWERTIME");
			return false;
		}
		else if( $("#txtHora_termino").val() == null || $("#txtHora_termino").val().length == 0 || /^\s+$/.test($("#txtHora_termino").val()) ){
			toastr.warning("Debe ingresar Hora T&eacute;rmino Turno", "POWERTIME");
            return false;
		}
        else if($("#txtHora_termino").val() == "00:00"){
			toastr.warning("Debe ingresar Hora T&eacute;rmino Turno", "POWERTIME");
			return false;
		}		
		else{
			$.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/ingresarhorarioturno",
				data : JSON.stringify({
					id_turno:$("#txtId").val(),
					id_dia:$("#txtDia").val(),				
					hora_inicio:$("#txtHora_inicio").val(),
					hora_termino:$("#txtHora_termino").val(),
					descanso:$("#txtDescanso").val()				
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
						listarRegistro();
					}
				}
			})			
		}	
		
	});	
	
	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/obtenerlistadohorarioturno",
			data : JSON.stringify({
				id_turno: $("#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-eliminar'>Eliminar</button>";
					  $('#example').dataTable().fnAddData( [
						dados[i][j].dia,
						formatearHora(dados[i][j].hora_inicio),	
						formatearHora(dados[i][j].hora_termino),
						boton + "<input type='hidden' value ='"+dados[i][j].id+"' />"
					  ]);
					}
				}
			}
		});
	} 
	
	var idEliminar;	
	$("#example").on('click','.btn-eliminar', function() {			
		$('#modal-delete').modal("show");
	    idEliminar = $(this).parents("tr").find("td:eq(3)").find("input").val();
	});	
		
	$("#btn-confirmar").click(function(){
		$.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/eliminarhorarioturno",
			data : JSON.stringify({
				id:idEliminar,							
			}),
			success: function(data, textStatus, xhr) {
				if(parseInt(xhr.status) == 201){
					$('#modal-delete').modal("toggle");					
					listarRegistro();
				}
			}
		})		
	});		
	
	function formatearHora(hora){		
		if(hora != null){ hora = hora.replace('-', '');  hora =  hora.substring(0, 5); return hora; } else { return hora; }	
	}		
 
	$("#btnEnviar").click(function(){

		if($("#txtDescripcion").val().length == 0){
			toastr.warning("Debe Ingresar Descripci&oacute;n", "POWERTIME");
            return false;
		}else{
			
	 
			$.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/ingresarturno",
				data : JSON.stringify({
					id:$("#txtId").val(),
					descripcion:$("#txtDescripcion").val(),
					diurno:$("#txtDiurno").val()					
				}),
				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");
						if(parseInt(data[0].id) > 0){
							$("#txtId").val(data[0].id);
							$("#div-horario-turno").removeClass("d-none");
						}								
					}
				}
			})
		}

	});

	$("#btnEditar").click(function(){

		if($("#txtDescripcion").val().length == 0){
			toastr.warning("Debe Ingresar Descripci&oacute;n", "POWERTIME");
            return false;
		}else{
			$.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/actualizarturno",
				data : JSON.stringify({
					id:$("#txtId").val(),
					descripcion:$("#txtDescripcion").val(),
					diurno:$("#txtDiurno").val()					
				}),
				beforeSend : function()
				{
					//$("#mensajeUsuario").html("<div class='alert alert-info'>Enviando datos</div>");
				},
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
					}
				}
			})
		}

	});	 

 	$("#btnLimpiar").click(function(){
		limpiarFormulario();
	});
	
	function limpiarFormulario(){
		$("#txtDescripcion").val("");
		$("#div-horario-turno").addClass("d-none");
	}
	
	
	function listarPersonaTurno(){

		$('#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/obtenerturnopersonas",	
			data : JSON.stringify({
				id_turno:$("#txtId").val(),				
			}),			
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){												
					  
					  $('#example2').dataTable().fnAddData( [						  
						dados[i][j].nombre +" " +dados[i][j].apellido,	
						dados[i][j].sucursal,	
						dados[i][j].departamento,							
					  ]);
					}
				}
			}
		});

	}

    $("#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="txtId" name="txtId" value="'+$("#txtId").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();		 
	});		
	
});	 	
  
</script>

</body>
</html>
