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

	$fecha_inicio = date('d-m-Y');


	$boton = "<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>INGRESAR</button>";
	
	$id = 0;
	$fecha = date("d-m-Y");
	$id_persona = 0;	
	$id_autoriza = $_SESSION['LOGIN']['CODIGO'];
	$nombrePersona = "";
	$nombreAuroriza = $_SESSION['LOGIN']['NOMBRE'];	
	$observacion = "";	
	$hide = "d-none";
	$id_motivo = 0;		
	
    if($_POST){

		$hide = "";
		$url = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpermiso';
		$ch = curl_init($url); //create a new cURL resource
		$payload = json_encode(array('id' => $_POST["txtId"], 'api_token'=> 'lEkujNtWXOCCsOhRBIRON8I8wWZVhHGm5JylqMZC'));
		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;
		$fecha = date('d-m-Y', strtotime($array[0]->fecha));
		$id_persona = $array[0]->id_persona;	
		$id_autoriza = $array[0]->id_autoriza;
		$observacion = $array[0]->observacion;		
		$id_motivo = $array[0]->id_motivo;			
		/******************************************************************/		

		$url2 = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpersona';
		$ch2 = curl_init($url2); //create a new cURL resource
		$payload2 = json_encode(array('id' => $id_persona));
		curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);//attach encoded JSON string to the POST fields
		curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
		curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
		$result2 = curl_exec($ch2); //execute the POST request
		$array2 = json_decode($result2);
	
		$nombrePersona = $array2[0]->nombre ." ". $array2[0]->apellido;
		curl_close($ch2);
		
		/******************************************************************/		

		$url2 = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpersona';
		$ch2 = curl_init($url2); //create a new cURL resource
		$payload2 = json_encode(array('id' => $id_autoriza));
		curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);//attach encoded JSON string to the POST fields
		curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
		curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
		$result2 = curl_exec($ch2); //execute the POST request
		$array2 = json_decode($result2);
	
		$nombreAuroriza = $array2[0]->nombre ." ". $array2[0]->apellido;
		curl_close($ch2); 				
		
		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" />
  
  <!-- JQUERY UI -->  
  <link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />
  
  <style>
  #example{
	  font-size:10px;
  }
  label{
	  font-size:12px;
  }  
  #example3{
	  font-size:10px;
  }
  .content-header h4{ 
	  font-size: 20px
  }  
  
  .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">
            <h4>Ingreso de Ausencia</h4>
			<input type="hidden" class="form-control control-text" id="txtId_autoriza" value="<?php echo $id_autoriza ?>">		  			
		  </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-body">
				  <div class="form-group">
					<label>Seleccionar Trabajador:</label>
						<div class="row">
							<div class="col-md-9 input-group-sm">
								<input type="text" class="form-control control-text" id="txtNombre" value="<?php echo $nombrePersona ?>" readonly> 
								<input type="hidden" class="form-control control-text" id="txtId_persona" value="<?php echo $id_persona ?>">
							</div>
							<div class="col-md-3"> 
								<button type="button" class="btn btn-info btn-block btn-sm" id="btnBuscar">Buscar </button>
							</div>
						</div>					  
				  </div>				    
				  <div class="form-group input-group-sm">
					<label>Fecha :</label>
					<input type="text" class="form-control control-number" id="txtFecha" value="<?php echo $fecha ?>" readonly>
				  </div>
				  <div class="form-group input-group-sm">
					<label>Seleccione :</label>
					<select class="form-control" id="txtMotivo">
						<option value="0">Seleccione...</option>
					</select>
				  </div>					  
				  <div class="form-group input-group-sm">
					<label>Observaci&oacute;n :</label>
					<textarea type="text" class="form-control" id="txtObservacion" rows="3"><?php echo $observacion ?></textarea>
				  </div>				  
				</div>
				<!-- /.card-body -->
				<div class="card-footer">
					<?php echo $boton ?>
					<input type="hidden" class="form-control control-text" id="txtCargo" value="<?php echo $_SESSION['LOGIN']['CARGOUSUARIO'] ?>">
					<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 d-none" id="div-trabajador">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-body">
        			 <div class="row">
        			    <div class="col-md-12">
        				  <div class="input-group mb-2 input-group-sm">
        					<div class="input-group-prepend">
        					  <div class="input-group-text">Centro</div>
        					</div>
        					<select class="form-control" id="txtDepartamento"> </select>
        				  </div>							
        				</div>			
        			 </div>		  
        			 <div class="row">
        				<div class="col-md-12">
        				  <table id="example3" class="table table-bordered table-striped">
        					<thead>
        					<tr>	
        					  <th>RUT</th>					
        					  <th>NOMBRE</th>
        					  <th>TURNO</th>	
        					  <th>CARGO</th>						  
        					  <th></th>				  
        					</tr>
        					</thead>			
        				  </table>					
        				</div>
        			 </div>
				</div>
				<!-- /.card-body -->
				<div class="card-footer">

				</div>
            </div>
          </div>             
          
          <div class="col-md-6 d-none" id="div-permisos">
            <!-- Horizontal Form -->
            <div class="card">
				<div class="card-body">
        			 <div class="row">
        				<div class="col-md-12">
        				  <table id="example" class="table table-bordered table-striped">
        					<thead>
        					<tr>						  
        					  <th>FECHA</th>
        					  <th>OBSERVACI&Oacute;N</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>
