<?php include_once("../lib/control.seguridad.php"); ?>
<?php
	
	$id = "";
	$rut = "";
	$pasaporte = "";		
	$nombre = "";
	$apellido = "";
	$id_pantalla = "";	
	$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;
		$id_pantalla = $array[0]->id_pantalla;		
		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">   
  <style>
  #example{
	  font-size:11px;
  }
  #example2{
	  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">
          <div class="col-sm-6">
            <h4>Perf&iacute;les de Acceso Usuario</h4>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content" id="app">
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-8">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header">
				  <div class="row">
					<div class="col-md-8">					
					  <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 control-text txtToUpper" id="txtNombre" value="<?php echo $nombre ." ".$apellido  ?>" readonly>
					  </div>										
					</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">Rut</div>
						</div>
						<input type="text" class="form-control control-number" 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>					
				</div>
				<div class="card-body">		
				  <table id="example" class="table table-bordered table-striped">
					<thead>
					<tr>			
					  <th><input type='checkbox' class='btn-checkbox-todo' ></th>				
					  <th>PERFIL</th>			  
					</tr>
					</thead>			
				  </table>
				  <div class="div-response"></div>					
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
			
				</div>
            </div>
          </div>
          <div class="col-md-4">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header">				
				</div>
				<div class="card-body">	
				  <div class="form-group input-group-sm">
					<label>Pantalla Principal :</label>
					<select class="form-control" id="txtPerfil">
						<option value="0">Seleccione...</option>
					</select>
					<small class="form-text text-muted">Seleccione Pantalla de inicio para usuario.</small>
				  </div>					
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
					<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>MODIFICAR</button>
				</div>
            </div>
          </div>		  
        </div>
        <!-- /.row -->
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  
  <?php include_once("../inc/footer.php"); ?>

	
</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 () {
	  
    $(document).bind("contextmenu",function(e){
      return false;
    });	  	  
	  
    $('#example').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"
      } 		  
    });	 
    comboPerfil();
	function comboPerfil(){
		$.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/perfiles",	
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtPerfil').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
				$('#txtPerfil').val(<?php echo $id_pantalla ?>);
			}
		});			
	}	
	
	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/listarperfilespersona",	
			data : JSON.stringify({
				idpersona:$("#txtId").val()			
			}),			
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
					  var checkbox = "<input type='checkbox' class='btn-checkbox' >";
					  if(parseInt(dados[i][j].activo) == 1){ checkbox = "<input type='checkbox' class='btn-checkbox' checked >"; }
						
					  $('#example').dataTable().fnAddData( [
                        checkbox,					  
						dados[i][j].descripcion + "<input type='hidden' value ='"+dados[i][j].id+"' />"							
					  ]);
					}
				}
			}
		});

	}	
	
    $("#example").on('click','.btn-checkbox', function() {
          var idperfil = $(this).parents("tr").find("td:eq(1)").find("input").val();
	
		  if($(this).is(":checked")){
			$.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/ingresarperfilpersona",
				data : JSON.stringify({
					id_persona:$("#txtId").val(),
					id_perfil:idperfil				
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Permiso de Acceso Otorgado Exitosamente", "POWERTIME");
					}
				}
			}) 		  
		  }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/eliminarperfilpersona",
				data : JSON.stringify({
					id_persona:$("#txtId").val(),
					id_perfil:idperfil				
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.error("Permiso de Acceso a Modulo Revocado", "POWERTIME");
					}
				}
			}) 	
		  }

    });	
	
	$(".btn-checkbox-todo").click(function(){	
		if($(this).is(":checked")){
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", true);
				var idperfil = $(this).find("td:eq(1)").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/ingresarperfilpersona",
					data : JSON.stringify({
						id_persona:$("#txtId").val(),
						id_perfil:idperfil				
					}),
					success: function(data, textStatus, xhr) {
						if(parseInt(xhr.status) == 201){
							toastr.success("Permiso de Acceso Otorgado Exitosamente", "POWERTIME");
						}
					}
				}) 				
			}); 	
		}else{
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", false);
				var idperfil = $(this).find("td:eq(1)").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/eliminarperfilpersona",
					data : JSON.stringify({
						id_persona:$("#txtId").val(),
						id_perfil:idperfil				
					}),
					success: function(data, textStatus, xhr) {
						if(parseInt(xhr.status) == 201){
							toastr.error("Permiso de Acceso a Modulo Revocado", "POWERTIME");
						}
					}
				}) 				
			}); 			
		}
	});

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

		if( parseInt($("#txtPerfil").val()) == 0){
			toastr.warning("Debe seleccionar Pantalla de Inicio", "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/actualizarpantallausuario",
				data : JSON.stringify({
					id:$("#txtId").val(),
					id_pantalla:$("#txtPerfil").val(),									
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){					
						toastr.success("Pantalla de Inicio asignada Exitosamente", "POWERTIME");
					}
				}
			})
		}

	});	
		
	
});	 	
  
</script>

</body>
</html>
