<!DOCTYPE html>
<html lang="en">


<?php $this->load->view("kepaladinas/header"); ?>

<body>

	<?php $this->load->view("kepaladinas/side_topbar"); ?>

	<div id="wrapper">
		<div class="main-content">
			<div class="row small-spacing">
				<div class="col-xs-12">
					<div class="box-content">
						<h4 class="box-title" id="header_peta">Peta Absensi</h4>

						<!-- /.dropdown js__dropdown -->
						<div class="form-group">
							<div id="map" style="width: 100%; height: 500px"></div>

						</div>
						<div class="form-group text-center" id="title_peta"></div>
						<!-- /#flot-chart-1.flot-chart -->
					</div>
					<!-- /.box-content -->
				</div>
				<!-- /.col-xs-12 -->

				<div class="col-xs-12">
					<div class="box-content">
						<h4 class="box-title" id="header_absensi">Absensi Pegawai</h4>

						<div class="card-content">
							<div style="overflow-x: auto">
								<table id="table_list_karyawan" class="table table-striped table-bordered display" style="width:100%">
									<thead>
										<tr>
											<th>NIP</th>
											<th>Nama</th>
											<th>Status</th>
											<th>Last Updated</th>
										</tr>
									</thead>
									<tbody>
										<?php
										foreach ($list_karyawan as $key => $value) {
										?>
											<tr>
												<td><?= $value->nik ?></td>
												<td><?= $value->nama ?></td>
												<td id="status_<?= $value->nik ?>"> <?= $value->status_kerja ?> </td>
												<td id="lu_<?= $value->nik ?>"> - </td>
											</tr>
										<?php
										}
										?>
									</tbody>
								</table>
							</div>
						</div>
					</div>
					<!-- /.box-content -->
				</div>
				<!-- /.col-xs-12 -->

			</div>
			<!-- /.row -->

			<?php $this->load->view('kepaladinas/footer') ?>

		</div>
		<!-- /.main-content -->
	</div>

	<?php $this->load->view('kepaladinas/scripts') ?>
	<script src="<?= base_url() ?>assets/plugin/datatables/media/js/jquery.dataTables.min.js"></script>
	<script src="<?= base_url() ?>assets/plugin/datatables/media/js/dataTables.bootstrap.min.js"></script>

	<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD7B9RynI4hQM_Y4BG9GYxsTLWwYkGASRo&libraries=geometry,drawing,places&v=weekly&region=ID&language=id"></script>

	<script>
		$('#table_list_karyawan').DataTable({

		})
		var id_dinas = <?= $id_dinas ?>;
		$("#header_peta").html(`Peta Absensi <i>(${getTodayDate()})</i>`)
		$("#header_absensi").html(`Absensi Pegawai <i>(${getTodayDate()})</i>`)

		let markersOverlay = [];

		function addInfoWindow(marker, message) {

			var infoWindow = new google.maps.InfoWindow({
				content: message
			});

			google.maps.event.addListener(marker, 'click', function() {
				infoWindow.open(map, marker);
			});
		}
		async function initMap() {
			map = new google.maps.Map(document.getElementById("map"), {
				zoom: 17.5,
				center: {
					lat: <?= $lat ?>,
					lng: <?= $lng ?>
				},
				mapTypeId: 'hybrid',
				streetViewControl: false,
			});

			const cityCircle = new google.maps.Circle({
				strokeColor: "#FF0000",
				strokeOpacity: 0.3,
				strokeWeight: 0.3,
				fillColor: "#FF0000",
				fillOpacity: 0.3,
				map,
				center: {
					lat: <?= $lat ?>,
					lng: <?= $lng ?>
				},
				radius: <?= $radius ?>,
			});

			const marker = new google.maps.Marker({
				position: {
					lat: <?= $lat ?>,
					lng: <?= $lng ?>
				},
				map: map,
				title: 'Center',
				icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
			});

			markersOverlay[0] = marker;

			let dinas_html = `<div class="card-content">
					<div class="form-group>
						<label for="nik"><?= $dinas ?></label>						
					</div>
				</div>`

			addInfoWindow(marker, dinas_html);

			setInterval(
				async function() {
					clearOverlays()
					markers = []
					markers = [{
						lat: <?= $lat ?>,
						lng: <?= $lng ?>

					}]
					let all_data;
					try {
						const the_data = await $.ajax({
							url: server_url_api + "get_today_absensi?id_dinas=" + id_dinas,
							type: 'get',
							async: false,
							beforeSend: function(res) {
								// block_ui("Mengambil Data Karyawan");
							},
						});
						// console.log(the_data);
						all_data = the_data.data;

						for (let i = 0; i < all_data.length; i++) {
							markers.push(all_data[i])
							// console.log(all_data)
						}

						let arr = []
						for (let i = 0; i < markers.length; i++) {
							console.log(markers[i]['lat'])
							let latlng = new google.maps.LatLng(markers[i]['lat'], markers[i]['lng']);
							arr.push(latlng);
							let color = i > 0 ? 'blue' : 'green'

							const marker = new google.maps.Marker({
								position: {
									lat: markers[i]['lat'],
									lng: markers[i]['lng']
								},
								map: map,
								title: 'Center',
								icon: `https://maps.google.com/mapfiles/ms/icons/${color}-dot.png`,
							});

							markersOverlay[i] = marker;
							if (i > 0) {
								let html = `<div class="card-content">
									<div class="form-group>
										<label for="nik">NIK</label>
										<input type="text" class="form-control" value="${markers[i]['nik']}" disabled>
									</div>
									<div class="form-group>
										<label for="nik">Nama</label>
										<input type="text" class="form-control" value="${markers[i]['nama']}" disabled>
									</div>
									<div class="form-group>
										<label for="nik">Last Updated</label>
										<input type="text" class="form-control" value="${markers[i]['last_updated']}" disabled>
									</div>
									<div class="form-group>
										<label for="nik">Status</label>
										<input type="text" class="form-control" value="${markers[i]['status']}" disabled>
									</div>
								</div>`
								$("#lu_" + markers[i]['nik']).html(markers[i]['last_updated']);
								$("#status_" + markers[i]['nik']).html(markers[i]['status']);
								addInfoWindow(marker, html);
							} else {
								addInfoWindow(marker, dinas_html);
							}
						}





						var bounds = new google.maps.LatLngBounds();

						if (markers.length > 1) {
							for (var i = 0; i < arr.length; i++) {
								bounds.extend(arr[i]);
							}
							map.fitBounds(bounds);

						}

					} catch (e) {
						console.log(e)
					}
				}, 5000)

		}
		google.maps.event.addDomListener(window, 'load', initMap);

		function clearOverlays() {
			if (markersOverlay) {
				for (i in markersOverlay) {
					markersOverlay[i].setMap(null);
				}
			}
		}


		function addMinutes(time, minutes) {
			return new Date(new Date('1970-01-01T' + time + 'Z').getTime() + minutes * 60000).toISOString().substr(11, 5);
		}

		async function check_data() {
			// console.log("selalu jalankan")
			// get current time
			const today = new Date();
			// chnage time to overall seconds
			let time = today.getHours() * 3600 + today.getMinutes() * 60 + today.getSeconds();

			let data
			try {
				// get today day name in id

				const day = today.toLocaleString('id-ID', {
					weekday: 'long'
				});
				// console.log(day)

				data = await $.ajax({
					url: server_url_api + "check_jadwal?hari=" + day + "&id_dinas=" + id_dinas,
					type: 'get',
					async: false,
					// beforeSend: function(res) {
					//   block_ui("Mengambil Data Informasi Libur");
					// },
				});
				data = data.data
				// console.log(data);
				// create  const jam_masuk and jam_pulang
				let jam_masuk = data.jam_masuk
				let jam_pulang = data.jam_pulang

				// add 30 minutes before jam_masuk
				// add 30 minutes after jam_pulang
				jam_masuk = addMinutes(jam_masuk, -30)
				jam_pulang = addMinutes(jam_pulang, 30)

				// get the overall seconds of jam_masuk and jam_pulang
				jam_masuk = jam_masuk.split(":")[0] * 3600 + jam_masuk.split(":")[1] * 60
				jam_pulang = jam_pulang.split(":")[0] * 3600 + jam_pulang.split(":")[1] * 60

				console.log("jam_masuk", jam_masuk)
				console.log("jam_pulang", jam_pulang)
				console.log("time", time)

				if (time >= jam_masuk && time <= jam_pulang) {
					$("#map").attr("hidden", false);
					$("#title_peta").attr("style", "display:none");
				} else {
					$("#map").attr("hidden", true);
					$("#title_peta").attr("style", "display:block");
					$("#title_peta").html("Peta tidak dapat ditampilkan saat ini, Diluar Jam Kerja");
				}




			} catch (error) {
				// await $.unblockUI();
				const statusCode = error.status;
				console.log(error)
				console.log(statusCode)
				$("#map").attr("hidden", true);
				$("#title_peta").attr("style", "display:block");
				$("#title_peta").html("Peta tidak dapat ditampilkan saat ini, Diluar Jam Kerja ");


			}

		}

		check_data()
		setInterval(
			check_data, 5000
		)
	</script>

</body>

<!-- Dibuat oleh Kicap Karan. https://www.kicap-karan.com -->

</html>