<?php include_once("../lib/control.seguridad.php"); ?>
<?php
	$fecha_inicio = date('Y-m-d', mktime(0,0,0, date('m'), 1, date('Y')));
	$fecha_termino = date('Y-m-d', mktime(0,0,0, date('m'), date("d", mktime(0,0,0, date('m')+1, 0, date('Y'))), date('Y'))); 
?>
<!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 rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />  

   <link href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />   
  <style>
  #example{
	  font-size:10px;
  }
  .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-11">
            <h4>Permisos</h4>
          </div>
			<div class="col-md-1">
			  <button type="button" class="btn btn-info mb-2 btn-sm btn-block" id="btnNuevo_registro">Nuevo</button>	
			</div>			  
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content" id="app">
      <div class="row">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
			  <div class="row">
				<div class="col-md-3">
				  <div class="input-group mb-2 input-group-sm">
					<div class="input-group-prepend">
					  <div class="input-group-text">Fecha Inicio</div>
					</div>
					<input type="text" class="form-control" id="txtFecha_inicio" value="<?php echo $fecha_inicio ?>" readonly >
				  </div>
				</div>
				<div class="col-md-3">
				  <div class="input-group mb-2 input-group-sm">
					<div class="input-group-prepend">
					  <div class="input-group-text">Fecha Termino</div>
					</div>
					<input type="text" class="form-control" id="txtFecha_termino" value="<?php echo $fecha_termino ?>" readonly >
				  </div>
				</div>				
				<div class="col-md-1">
				  <button type="button" class="btn btn-info mb-2 btn-sm btn-block" id="btnBuscar">Buscar</button>
				</div>	
				<div class="col-md-3">
				  <button type="button" class="btn btn-info mb-2 btn-sm" id="btnImprimir">Generar Informe</button>
				 <!-- <button type="button" class="btn btn-info mb-2 btn-sm" id="btnExcel">Generar Excel</button>-->
				</div>						
			  </div>
				<div class="row">
					<div class="col-md-3">
					  <div class="input-group mb-2 input-group-sm">
						<div class="input-group-prepend">
						  <div class="input-group-text">&Aacute;rea</div>
						</div>
						<select class="form-control" id="txtSucursal"> 
							<option value="0">Todo</option>
						</select>
					  </div>
					</div>	
					<div class="col-md-3">
					  <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">
							<option value="0">Seleccione...</option>
						</select>
					  </div>
					</div>						
				</div>			  
            </div>
            <!-- /.card-header -->
            <div class="card-body">
              <table id="example" class="table table-bordered table-striped">
                <thead>
                <tr>			
                  <th>FECHA INICIO</th>				
                  <th>FECHA TERMINO</th>
                  <th>DIAS</th>					  
                  <th>TIPO DE PERMISO</th>	
				  <th>ESTADO</th>		
                  <th>RUT</th>					  
                  <th>TRABAJADOR</th>	
                  <th>&Aacute;REA</th>	
                  <th>CENTRO</th>					  
                  <th></th>					  
                </tr>
                </thead>			
              </table>
			  <div class="div-response"></div>
			  <input type="hidden" class="form-control control-text" id="txtId_autoriza" value="<?php echo $_SESSION['LOGIN']['CODIGO']; ?>">
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  
  <?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 text-center">
			<p>&iquest; Desea Anular Permiso ?</p>
			  <div class="form-group">
				<textarea class="form-control control-text" id="txtObservacion" name="txtObservacion" rows="5"></textarea>
				<small class="form-text text-muted">Observaci&oacute;nes</small>
			  </div>				
		  	  <button type="button" class="btn btn-danger" id="btn-anular">Anular</button>					
		  </div>
		  <div class="modal-footer">
		    <input type="hidden" class="form-control control-text" id="txtId_autoriza" value="<?php echo $_SESSION['LOGIN']['CODIGO'] ?>">
			<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-documento">
			<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>
<!-- ./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/jQueryUI/jquery-ui.js"></script>
<script src="../plugins/toastr/toastr.js"></script>

