<?php include_once("../lib/control.seguridad.php"); ?>
<!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">    
  <!-- JQUERY TIMEPICKER -->  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">    
  <link href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />  
  
  <link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.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-6">
            <h4>Cuadro Comparativo Permisos</h4>
          </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-4">
					  <div class="input-group mb-2 input-group-sm">
						<div class="input-group-prepend">
						  <div class="input-group-text">Sucursal</div>
						</div>
						<select class="form-control" id="txtSucursal"> 
							<option value="0">Todos</option>						
						</select>
					  </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">Departamento</div>
						</div>
						<select class="form-control" id="txtDepartamento">
							<option value="0">Todos</option>
						</select>
					  </div>
					</div>
					<div class="col-md-1">
					  <button type="button" class="btn btn-info mb-2 btn-sm btn-block" id="btnBuscarPermiso">Buscar</button>
					</div>						
					<div class="col-md-3">
					  <button type="button" class="btn btn-info mb-2 btn-sm float-right" id="btnImprimir">Imprimir Informe</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">Fecha Inicio</div>
						</div>
						<input type="text" class="form-control" id="txtFecha_inicio_permiso" value="<?php echo date("Y-m-d", strtotime("-3 month", strtotime(date("Y-m-d")))); ?>" 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_permiso" value="<?php echo date("Y-m-d") ?>" readonly >
					  </div>
					</div>						
				</div>				
            </div>
            <!-- /.card-header -->
            <div class="card-body">
			  <div class="row">
				<div class="col-md-4">
					<div class="chart">
					  <canvas id="barChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
					</div>
					<div class="chart-line">
					  <canvas id="areaChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
					</div>					
				</div>
				<div class="col-md-8">
				  <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>TRABAJADOR</th>	
					  <th>SUCURSAL</th>						  
					  <th>DEPARTAMENTO</th>						  
					  <th>OBSERVACION</th>						  
					</tr>
					</thead>			
				  </table>				
				</div>
			  </div>
			  <div class="div-response"></div>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  
  <?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>
<!-- ChartJS -->
<script src="../plugins/chart.js/Chart.min.js"></script>

<script src="../plugins/toastr/toastr.js"></script>
<script src="../plugins/jQueryUI/jquery-ui.js"></script>
<script>
  $(function () { 
  
  
	 $.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']);
	 $("#txtFecha_inicio_permiso").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		onSelect: function(dateText, inst) {
		var lockDate = new Date($('#txtFecha_inicio_permiso').datepicker('getDate'));
		$('#txtFecha_termino_permiso').datepicker('option', 'minDate', lockDate);
		}		
	 }) 
	
	 $("#txtFecha_termino_permiso").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		minDate: $("#txtFecha_inicio_permiso").val() 
	 }) 
	 
    $('#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"
      }	 	  
    });
	
	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();
				listarRegistro();
				generarGrafico();
			}
		});				
	}

	$("#txtSucursal").change(function () {
		departamento();
		listarRegistro();
		generarGrafico();
    });

	function departamento(){
		$('#txtDepartamento').empty();	
		$('#txtDepartamento').append($('<option>', {
			value: 0,
			text : "Todos"
		}));		
		$.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
						}));
					}
				}
			}
		});			
	}	
	
	$("#txtDepartamento").change(function () {
		listarRegistro();
		generarGrafico();
    });	
	
	$("#btnBuscarPermiso").click(function () {
		listarRegistro();
		generarGrafico();
    });

    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/listarpermisosucursaldepartamento",
			data : JSON.stringify({
				id_sucursal: $("#txtSucursal").val(),	
				id_departamento: $("#txtDepartamento").val(),					
				fecha_inicio: $("#txtFecha_inicio_permiso").val(),
				fecha_termino: $("#txtFecha_termino_permiso").val()				
			}),			
			success: function(dados)
			{
				$('#example').dataTable().fnClearTable();
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
					  $('#example').dataTable().fnAddData( [
						dados[i][j].fecha_inicio,						  
						dados[i][j].fecha_termino,	
						dados[i][j].total,							
						dados[i][j].tipo,		
						dados[i][j].nombre +" "+dados[i][j].apellido,	
						dados[i][j].sucursal,		
						dados[i][j].departamento,								
						dados[i][j].observacion
					  ]);
					}
				}
			}
		});			
	}
	
	$("#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_permiso").val()+'" >'+
		'<input type="text" class="form-control" id="txtFecha_termino" name="txtFecha_termino" value="'+$("#txtFecha_termino_permiso").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');			
	});
	
	$('#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();		 
	});		
	
	generarGrafico();
	function generarGrafico(){
		
      $('#barChart').remove(); // this is my <canvas> element
      $('.chart').append('<canvas id="barChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>');		
		
		var meses = new Array();
		var cantidad = new Array();

		
		$.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/estadisticapermiso",			
			data : JSON.stringify({
				id_sucursal: $("#txtSucursal").val(),	
				id_departamento: $("#txtDepartamento").val(),					
				fecha_inicio: $("#txtFecha_inicio_permiso").val(),
				fecha_termino: $("#txtFecha_termino_permiso").val()								
			}),			
			success: function(dados)
			{				 
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){						
						meses.push (dados[i][j].fecha_inicio);
						cantidad.push (parseInt(dados[i][j].cantidad));						
					}
				 }
						
				var areaChartData = {
				  labels  : meses,
				  datasets: [
					{
					  label               : 'PERMISOS',
					  backgroundColor     : 'rgba(210, 214, 222, 1)',
					  borderColor         : 'rgba(210, 214, 222, 1)',
					  pointRadius         : false,
					  pointColor          : 'rgba(210, 214, 222, 1)',
					  pointStrokeColor    : '#c1c7d1',
					  pointHighlightFill  : '#fff',
					  pointHighlightStroke: 'rgba(220,220,220,1)',
					  data                : cantidad
					}
				  ]
				}	  
				
				
				var barChartCanvas = $('#barChart').get(0).getContext('2d');
 		 
			 
			 
				var barChartData = jQuery.extend(true, {}, areaChartData)
				var temp0 = areaChartData.datasets[0]
				barChartData.datasets[0] = temp0

				var barChartOptions = {
				  responsive              : true,
				  maintainAspectRatio     : false,
				  datasetFill             : false			  
				}
		 	    
				var barChart = new Chart(barChartCanvas, {
				  type: 'bar', 
				  data: barChartData,
				  options: barChartOptions
				})
				
				var areaChartOptions = {
				  maintainAspectRatio : false,
				  responsive : true,
				  legend: {
					display: false
				  },
				  scales: {
					xAxes: [{
					  gridLines : {
						display : false,
					  }
					}],
					yAxes: [{
					  gridLines : {
						display : false,
					  }
					}]
				  }
				}				
				
				var areaChartCanvas = $('#areaChart').get(0).getContext('2d')
					var areaChart       = new Chart(areaChartCanvas, { 
					  type: 'line',
					  data: areaChartData, 
					  options: areaChartOptions
				})				

			
				
			}
		});		
			
	}		
	
});
</script>
</body>
</html>
