<?php
	include("header.php");
	if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'superadmin') {
		
		} else {
		
		// If the user is not admin, redirect or show an error
        header("Location: login.php");
		exit();	
	}
	
?>
<div class="container-fluid mb-3">
	<div class="d-flex justify-content-between align-items-center mb-3">
		
		<div class="col-6"><h2 class="h3 m-0">All Page Visit Log</h2></div>
		
		<div class="col-6 text-right"> 
			<div>
				<label class="custom-toggle">
					<input type="checkbox" id="toggleIP" value="1">
					<span class="slider"></span>
					
				</label><span class="ml-2 font-weight-bold">Our IP</span>
			</div>
			<button id="refreshTable" class="btn btn-primary">
				<span id="refreshIcon" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
				Refresh Data
			</button>
			<button id="downloadAll" class="btn btn-success">
				<i class="fa fa-download"></i> Download All (CSV)
			</button>
			
			
		</div>
	</div>	
	
	<table id="pagevists" class="table table-striped">
		<thead>
			<tr>
				<th>ID</th>
				<th>Ip Address</th>
				<th>Admin Name</th>
				<th>User Type</th>
				<th>User Name</th>
				<th>Page Info</th>
				<th>Type</th>
				<th>Controller</th>
				<th>View</th>
				<th>Visit Time</th>
				
			</tr>
		</thead>
	</table>
</div>
<!-- DataTables & jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>


<script>
	$(document).ready(function() {
		$('#toggleIP').on('change', function () {
       table.ajax.reload(); // fetches new data with updated toggleIP param
		});
		var table =	$('#pagevists').DataTable({
			"processing": true,
			"serverSide": true,
			"ajax": {
				"url": "fetch_users_page_log.php",
				"type": "GET",
				"data": function (d) {
				// Send toggleIP value: 1 = checked, 2 = unchecked
				d.toggleIP = $('#toggleIP').is(':checked') ? 1 : 0;
			}
			},
			"columns": [
			{ "data": "id" },
			{ "data": "ip_address" },
			{ "data": "adminname" },
			{ "data": "usertype" },
			{ "data": "username" },
			{ "data": "pagename" },
			{ "data": "type" },
			{ "data": "controller" },
			{ "data": "view" },			
			{ "data": "created_at" }
			],
			"order": [[0, "desc"]]
		});
		
		$('#refreshTable').click(function() {
			var refreshIcon = $('#refreshIcon');
			
			// Show loading spinner
			refreshIcon.removeClass('d-none');
			
			// Reload DataTable
			table.ajax.reload(function() {
				// Hide spinner after reload completes
				refreshIcon.addClass('d-none');
			});
		});
		$('#downloadAll').click(function () {
    let toggle = $('#toggleIP').is(':checked') ? 1 : 0;
    window.location.href = 'download_users_pagelog.php?toggle=' + toggle;
});
	});
</script>

</body>
</html>