<?php include_once("../lib/control.seguridad.php"); ?>
<?php

	$boton = "<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>INGRESAR</button>";
	
	$id = "";
	$rut = "";
	$pasaporte = "";		
	$nombre = "";
	$apellido = "";	
	$telefono = "";	
	$email = "";	
	$id_nacionalidad = "";	
	$marca = "";		
	$usuario = "";	
	$contrasena = "";		
	
	$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;		
		$id_nacionalidad = $array[0]->id_nacionalidad;	
		$marca = $array[0]->marca;			
		$usuario = $array[0]->usuario;	
		$contrasena = $array[0]->contrasena;
		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">
  
  <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;
  }  
  </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>Trabajador</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">General Form</li>
            </ol>
          </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">
					<h3 class="card-title p-3">Formulario Trabajador</h3>
				</div>
				<div class="card-body">
				  <div class="form-group">
					<label>Rut :</label>
					<input type="text" class="form-control control-number" id="txtRut" value="<?php echo $rut ?>">
					<small class="form-text text-muted">Rut.</small>
				  </div>
				  <div class="form-group">
					<label>Pasaporte :</label>
					<input type="text" class="form-control control-number" id="txtPasaporte" value="<?php echo $pasaporte ?>">
					<small class="form-text text-muted">N&uacute;mero de Pasaporte.</small>
				  </div>				  
				  <div class="form-group">
					<label>Nombres:</label>
					<input type="text" class="form-control control-text" id="txtNombre" value="<?php echo $nombre ?>">
					<small class="form-text text-muted">Nombre.</small>
				  </div>
				  <div class="form-group">
					<label>Apellidos:</label>
					<input type="text" class="form-control control-text" id="txtApellido" value="<?php echo $apellido ?>">
					<small class="form-text text-muted">Apellidos.</small>
				  </div>	
				  <div class="form-group">
					<label>Marcaje Laboral :</label>
					<select class="form-control" id="txtMarca">
						<option value="1">Si, marca turno laboral</option>
						<option value="2">Art&iacute;culo 22, C&oacute;digo del trabajo</option>						
					</select>
					<small class="form-text text-muted">Seleccione Opci&oacute;n de Marcaje Laboral.</small>
				  </div>							  
				  <div class="form-group">
					<label>Nacionalidad :</label>
					<select class="form-control" id="txtNacionalidad">
						<option value="0">Seleccione...</option>
					</select>
					<small class="form-text text-muted">Seleccione Nacionalidad.</small>
				  </div>					  
				  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
					<?php echo $boton ?>
					<input type="hidden" class="form-control control-text" id="txtId" value="<?php echo $id ?>" readonly>					
					<button type="button" class="btn btn-default float-right" id="btnLimpiar">Limpiar</button>
				</div>
            </div>
          </div>
          <div class="col-md-6">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-header d-flex p-0">
					<h3 class="card-title p-3">Datos Contacto</h3>
					<ul class="nav nav-pills ml-auto p-2 <?php echo $hide ?>" id="menu-turno">
					  <li class="nav-item">
						<a class="nav-link nav-departamento active" href="#contacto" data-toggle="tab">Contacto</a>
					  </li>
					  <li class="nav-item">
						<a class="nav-link nav-equipo" href="#turno" data-toggle="tab">Turno</a>
					  </li>
					  <li class="nav-item">
						<a class="nav-link nav-equipo" href="#depto" data-toggle="tab">Departamento</a>
					  </li>					  
					</ul>						
				</div>
				<div class="card-body">	
					<div class="tab-content p-0">
					  <div class="tab-pane active" id="contacto">
						  <div class="form-group">
							<label>Telefono :</label>
							<input type="text" class="form-control control-number" id="txtTelefono" value="<?php echo $telefono ?>">
							<small class="form-text text-muted">Telefono de Contacto.</small>
						  </div>				
						  <div class="form-group">
							<label>E-mail:</label>
							<input type="text" class="form-control control-text" id="txtEmail" value="<?php echo $email ?>">
							<small class="form-text text-muted">Correo Electr&oacute;nico de Contacto.</small>
						  </div>		 			  
					  </div>
					  <div class="tab-pane" id="turno">
						  <div class="form-group">
							<label>Turno :</label>
							<select class="form-control" id="txtTurno">
								<option value="0">Seleccione...</option>
							</select>
							<small class="form-text text-muted">Turno Laboral Trabajador.</small>
						  </div>
						  <button type='button' class='btn btn-info btn-sm' id='btnEnviarTurno' name='btnEnviarTurno'>INGRESAR</button>	
						  <table id="example" class="table table-bordered table-striped">
							<thead>
							<tr>			
							  <th>TURNO</th>				
							  <th class="col-md-2"></th>					  
							</tr>
							</thead>			
						  </table>						  
					  </div>  
					  <div class="tab-pane" id="depto">
						  <div class="form-group">
							<select class="form-control" id="txtSucursal">
							</select>
							<small class="form-text text-muted">Sucursal Trabajador..</small>
						  </div>					  
						  <div class="form-group">
							<label>Departamento :</label>
							<select class="form-control" id="txtDepartamento">
								<option value="0">Seleccione...</option>
							</select>
							<small class="form-text text-muted">Departamento Trabajador.</small>
						  </div>
						  <button type='button' class='btn btn-info btn-sm' id='btnEnviarDepartamento' name='btnEnviarDepartamento'>INGRESAR</button>	
						  <table id="example2" class="table table-bordered table-striped">
							<thead>
							<tr>			
							  <th>DEPARTAMENTO</th>				
							  <th class="col-md-2"></th>					  
							</tr>
							</thead>			
						  </table>						  
					  </div>  					  
					</div>	
					
			
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
				</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 MENSAJE SISTEMA</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" data-dismiss="modal">Cerrar</button>
			<button type="button" class="btn btn-info" id="btn-confirmar">Confirmar</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>

