<?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" />  
  <style>
  #example{
	  font-size:10px;
  }
  .ui-timepicker-container {
      z-index: 3500 !important;
   }
   .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">
          <div class="col-sm-8">
            <h4>Justificaci&oacute;n Masiva</h4>
          </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">Autoriza</div>
				</div>
				<input type="text" class="form-control control-text" id="txtNombre_autoriza" value="<?php echo $_SESSION['LOGIN']['NOMBRE'] ?>" readonly>
				<input type="hidden" class="form-control control-text" id="txtId_autoriza" value="<?php echo $_SESSION['LOGIN']['CODIGO'] ?>">
			  </div>
			</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</div>
						</div>
						<input type="text" class="form-control" id="txtFecha" value="<?php echo 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">Sucursal</div>
						</div>
						<select class="form-control" id="txtSucursal"> </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">Seleccione...</option>
						</select>
					  </div>
					</div>	
					<div class="col-md-2">
						<button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>Procesar Elemento(s) Seleccionado(s)</button>
					</div>					
				</div>
            </div>
            <!-- /.card-header -->
            <div class="card-body">
              <table id="example" class="table table-bordered table-striped">
                <thead>
                <tr>	
                  <th>
					<input type="checkbox" class="btn btn-checkbox-todo">				  
				  </th>				
                  <th>RUT</th>				
                  <th>NOMBRE</th>	
                  <th>DEPARTAMENTO</th>					  
                  <th>TURNO</th>				
                  <th>CARGO</th>						  
                </tr>
                </thead>			
              </table>
			  <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 id="modal-confirma" class="modal" tabindex="-1" role="dialog">
	  <div class="modal-dialog modal-dialog-centered modal-lg" 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">
			<div class="row">
				<div class="col-md-6 text-center">
					<p>&iquest; Desea Procesar Listado ?<br /> Trabajadore(s) seleccionado(s) : (<label class="lblCantidad_trabajador"></label>)</p>
				</div>
				<div class="col-md-6">
				  <div class="form-group input-group-sm">
					<label>Tipo de Justificaci&oacute;n :</label>
					<select class="form-control" id="txtTipo_justificacion">
					</select>
					<small class="form-text text-muted">Tipo de Marcaje a Justificaci&oacute;n de Inasistencia .</small> 
				  </div>				
				  <div class="form-group d-none" id="div-hora-inicio">
					<label>Hora Inicio:</label>
					<input type="text" class="form-control control-text" id="txtHora_inicio" value="00:00" readonly>
					<small class="form-text text-muted">Hora Inicio Inasistencia.</small>
				  </div>	
				  <div class="form-group d-none" id="div-hora-termino">
					<label>Hora T&eacute;rmino:</label>
					<input type="text" class="form-control control-text" id="txtHora_termino" value="00:00" readonly>
					<small class="form-text text-muted">Hora T&eacute;rmino de Inasistencia.</small>
				  </div>	
				  <div class="form-group d-none" id="div-tipo-marcaje">
					<label>Tipo Marcaje :</label>
					<select class="form-control" id="txtTipo_marcaje">
						<option value="-1">Seleccione...</option>
					</select>
					<small class="form-text text-muted">Tipo de Marcaje a Justificar .</small>
				  </div>	
				  <div class="form-group">
					<label>Observaci&oacute;n:</label>
					<textarea class="form-control control-text" id="txtObservacion" rows="5">Justificaci&oacute;n Masiva</textarea>
					<small class="form-text text-muted">Observaci&oacute;nes de asignaci&oacute;n de Justificaci&oacute;n.</small>
				  </div>				  
				</div>
			</div>			
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
			<button type="button" class="btn btn-info" id="btn-confirmar">Confirmar</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/toastr/toastr.js"></script>
 
<link rel="stylesheet" href="../plugins/jQueryUI/jquery-ui.css" />
<script src="../plugins/jQueryUI/jquery-ui.js"></script>
<!-- JQUERY TIMEPICKER -->  
<script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>

