<?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">    
  <link href="../plugins/toastr/build/toastr.css" rel="stylesheet" type="text/css" />  
  <style>
  #example{
	  font-size:11px;
  }
  </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>Hora Extra Masiva</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">DataTables</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="row">
					<div class="col-md-4">
						<div class="form-group">
							<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'] ?>">
							<small class="form-text text-muted">Profesional que autoriza la hora extra.</small>
						</div>					
					</div>
				</div>
				<div class="row mt-2">
					<div class="col-md-4">
					  <div class="form-group">
						<select class="form-control" id="txtSucursal">
						</select>
						<small class="form-text text-muted">Seleccione Sucursal..</small>
					  </div>						
					</div>
					<div class="col-md-4">
					  <div class="form-group">
						<select class="form-control" id="txtDepartamento">
							<option value="0">Seleccione...</option>
						</select>
						<small class="form-text text-muted">Seleccione departamento.</small>
					  </div>						
					</div>	
					<div class="col-md-4">
					  <div class="form-group">
						<input type="text" class="form-control" id="txtFecha" value="<?php echo date("Y-m-d"); ?>" readonly>
						<small class="form-text text-muted">Fecha ejecuci&oacute;n Hora Extra.</small>
					  </div>						
					</div>
				</div>
            </div>
            <!-- /.card-header -->
            <div class="card-body">
			  <button type='button' class='btn btn-info btn-sm' id='btnEnviar' name='btnEnviar'>PROCESAR ELEMENTOS SELECCIONADOS</button>
              <table id="example" class="table table-bordered table-striped">
                <thead>
                <tr>	
                  <th class="col-md-2">
					   <div class="input-group">
						   <div class="input-group-prepend">
							   <span class="input-group-text">
								<input type="checkbox" class="btn btn-checkbox-todo">
							   </span>
						   </div>
						   <input type="text" class="form-control" class="txtHora" id="txtHora" name="txtHora" disabled>
					   </div>				  
				  </th>				
                  <th>RUT</th>				
                  <th>NOMBRE</th>	
                  <th>TELEFONO</th>				
                  <th>E-MAIL</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" 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 Procesar Listado de Hora Extra M&aacute;siva ?<br />
			Al momento de procesar se asignar&aacute;n (<label class="lblCantidad"></label>) Hora(s) extras a cada trabajador seleccionado</p>
			
		  </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>
<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").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,
    });
	
	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();
			}
		});				
	}

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

	function departamento(){
		$('#txtDepartamento').empty();	
		$.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
						}));
					}
				}
				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: "http://200.24.13.60/~program1/power-time-api/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 = '<div class="input-group">';
						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 += '<input type="text" class="form-control" class="txtHora" disabled>';
						campo += '</div>';
					
					  $('#example').dataTable().fnAddData( [
					    campo,
						dados[i][j].rut,	
						dados[i][j].nombre,
						dados[i][j].telefono,	
						dados[i][j].email+ "<input type='hidden' value ='"+dados[i][j].id+"' />",
					  ]);
					}
				}
			}
		});

	}
	
	$("#txtHora").bind('keypress', function(event) {
	  var regex = new RegExp("^[0-9]+$");
	  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
	  if (!regex.test(key)) {
		event.preventDefault();
		return false;
	  }
	});	  	
	
	$(".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);
				$(this).find("td:eq(0)").find("input").val(2);
				$("#txtHora").attr("disabled", false);
				$("#txtHora").val(2);
				$('#txtHora').focus();
				//alert($(this).find("td:eq(0)").find('input[type="checkbox"]').prop('checked') +" -- "+$(this).find("td:eq(1)").html());
			}); 	
		}else{
			jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
				$(this).find("td:eq(0)").find('input[type="checkbox"]').attr("checked", false);
				$(this).find("td:eq(0)").find("input").val("");
				$("#txtHora").attr("disabled", true);
				$("#txtHora").val("");
			}); 			
		}
	});
	
	$('#txtHora').keyup(function(e){
		if(e.keyCode == 13){
			 if(!$('#txtHora').val() || /^\s*$/.test($('#txtHora').val())){
				 toastr.warning("Debe Ingresar Cantidad de Horas Extras", "POWERTIME");
				 return false;
			 }else if (parseInt($('#txtHora').val()) <= 0 || parseInt($('#txtHora').val()) > 8){
				 toastr.warning("Ingrese Cantidad de Horas Mayor a 0 y Menor de 8", "POWERTIME");
				 return false;				 
			 }else{
				 jQuery($('#example').dataTable().fnGetNodes()).each(function () { 
					$(this).find("td:eq(0)").find("input").val($('#txtHora').val());
				 }); 				 
				 $('#modal-confirma').modal("show");
				 $(".lblCantidad").html($('#txtHora').val());
			 }
		}
	});		
	
   $("#example").on('click','.btn-checkbox', function() {
         var id = $(this).parents("tr").find("td:eq(4)").find("input").val();
 
		 if($(this).is(":checked")){
            $(this).parents("tr").find("td:eq(0)").find("input").val(2);	

			$.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/ingresarhoraextra",
				data : JSON.stringify({
					fecha:$("#txtFecha").val(),
					cantidad:$(this).parents("tr").find("td:eq(0)").find("input").val(),		
					id_persona:id,	
					id_autoriza:$("#txtId_autoriza").val(),	
					observacion:"Hora Extra Masiva"				
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Registro Ingresado Exitosamente", "POWERTIME");
					}
					if(parseInt(xhr.status) == 304){
						toastr.success("Trabajador cuenta con hora extra asigana en fecha : "+$("#txtFecha").val(), "POWERTIME");
					}					
				}
			})
			
		 }else{
            $(this).parents("tr").find("td:eq(0)").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/eliminarhoraextratrabajador",
				data : JSON.stringify({
					fecha:$("#txtFecha").val(),	
					id_persona:id			
				}),
				success: function(data, textStatus, xhr) {
					if(parseInt(xhr.status) == 201){
						toastr.success("Registro Eliminado Exitosamente", "POWERTIME");
					}
				}
			})			
		 }
		 
		 
    });	
	
});
</script>
</body>
</html>