<!-- ./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>
<!-- DataTables -->
<script src="../plugins/datatables/jquery.dataTables.js"></script>
<script src="../plugins/datatables-bs4/js/dataTables.bootstrap4.js"></script>

<script src="../plugins/toastr/toastr.js"></script>

  <!-- JQUERY UI --> 
<script src="../plugins/jQueryUI/jquery-ui.js"></script>


<script>

  $(function () {
	  
	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/motivo",		
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtMotivo').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
				$('#txtMotivo').val(<?php echo $id_motivo ?>);
			}
		});	
	
	}

	$('#txtMotivo').change(function(){
		if($('#txtMotivo').val() == 0){
			$('#txtObservacion').val("");
		}else{
			$('#txtObservacion').val($('#txtMotivo option:selected').text());
		}
		
	});
	
	   
     $('#example3').DataTable({
		  "paging": true,
		  "lengthChange": false,
		  "searching": false,
		  "ordering": true,
		  "info": false,
		  "autoWidth": false,
		  "pageLength": 7,
		  "language": {
			"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
		  } 			  
     });	

     $('#example').DataTable({
		  "paging": true,
		  "lengthChange": false,
		  "searching": false,
		  "ordering": true,
		  "info": false,
		  "autoWidth": false,
		  "pageLength": 7,
		  "language": {
			"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
		  } 	
     });		 
	  
	  
    $(document).bind("contextmenu",function(e){
      return false;
    });	  
	  
	 $.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").datepicker({
		dateFormat: "dd-mm-yy",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",	
	 }) 
	
	listarRegistroDep();
	function listarRegistroDep(){

		$.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_autoriza").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_departamento,
							text : dados[i][j].sucursal + " (" +dados[i][j].departamento +" )"
						}));
					}
				}
				listarRegistro();
			}
		});

	}
	
	$("#txtDepartamento").change(function () {
		listarRegistro();
    });	
	function listarRegistro(){

		$('#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/obtenerpersonadepartamento",
			data : JSON.stringify({
				id_departamento: $('#txtDepartamento').val(),								
			}),		
			success: function(dados)
			{
				$('#example3').dataTable().fnClearTable();
				 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'>Asignar</button>";
					  $('#example3').dataTable().fnAddData( [
						dados[i][j].rut,						  
						dados[i][j].nombre+" "+dados[i][j].apellido,	
						dados[i][j].turno,		
						dados[i][j].cargo,								
						boton +"<input type='hidden' value ='"+dados[i][j].id+"' />"
					  ]);
					}
				}
			}
		});

	}
	
	$("#example3").on('click','.btn-editar', function() {
		var id = $(this).parents("tr").find("td:eq(4)").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/obtenerpersona",
			data : JSON.stringify({
				id: id			
			}),			
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){					
					$("#txtNombre").val(dados[i].nombre+" "+dados[i].apellido); 
					$("#txtId_persona").val(id);
					$("#div-trabajador").addClass("d-none");	
					$("#div-permisos").removeClass("d-none");
					listarPermisoTrabajador();
				}
			}
		});			
	});			
		

	$("#btnEnviar").click(function(){
		if(parseInt($("#txtId_persona").val()) == 0){
			toastr.warning("Debe Seleccionar Trabajador", "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/ingresarfalta",
				data : JSON.stringify({
					id:$("#txtId").val(),
					fecha:convertDateFormat($("#txtFecha").val()),	
					id_persona:$("#txtId_persona").val(),	
					id_autoriza:$("#txtId_autoriza").val(),	
					id_motivo:$("#txtMotivo").val(),	
					observacion:$("#txtObservacion").val(),						
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
						listarPermisoTrabajador();
						limpiarFormulario();
					}
				}
			})			
		}
		
	});	

	$("#btnBuscar").click(function(){
		$("#txtNombre").val(""); 
		$("#txtId_persona").val(0);
		$("#div-permisos").addClass("d-none");
		$("#div-trabajador").removeClass("d-none");		
	});

 	$("#btnLimpiar").click(function(){
		limpiarFormulario();
	});
	
	function limpiarFormulario(){
		$("#txtId").val(0);
		$("#txtFecha").val(convertDateFormat(fechaActual()));			
		$("#txtId_persona").val(0);		
		$("#div-permisos").addClass("d-none");
		$("#txtNombre").val(""); 
		$("#txtMotivo").val(0); 
		$("#txtObservacion").val(""); 
		$("#div-trabajador").addClass("d-none");
		//$("#btnEnviar").attr("disabled", false); 
	}
 
	function fechaActual(){
		var fecha = new Date();
		var dia = fecha.getDate();
		var mes = fecha.getMonth() + 1;
		var anio = fecha.getFullYear();	
		if(dia < 10) { dia = "0"+dia; } 
		if(mes < 10) { mes = "0"+mes; }
        return anio+"-"+mes+"-"+dia;  		
	}

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

		$('#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/validaingresofalta",	
			data : JSON.stringify({
				fecha: convertDateFormat($("#txtFecha").val()),
				id_persona: $("#txtId_persona").val(),					
			}),				
			success: function(dados)
			{ 
				 for (i=0;i<dados.length;i++){					
					 $('#example').dataTable().fnAddData( [
						convertDateFormat($("#txtFecha").val()),	
						dados[i].mensaje						
					 ]);
					 //if(dados[i].cantidad > 0) { $("#btnEnviar").attr("disabled", true); }
				}
			}
		});

	}

 
	
	function convertDateFormat(numeros) {
        return numeros.split('-').reverse().join('-');
    }		
	
});	 	
  
</script>

</body>
</html>
