<?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" />     
  <style>
	  #example{
		  font-size:10px;
	  }
      .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 mb-1">
          <div class="col-sm-6">
            <h4>Listado Trabajadores</h4>
          </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">Listado Trabajadores</li>
            </ol>
          </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="form-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"> </select>
					  </div>
					</div>		
					<div class="col-md-2">
					  <div class="input-group mb-2 input-group-sm">
						<button type='button' class='btn btn-default btn-sm' id='btnLimpiar' name='btnLimpiar'>LIMPIAR</button>
					  </div>
					</div>							
				</div>	
				  <div class="form-row align-items-center">
					<div class="col-md-4">
					  <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-4">
					  <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-2">
					  <button type="button" class="btn btn-danger mb-2 btn-sm" id="btnInforme">Informe PDF</button>
					</div>					
				  </div>				
            </div>
            <!-- /.card-header -->
            <div class="card-body">
				<ul class="nav nav-pills ml-auto p-2" id="menu-turno">
				  <li class="nav-item">
					<a class="nav-link nav-depto active" href="#dpto" data-toggle="tab">Departamento</a>
				  </li>
				  <li class="nav-item">
					<a class="nav-link nav-persona" href="#persona" data-toggle="tab">Persona</a>
				  </li>						  
				</ul>	
				
				<div class="row">
				<div class="col-md-6">
					<div class="tab-content p-0">
						<div class="tab-pane active" id="dpto">		
						  <table id="example2" class="table table-bordered table-striped">
							<thead>
							<tr>	
							  <th>
							   <div class="input-group input-group-sm">
								   <div class="input-group-prepend">
									   <span class="input-group-text">
										<input type="checkbox" class="btn btn-checkbox-todo">
									   </span>
								   </div>
							   </div>				  
							  </th>						
							  <th>SUCURSAL</th>								  				  
							</tr>
							</thead>			
						  </table>									
						</div>
						<div class="tab-pane" id="persona">	
						  <table id="example" class="table table-bordered table-striped">
							<thead>
							<tr>	
							  <th>
							   <div class="input-group input-group-sm">
								   <div class="input-group-prepend">
									   <span class="input-group-text">
										<input type="checkbox" class="btn btn-checkbox-todo2">
									   </span>
								   </div>
							   </div>				  
							  </th>							
							  <th>RUT</th>				
							  <th>NOMBRE</th>	
							  <th>TURNO</th>				
							  <th>CARGO</th>					  				  
							</tr>
							</thead>			
						  </table>								
						</div>				
					</div>	  				
				</div>	

				<div class="col-md-6">
				  <table id="example3" class="table table-bordered table-striped">
					<thead>
					<tr>							
					  <th>RUT</th>				
					  <th>NOMBRE</th>
					  <th></th>					  
					  <!--<th>TURNO</th>				
					  <th>CARGO</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 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-informe">
        <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 class="modal" tabindex="-1" role="dialog"  id="modal-default2">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">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 text-center">
		<div id="mensajeUsuario"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-info btn-sm" id="btnAceptar">Aceptar</button>	  
        <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>
  $(function () { 
  
    $(".modal-body-informe").height(parseInt(screen.height) -400);  
  
	 $.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() 
	 })   
  
    $('#example').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": true,
      "ordering": false,
      "info": false,
      "autoWidth": false,
	  "pageLength": 7,	  
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      } 	
    });
	
    $('#example2').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": true,
      "ordering": false,
      "info": false,
      "autoWidth": false,
	  "pageLength": 7,
	  "language": {
		"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"
      } 	
    });	
	
    $('#example3').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": true,
      "ordering": false,
      "info": false,
      "autoWidth": false,
	  "pageLength": 7,
	  "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();
			}
		});				
	}
	
	$("#btnLimpiar").click(function(){
		combo();
        $('#example').dataTable().fnClearTable();	
		$('#example2').dataTable().fnClearTable();
		$('#example3').dataTable().fnClearTable();	

	    $('#persona').removeClass('active'); 
	    $('#dpto').addClass('active'); 
		
	    $('.nav-persona').removeClass('active'); 
	    $('.nav-depto').addClass('active'); 	

		$("#txtFecha_inicio").val(fechaActual());
		$("#txtFecha_termino").val(fechaActual());			
	});
	
 
	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;  		
	}	
		

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

	function departamento(){
        $('#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/obtenerdepartamentosucursal",
			data : JSON.stringify({
				id_sucursal: $('#txtSucursal').val(),								
			}),			
			success: function(dados)
			{
				$('#example2').dataTable().fnClearTable();
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						
						var campo = '<div class="input-group  input-group-sm">';
							campo += '<div class="input-group-prepend">';
							campo += '<span class="input-group-text">';
							campo += '<input type="checkbox" class="btn btn-checkbox">';
							campo += '</span>';
							campo += '</div>';
							campo += '</div>';
							
						  $('#example2').dataTable().fnAddData( [
							campo,
							dados[i][j].descripcion+ "<input type='hidden' value ='"+dados[i][j].id+"' />",,						
						  ]);
					}
				}
			}
		});			
	}

	$(".btn-checkbox-todo").click(function(){
        $('#example').dataTable().fnClearTable();		
		if($(this).is(":checked")){
			jQuery($('#example2').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", true);
				listarRegistro($(this).find("td:eq(1)").find("input").val());
			}); 	
		}else{
			jQuery($('#example2').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", false);
			}); 			
		}
	});	
	
    $("#example2").on('click','.btn-checkbox', function() {
         if($(this).is(":checked")){
			var id = $(this).parents("tr").find("td:eq(1)").find("input").val();
			listarRegistro(id);
		 }
		 
    });	
	
	function listarRegistro(id_departamento){
		
	    $('#dpto').removeClass('active'); 
	    $('#persona').addClass('active'); 
		
	    $('.nav-depto').removeClass('active'); 
	    $('.nav-persona').addClass('active'); 		
		

		$.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: id_departamento,								
			}),		
			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-xs btn-editar'>Ver Marcajes</button>";					  
					  var cargo = dados[i][j].cargo;
					  if(dados[i][j].cargo == null) { cargo = "NO ASIGNADO"; }
					  
						var campo = '<div class="input-group  input-group-sm">';
							campo += '<div class="input-group-prepend">';
							campo += '<span class="input-group-text">';
							campo += '<input type="checkbox" class="btn btn-checkbox">';
							campo += '</span>';
							campo += '</div>';
							campo += '</div>';			

						  var existe = false; 
						  jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
							 if($(this).find("td:eq(4)").find("input").val() == dados[i][j].id){ existe = true;}
						  }); 								
					      if(!existe){
							  $('#example').dataTable().fnAddData( [
								campo,
								dados[i][j].rut,	
								dados[i][j].nombre +" "+dados[i][j].apellido,
								dados[i][j].turno,
								cargo + "<input type='hidden' value ='"+dados[i][j].id+"' />"						
							  ]);
						  }
					}
				}
			}
		});

	}
	
    $("#example").on('click','.btn-checkbox', function() {
         if($(this).is(":checked")){
			obtenerTrabajador($(this).parents("tr").find("td:eq(4)").find("input").val());
		 }		 
    });	
	
	$(".btn-checkbox-todo2").click(function(){	
		if($(this).is(":checked")){
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(4)").find('input[type="checkbox"]').attr("checked", true);
				obtenerTrabajador($(this).find("td:eq(4)").find("input").val());
			}); 	
		}else{
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(4)").find('input[type="checkbox"]').attr("checked", false);
			}); 			
		}
	});		
	
	function obtenerTrabajador(idTrabajador){
		
		var existe = false; 
		jQuery($('#example3').dataTable().fnGetNodes()).each(function () { 
			if($(this).find("td:eq(2)").find("input").val() == idTrabajador){ existe = true;}
		}); 					 				 
		if(!existe) {
		$.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: idTrabajador,								
			}),		
			success: function(dados)
			{				
				 for (i=0;i<dados.length;i++){
				  var boton = "<button type='button' class='btn btn-info btn-xs btn-excluir'>Excluir</button>";	 
				  $('#example3').dataTable().fnAddData( [
					dados[i].rut,	
					dados[i].nombre +" "+dados[i].apellido,
					boton+ "<input type='hidden' value ='"+dados[i].id+"' />",					
				  ]);						 				
				}
			}
		});				
		}						
			
	}
	
	var parent;
	$("#example3").on('click','.btn-excluir', function() {
		$("#btnAceptar").removeClass("d-none");
		
		$("#mensajeUsuario").html("&iquest; Desea Excluir de informe a : ? <br />" + $(this).parents("tr").find("td:eq(1)").html());
		$('#modal-default2').modal('show');
        parent = $(this).parents("tr");		
	});

	$("#btnAceptar").click(function(){
        $('#example3').dataTable().fnDeleteRow( parent, null, true );		
		$('#modal-default2').modal('toggle');
	});
	
	
	$("#btnInforme").click(function(){
		
		$("#btnAceptar").addClass("d-none");
		
		if($('#example3').dataTable().fnGetData().length > 0){
            var lista = [];
			jQuery($('#example3').dataTable().fnGetNodes()).each(function () { lista.push($(this).find("td:eq(0)").html()); });	
			
						
			$('.div-response').html('<form action="exportar.listado.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="hidden" class="form-control control-number" id="txtListado" name="txtListado" value="'+lista+'" >'+		
			'</form>');			
			document.forms['form'].submit();
			$('#modal-default').modal('show');
            			
		}else{
			$("#mensajeUsuario").html("Debe Seleccionar Trabajadores a generar Informe");
			$('#modal-default2').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();		 
	});		

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