<script>

  $(function () {
	  
    $('#example').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false,
    });
	
    $('#example2').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false,
    });	
	
	$(".control-number").bind('keypress', function(event) {
	  var regex = new RegExp("^[0-9]+$");
	  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
	  if (!regex.test(key)) {
		event.preventDefault();
		return false;
	  }
	});	 
	
	/*
	$(".control-text").bind('keypress', function(event) {
	  var regex = new RegExp("^[a-zA-Z 0-9]+$");
	  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
	  if (!regex.test(key)) {
		event.preventDefault();
		return false;
	  }
	});	 
*/
    $('#txtMarca').val(<?php echo $marca ?>);
	combo();
	function combo(){
		$.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/nacionalidad",		
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtNacionalidad').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
				$('#txtNacionalidad').val(<?php echo $id_nacionalidad ?>);
			}
		});		
		$.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/turno",		
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtTurno').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
			}
		});
		$.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/sucursal",		
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtSucursal').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
				departamento();
			}
		});			
	}	
	
	$("#txtSucursal").change(function () {
		departamento();
    });

	function departamento(){
		$('#txtDepartamento').empty();	
		$.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/obtenerdepartamentosucursal",
			data : JSON.stringify({
				id_sucursal: $('#txtSucursal').val(),								
			}),			
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtDepartamento').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
				listarRegistro();
			}
		});			
	}		
	  
	$("#btnEnviar").click(function(){

		if($("#txtRut").val().length == 0){
			$("#mensajeUsuario").html("Debe Ingresar Descripci&oacute;n");
			$("#modal-default2").modal('show');
            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/ingresartrabajador",
				data : JSON.stringify({
					rut:$("#txtRut").val(),
					pasaporte:$("#txtPasaporte").val(),					
					nombre:$("#txtNombre").val(),
					apellido:$("#txtApellido").val(),					
					telefono:$("#txtTelefono").val(),	
					email:$("#txtEmail").val(),	
					id_nacionalidad:$("#txtNacionalidad").val(),
					marca:$("#txtMarca").val()					
				}),
				beforeSend : function()
				{
					//$("#mensajeUsuario").html("<div class='alert alert-info'>Enviando datos</div>");
				},
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						if(parseInt(data[0].id) > 0){
							$("#txtId").val(data[0].id);
							$("#menu-turno").removeClass("d-none");
						}						
						toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
					}
				}
			})
		}

	});

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

		if($("#txtRut").val().length == 0){
			$("#mensajeUsuario").html("Debe Ingresar Descripci&oacute;n");
			$("#modal-default2").modal('show');
            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/actualizartrabajador",
				data : JSON.stringify({
					id:$("#txtId").val(),
					rut:$("#txtRut").val(),
					pasaporte:$("#txtPasaporte").val(),					
					nombre:$("#txtNombre").val(),
					apellido:$("#txtApellido").val(),					
					telefono:$("#txtTelefono").val(),	
					email:$("#txtEmail").val(),	
					id_nacionalidad:$("#txtNacionalidad").val(),
					marca:$("#txtMarca").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 Editado Exitosamente", "POWERTIME");
					}
				}
			})
		}

	});	 

 	$("#btnLimpiar").click(function(){
		limpiarFormulario();
	});
	
	function limpiarFormulario(){
		$("#txtDescripcion").val("");
	}
	
	$("#btnEnviarTurno").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/ingresarturnopersona",
			data : JSON.stringify({
				id_persona:$("#txtId").val(),
				id_turno:$("#txtTurno").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/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-sm btn-eliminar'>Eliminar</button>";
					  $('#example').dataTable().fnAddData( [
						dados[i][j].descripcion,	
						boton  + "<input type='hidden' value ='"+dados[i][j].id+"' />"
					  ]);
					}
				}
			}
		});

	}

	var idEliminar;
    var idModulo = 1;		
	$("#example").on('click','.btn-eliminar', function() {			
		$('#modal-delete').modal("show");
	    idEliminar = $(this).parents("tr").find("td:eq(1)").find("input").val();
		idModulo = 1;
	});	
		
	$("#btn-confirmar").click(function(){
		if(idModulo == 1){
			$.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/eliminarturnopersona",
				data : JSON.stringify({
					id:idEliminar,								
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						$('#modal-delete').modal("toggle");					
						listarRegistro();
					}
				}
			})
		}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/eliminardepartamentopersona",
				data : JSON.stringify({
					id:idEliminar,								
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						$('#modal-delete').modal("toggle");					
						listarRegistroDep();
					}
				}
			})			
		}		
	});	
	
	$("#btnEnviarDepartamento").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/ingresardepartamentopersona",
			data : JSON.stringify({
				id_persona:$("#txtId").val(),
				id_departamento:$("#txtDepartamento").val()					
			}),
			success: function(data, textStatus, xhr) {
				if(parseInt(xhr.status) == 201){				
					toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
					listarRegistroDep();
				}
			}
		})		

	});
	
	
	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 boton = "<button type='button' class='btn btn-info btn-sm btn-eliminar'>Eliminar</button>";
					  $('#example2').dataTable().fnAddData( [
						dados[i][j].departamento,	
						boton  + "<input type='hidden' value ='"+dados[i][j].id+"' />"
					  ]);
					}
				}
			}
		});

	}	
	$("#example2").on('click','.btn-eliminar', function() {			
		$('#modal-delete').modal("show");
	    idEliminar = $(this).parents("tr").find("td:eq(1)").find("input").val();
		idModulo = 2;
	});	
			
	
});	 	
  
</script>

</body>
</html>