<script>
  $(function () { 

    $(".modal-body-documento").height(parseInt(screen.height) -400);

    $(document).bind("contextmenu",function(e){
      return false;
    });	  
	  
    $('#txtObservacion').keyup(function(){
        $(this).val($(this).val().toUpperCase());
    });	 	

    $('#example').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": true,
      "ordering": false,
      "info": true,
      "autoWidth": false,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      } 	  
    });
	
	 $.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_inicio").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		onSelect: function(dateText, inst) {
		var lockDate = new Date($('#txtFecha_inicio').datepicker('getDate'));
		$('#txtFecha_termino').datepicker('option', 'minDate', lockDate);
		}		
	 }) 
	
	 $("#txtFecha_termino").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		minDate: $("#txtFecha_inicio").val() 
	 }) 		
	
	$("#btnBuscar").click(function(){
		listarRegistro();
	});
	
	
	combo();
	function combo(){
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/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();	
		$('#txtDepartamento').append($('<option>', {
			value: 0,
			text : "Todo"
		}));
						
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/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();
			}
		});			
	}	
	
	$("#txtDepartamento").change(function () {
		listarRegistro();
    });		
		

		
	listarRegistro();
	function listarRegistro(){

		$('#example').dataTable().fnClearTable();

		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
            crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/public/permisoestadodeptosucursal",	
			data : JSON.stringify({
				fecha_inicio: $("#txtFecha_inicio").val(),
				fecha_termino: $("#txtFecha_termino").val(),
				id_departamento: $("#txtDepartamento").val(),
				id_sucursal: $("#txtSucursal").val(),				
				id_estado: 1				
			}),				
			success: function(dados)
			{
				 var dias = ["Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom"];
				 $('#example').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'>Editar</button>";
					  var boton2 = "<button type='button' class='btn btn-info btn-xs btn-eliminar'>Anular</button>";
					  var boton3 = "<button type='button' class='btn btn-info btn-xs btn-ver-permiso'>Ver Permiso</button>";
					  
					  var fecha_inicio  = new Date(dados[i][j].fecha_inicio);
					  var fecha_termino  = new Date(dados[i][j].fecha_termino);
					  
					  $('#example').dataTable().fnAddData( [
						dias[fecha_inicio.getDay()]+" "+convertDateFormat(dados[i][j].fecha_inicio),	
						dias[fecha_termino.getDay()]+" "+convertDateFormat(dados[i][j].fecha_termino),
						dados[i][j].total,						
						dados[i][j].tipo,
						dados[i][j].estado,		
						dados[i][j].rut,								
						dados[i][j].nombre+" "+dados[i][j].apellido,
						dados[i][j].sucursal,		
						dados[i][j].departamento,								
						boton  +" "+boton2 +" "+boton3 + "<input type='hidden' value ='"+dados[i][j].id+"' />"
					  ]);
					}
				}
			}
		});

	}
	
	function convertDateFormat(string) {
        var info = string.split('-').reverse().join('-').split('-');
        return info[0]+"-"+info[1];
    }	
	
	
	$("#example").on('click','.btn-ver-permiso', function() {
		$('.div-response').html('<form action="../permiso/permiso.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
		'<input type="text" class="form-control" id="txtId_permiso" name="txtId_permiso" value="'+$(this).parents("tr").find("td:eq(9)").find("input").val()+'" >'+
		'</form>');			
		document.forms['form'].submit();
		$('#modal-default').modal('show');		
	});	
	
	$("#example").on('click','.btn-editar', function() {
		var id = $(this).parents("tr").find("td:eq(9)").find("input").val();
		$('.div-response').html('<form action="index.php" name="form" method="post" style="display:none;"><input type="text" name="txtId" id="txtId" value="'+ id +'" /></form>');
		document.forms['form'].submit();
	});		
	
	var idPermiso;	
	$("#example").on('click','.btn-eliminar', function() {			
		$('#modal-delete').modal("show");
	    idPermiso = $(this).parents("tr").find("td:eq(9)").find("input").val();
	});	
		
	$("#btn-anular").click(function(){
		modificarEstadoPermiso(3);	
	});

	function modificarEstadoPermiso(codigo){
		$.ajax({
			type:'POST',
			contentType: 'application/json',
			dataType: "json",
			crossDomain: true,
			headers: {
				'Content-Type': 'application/json'
			},
			url: "<?php include_once('../inc/api_cred.php'); echo $apiUrl; ?>/public/anularpermiso",
			data : JSON.stringify({
				id:idPermiso,
				id_estado:codigo,
				motivo:$("#txtObservacion").val()				
			}),
			success: function(data) {
				if(parseInt(data[0]) == 1){
					$('#modal-delete').modal("toggle");					
					listarRegistro();			
					toastr.success("Permiso Anulado", "POWERTIME");				
					/*$.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/ingresarlogpermiso",
						data : JSON.stringify({
							id_permiso:idPermiso,
							id_usuario:$("#txtId_autoriza").val(),	
							observacion:$("#txtObservacion").val()				
						}),
						success: function(data, textStatus, xhr) {
							if(parseInt(xhr.status) == 201){
								var mensaje = "Permiso Anulado Exitosamente";
								if(codigo == 2){ mensaje = "Permiso Aprobado Exitosamente"; }
								toastr.success(mensaje, "POWERTIME");
								$("#txtObservacion").val("");
							}
						}
					})						
					*/
				}
			}
		})			
	}

	$("#btnImprimir").click(function(){
		$('.div-response').html('<form action="informe.general.permiso.pdf.inc.php"  target="iframe3" name="form" method="POST" style="display:none;"> '+
		'<input type="text" class="form-control" id="txtFecha_inicio" name="txtFecha_inicio" value="'+$("#txtFecha_inicio").val()+'" >'+
		'<input type="text" class="form-control" id="txtFecha_termino" name="txtFecha_termino" value="'+$("#txtFecha_termino").val()+'" >'+
		'<input type="text" class="form-control" id="txtDepartamento" name="txtDepartamento" value="'+$("#txtDepartamento").val()+'" >'+
		'<input type="text" class="form-control" id="txtSucursal" name="txtSucursal" value="'+$("#txtSucursal").val()+'" >'+
		'</form>');			
		document.forms['form'].submit();
		$('#modal-default').modal('show');			
	});
	
	$("#btnExcel").click(function(){
		$('.div-response').html('<form action="exportar.excel.inc.php" target="this" name="form" method="post" style="display:none;">'+
		'<input type="text" class="form-control" id="txtFecha_inicio" name="txtFecha_inicio" value="'+$("#txtFecha_inicio").val()+'" >'+
		'<input type="text" class="form-control" id="txtFecha_termino" name="txtFecha_termino" value="'+$("#txtFecha_termino").val()+'" >'+
		'<input type="text" class="form-control" id="txtDepartamento" name="txtDepartamento" value="'+$("#txtDepartamento").val()+'" >'+
		'<input type="text" class="form-control" id="txtSucursal" name="txtSucursal" value="'+$("#txtSucursal").val()+'" >'+
		'</form>');			
		document.forms['form'].submit();		
	});
	
	$('#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();		 
	});	
		
	
	
	$("#btnNuevo_registro").click(function(){
		window.location="index.php";
	});		
});
</script>
</body>
</html>
