<?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 = "";	
	$nombre = "";
	$email = "";	
	$idsucursal = 0;
	$iddepartamento = 0;	
	
    if($_POST){
        
		$hide = "";
		$url = 'http://200.24.13.60/~program1/power-time-api/public/obtenerfirmante';
		$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;
		$idsucursal = $array[0]->idsucursal;		
		$iddepartamento = $array[0]->iddepartamento;		
		$nombre = $array[0]->nombre;	
		$email = $array[0]->email;		

		$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" />
  <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;
	  }	  
      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>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="form-group input-group-sm">
					<label>&Aacute;rea :</label>
					<select class="form-control" id="txtSucursal">
					</select>
				  </div>	
				  <div class="form-group input-group-sm">
					<label>Centro :</label>
					<select class="form-control" id="txtDepartamento">
						<option value="0">Seleccione...</option>
					</select>
				  </div>				  
				  <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">
				  </div>			  
				  <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 ?>" maxlength="50">
				  </div>				  				  				  			
				  <div class="form-group input-group-sm">
					<label>E-mail:</label>
					<input type="text" class="form-control" id="txtEmail" value="<?php echo $email ?>">
				  </div>				  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
					<?php echo $boton ?>
					<input type="hidden" class="form-control" id="txtId" value="<?php echo $id ?>" readonly>					
					<button type="button" class="btn btn-default float-right" id="btnLimpiar">Limpiar</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>

<script>

  $(function () {
	  
    $(document).bind("contextmenu",function(e){
      return false;
    });	  
	
	$(".control-rut").bind('keypress', function(event) {
	  var regex = new RegExp("^[0-9 Kk .-]+$");
	  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 ñÑ]+$");
	  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
	  if (!regex.test(key)) {
		event.preventDefault();
		return false;
	  }
	});	 

 
	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/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
						}));
					}
				}
			}
		});			
	}		

	function validarEmail(valor) {
		if (/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(valor)){
			return true;
		} else {
			return false;
		}
	}	
		
	  
	$("#btnEnviar").click(function(){

		if( $("#txtNombre").val() == null || $("#txtNombre").val().length == 0 || /^\s+$/.test($("#txtNombre").val()) ){
			toastr.warning("Debe ingresar Nombre de Persona", "POWERTIME");
            return false;
		}
		else if( $("#txtRut").val() == null || $("#txtRut").val().length == 0 || /^\s+$/.test($("#txtRut").val()) ) {
			toastr.warning("Debe Ingresar Rut", "POWERTIME");
			return false;
		}
		else if( $("#txtEmail").val() == null || $("#txtEmail").val().length == 0 || /^\s+$/.test($("#txtEmail").val()) ) {
			toastr.warning("Debe Ingresar E-mail", "POWERTIME");
			return false;
		}
		else if( !validarEmail($("#txtEmail").val()) ) {
			toastr.warning("Debe Ingresar E-mail V&aacute;lido", "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/ingresarfirmante",
				data : JSON.stringify({
					rut:$("#txtRut").val(),
					idsucursal:$("#txtSucursal").val(),						
					iddepartamento:$("#txtDepartamento").val(),					
					nombre:$("#txtNombre").val(),	
					email:$("#txtEmail").val()					
				}),
				success: function(data, textStatus, xhr) {						
					if(parseInt(xhr.status) == 201){					
						toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
					}
				}
			})
		}

	});



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

		if( $("#txtNombre").val() == null || $("#txtNombre").val().length == 0 || /^\s+$/.test($("#txtNombre").val()) ){
			toastr.warning("Debe ingresar Nombre de Persona", "POWERTIME");
            return false;
		}
		else if( $("#txtRut").val() == null || $("#txtRut").val().length == 0 || /^\s+$/.test($("#txtRut").val()) ) {
			toastr.warning("Debe Ingresar Rut", "POWERTIME");
			return false;
		}
		else if( $("#txtEmail").val() == null || $("#txtEmail").val().length == 0 || /^\s+$/.test($("#txtEmail").val()) ) {
			toastr.warning("Debe Ingresar E-mail", "POWERTIME");
			return false;
		}
		else if( !validarEmail($("#txtEmail").val()) ) {
			toastr.warning("Debe Ingresar E-mail V&aacute;lido", "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/actualizarfirmante",
				data : JSON.stringify({
					id:$("#txtId").val(),
					idsucursal:$("#txtSucursal").val(),						
					iddepartamento:$("#txtDepartamento").val(),						
					rut:$("#txtRut").val(),				
					nombre:$("#txtNombre").val(),
					email:$("#txtEmail").val(),					
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Registro Editado Exitosamente", "POWERTIME");
					}
				}
			})
		}

	});
	
});	 	
  
</script>

</body>
</html>