<script>
  $(function () { 
  
	$("#txtTipo_justificacion").change(function () {
		if(parseInt($("#txtTipo_justificacion").val()) == 1){
			$("#div-hora-inicio").addClass("d-none"); 
			$("#div-hora-termino").addClass("d-none");
			$("#div-tipo-marcaje").addClass("d-none");
			$("#txtHora_inicio").val("00:00");
			$("#txtHora_termino").val("00:00");				
			$("#txtTipo_marcaje").val(-1);				
			
		}else{
			$("#div-hora-inicio").removeClass("d-none"); 
			$("#div-hora-termino").removeClass("d-none");
			$("#div-tipo-marcaje").removeClass("d-none");
		}
    });	   
  
	$('#txtHora_inicio').timepicker({ 
		timeFormat: 'HH:mm',
		interval: 30,
		minTime: '00:00',
		maxTime: '23:30',
		dynamic: false,
		dropdown: true,
		scrollbar: true		
	});	
 
	$('#txtHora_termino').timepicker({ 
		timeFormat: 'HH:mm',
		interval: 30,
		minTime: '00:00',
		maxTime: '23:30',
		dynamic: false,
		dropdown: true,
		scrollbar: true		
	});	
 
  
	 $.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").datepicker({
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		yearRange: "1900:2100",
		minDate: 0 
	 });	
	 
    $('#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: "<?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();
			}
		});	
		$.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/tipomarcaje",		
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtTipo_marcaje').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
			}
		});	
		$.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/tipojustificacion",		
			success: function(dados)
			{
				for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){
						$('#txtTipo_justificacion').append($('<option>', {
							value: dados[i][j].id,
							text : dados[i][j].descripcion
						}));
					}
				}
			}
		});			
	}

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

	function departamento(){
		$('#txtDepartamento').empty();	
		$.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();
    });	

	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/obtenerpersonadepartamento",
			data : JSON.stringify({
				id_departamento: $('#txtDepartamento').val(),								
			}),					
			success: function(dados)
			{
				 for (i=0;i<dados.length;i++){
					for (j=0;j<dados[i].length;j++){		

                      var campo = '<input type="checkbox" class="btn btn-checkbox">';
	
					  $('#example').dataTable().fnAddData( [
					    campo,
						dados[i][j].rut,	
						dados[i][j].nombre+" "+dados[i][j].apellido,
						dados[i][j].departamento,							
						dados[i][j].turno,	
						dados[i][j].cargo+ "<input type='hidden' value ='"+dados[i][j].id+"' />",
					  ]);
					}
				}
			}
		});

	}
	

	$(".btn-checkbox-todo").click(function(){	
		if($(this).is(":checked")){
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", true);
			}); 	
		}else{
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", false);
			}); 			
		}
	});
	
	
	$("#btnEnviar").click(function(){

		var contador = 0;
		jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
			if($(this).find("td:eq(0)").find('input[type="checkbox"]').is(":checked")){ contador++; }				 
		}); 
		if(contador > 0){
			$('#modal-confirma').modal("show");
			$(".lblCantidad").html($('#txtHora').val());
			$(".lblCantidad_trabajador").html(contador);		 
		}				 
		 				 	
	});
	
	$("#btn-confirmar").click(function(){
        $('#modal-confirma').modal("toggle");		
		var contador = 0;
        var cantidad_trabajador = parseInt($('.lblCantidad_trabajador').html());
		var i= 0;
		jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
			if($(this).find("td:eq(0)").find('input[type="checkbox"]').is(":checked")){ 
			    var id = $(this).find("td:eq(5)").find("input").val();
				$.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/ingresarjustificacion",
					data : JSON.stringify({
						fecha:$("#txtFecha").val(),
						hora_inicio:$("#txtHora_inicio").val(),
						hora_termino:$("#txtHora_termino").val(),	
                        id_tipo_justificacion:$("#txtTipo_justificacion").val(),						
						id_tipo_marcaje:$("#txtTipo_marcaje").val(),	
						id_persona:id,	
						id_autoriza:$("#txtId_autoriza").val(),	
						observacion:$("#txtObservacion").val()			
					}),
					success: function(data, textStatus, xhr) {
						if(parseInt(data[0]) > 0){ 
							contador++; i++;
							if(i == cantidad_trabajador) {
								toastr.success("Se han procesado : ("+contador+") Justificaciones de Inasistencias", "POWERTIME");	
							}							
						}			
					}
				})		 
			}
		}); 

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