<?php 
session_start();
include('includes/head.php');

// Get filter parameters
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$filter_admin = isset($_GET['admin']) ? $_GET['admin'] : '';
$filter_role = isset($_GET['role']) ? $_GET['role'] : '';
$filter_module = isset($_GET['module']) ? $_GET['module'] : '';
$filter_action = isset($_GET['action']) ? $_GET['action'] : '';
$filter_ip = isset($_GET['ip']) ? $_GET['ip'] : '';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Get unique values for filters
$admin_sql = "SELECT DISTINCT admin_name FROM admin_activities ORDER BY admin_name";
$admin_result = mysqli_query($conn, $admin_sql);

$role_sql = "SELECT DISTINCT admin_role FROM admin_activities ORDER BY admin_role";
$role_result = mysqli_query($conn, $role_sql);

$module_sql = "SELECT DISTINCT module FROM admin_activities WHERE module IS NOT NULL ORDER BY module";
$module_result = mysqli_query($conn, $module_sql);

$action_sql = "SELECT DISTINCT action FROM admin_activities ORDER BY action";
$action_result = mysqli_query($conn, $action_sql);

// Build query
$sql = "SELECT * FROM admin_activities WHERE 1=1";
$count_sql = "SELECT COUNT(*) as total FROM admin_activities WHERE 1=1";

// Apply filters
if ($filter_date_from && $filter_date_to) {
    $sql .= " AND DATE(created_at) BETWEEN '$filter_date_from' AND '$filter_date_to'";
    $count_sql .= " AND DATE(created_at) BETWEEN '$filter_date_from' AND '$filter_date_to'";
} elseif ($filter_date_from) {
    $sql .= " AND DATE(created_at) >= '$filter_date_from'";
    $count_sql .= " AND DATE(created_at) >= '$filter_date_from'";
} elseif ($filter_date_to) {
    $sql .= " AND DATE(created_at) <= '$filter_date_to'";
    $count_sql .= " AND DATE(created_at) <= '$filter_date_to'";
}

if ($filter_admin) {
    $sql .= " AND admin_name LIKE '%$filter_admin%'";
    $count_sql .= " AND admin_name LIKE '%$filter_admin%'";
}

if ($filter_role) {
    $sql .= " AND admin_role = '$filter_role'";
    $count_sql .= " AND admin_role = '$filter_role'";
}

if ($filter_module) {
    $sql .= " AND module = '$filter_module'";
    $count_sql .= " AND module = '$filter_module'";
}

if ($filter_action) {
    $sql .= " AND action LIKE '%$filter_action%'";
    $count_sql .= " AND action LIKE '%$filter_action%'";
}

if ($filter_ip) {
    $sql .= " AND ip_address LIKE '%$filter_ip%'";
    $count_sql .= " AND ip_address LIKE '%$filter_ip%'";
}

// Get total count
$count_result = mysqli_query($conn, $count_sql);
$count_row = mysqli_fetch_assoc($count_result);
$total_records = $count_row['total'];
$total_pages = ceil($total_records / $limit);

// Add sorting and pagination
$sql .= " ORDER BY created_at DESC LIMIT $limit OFFSET $offset";

// Execute query
$result = mysqli_query($conn, $sql);

// Get summary statistics
$summary_sql = "SELECT 
    COUNT(*) as total_activities,
    COUNT(DISTINCT admin_name) as unique_admins,
    COUNT(DISTINCT module) as unique_modules,
    COUNT(DISTINCT action) as unique_actions,
    MIN(created_at) as first_activity,
    MAX(created_at) as last_activity
    FROM admin_activities WHERE 1=1";

// Apply same filters to summary
if ($filter_date_from && $filter_date_to) {
    $summary_sql .= " AND DATE(created_at) BETWEEN '$filter_date_from' AND '$filter_date_to'";
} elseif ($filter_date_from) {
    $summary_sql .= " AND DATE(created_at) >= '$filter_date_from'";
} elseif ($filter_date_to) {
    $summary_sql .= " AND DATE(created_at) <= '$filter_date_to'";
}

if ($filter_admin) {
    $summary_sql .= " AND admin_name LIKE '%$filter_admin%'";
}

if ($filter_role) {
    $summary_sql .= " AND admin_role = '$filter_role'";
}

if ($filter_module) {
    $summary_sql .= " AND module = '$filter_module'";
}

if ($filter_action) {
    $summary_sql .= " AND action LIKE '%$filter_action%'";
}

if ($filter_ip) {
    $summary_sql .= " AND ip_address LIKE '%$filter_ip%'";
}

$summary_result = mysqli_query($conn, $summary_sql);
$summary = mysqli_fetch_assoc($summary_result);

// Role badge colors
$role_colors = array(
    'super_admin' => 'danger',
    'admin' => 'primary',
    'support' => 'info'
);
?>

<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-history me-2"></i>Activity Report</h4>
										<div class="box-controls pull-right">
											<div class="dropdown">
												<button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
													<i class="fas fa-download me-1"></i> Export Report
												</button>
												<div class="dropdown-menu">
													<a class="dropdown-item" href="export_activity_report.php?format=csv&<?php echo http_build_query($_GET); ?>">
														<i class="fas fa-file-csv"></i> CSV
													</a>
													<a class="dropdown-item" href="export_activity_report.php?format=excel&<?php echo http_build_query($_GET); ?>">
														<i class="fas fa-file-excel"></i> Excel
													</a>
													<a class="dropdown-item" href="export_activity_report.php?format=pdf&<?php echo http_build_query($_GET); ?>">
														<i class="fas fa-file-pdf"></i> PDF
													</a>
												</div>
											</div>
										</div>
									</div>
									<div class="box-body">
										<!-- Summary Stats -->
										<div class="row mb-20">
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h1 class="fw-500 text-primary"><?php echo number_format($summary['total_activities']); ?></h1>
														<p class="text-mute mb-0">Total Activities</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h1 class="fw-500 text-success"><?php echo number_format($summary['unique_admins']); ?></h1>
														<p class="text-mute mb-0">Unique Admins</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h1 class="fw-500 text-warning"><?php echo number_format($summary['unique_modules']); ?></h1>
														<p class="text-mute mb-0">Modules</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h1 class="fw-500 text-info"><?php echo number_format($summary['unique_actions']); ?></h1>
														<p class="text-mute mb-0">Action Types</p>
													</div>
												</div>
											</div>
											<div class="col-xl-4 col-md-8 col-12">
												<div class="box bg-light">
													<div class="box-body">
														<div class="row">
															<div class="col-6">
																<p class="mb-1"><strong>First Activity:</strong></p>
																<p class="mb-1"><strong>Last Activity:</strong></p>
															</div>
															<div class="col-6">
																<p class="mb-1"><?php echo $summary['first_activity'] ? date('M d, Y H:i', strtotime($summary['first_activity'])) : 'N/A'; ?></p>
																<p class="mb-0"><?php echo $summary['last_activity'] ? date('M d, Y H:i', strtotime($summary['last_activity'])) : 'N/A'; ?></p>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="box bg-light mb-20">
											<div class="box-body">
												<form method="GET" class="row">
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $filter_date_from; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $filter_date_to; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">Admin Name</label>
															<select class="form-control select2" name="admin">
																<option value="">All Admins</option>
																<?php while ($admin = mysqli_fetch_assoc($admin_result)): ?>
																	<option value="<?php echo $admin['admin_name']; ?>" <?php echo $filter_admin == $admin['admin_name'] ? 'selected' : ''; ?>>
																		<?php echo htmlspecialchars($admin['admin_name']); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">Admin Role</label>
															<select class="form-control" name="role">
																<option value="">All Roles</option>
																<?php while ($role = mysqli_fetch_assoc($role_result)): ?>
																	<option value="<?php echo $role['admin_role']; ?>" <?php echo $filter_role == $role['admin_role'] ? 'selected' : ''; ?>>
																		<?php echo ucfirst(str_replace('_', ' ', $role['admin_role'])); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">Module</label>
															<select class="form-control" name="module">
																<option value="">All Modules</option>
																<?php mysqli_data_seek($module_result, 0); ?>
																<?php while ($module = mysqli_fetch_assoc($module_result)): ?>
																	<option value="<?php echo $module['module']; ?>" <?php echo $filter_module == $module['module'] ? 'selected' : ''; ?>>
																		<?php echo htmlspecialchars($module['module']); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">Action Type</label>
															<select class="form-control" name="action">
																<option value="">All Actions</option>
																<?php mysqli_data_seek($action_result, 0); ?>
																<?php while ($action = mysqli_fetch_assoc($action_result)): ?>
																	<option value="<?php echo $action['action']; ?>" <?php echo $filter_action == $action['action'] ? 'selected' : ''; ?>>
																		<?php echo htmlspecialchars($action['action']); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">IP Address</label>
															<input type="text" class="form-control" name="ip" placeholder="Search IP..." value="<?php echo htmlspecialchars($filter_ip); ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="mb-3">
															<label class="form-label">&nbsp;</label>
															<div class="d-flex">
																<button type="submit" class="btn btn-primary me-2">
																	<i class="fas fa-filter me-1"></i> Filter
																</button>
																<a href="activity_report.php" class="btn btn-secondary">
																	<i class="fas fa-redo me-1"></i> Reset
																</a>
															</div>
														</div>
													</div>
												</form>
											</div>
										</div>
										
										<!-- Activities Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="activitiesTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>Admin</th>
														<th>Role</th>
														<th>Action</th>
														<th>Description</th>
														<th>Module</th>
														<th>Affected ID</th>
														<th>IP Address</th>
														<th>Timestamp</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($activity = mysqli_fetch_assoc($result)): ?>
															<?php
															$role_color = isset($role_colors[$activity['admin_role']]) ? $role_colors[$activity['admin_role']] : 'secondary';
															$timestamp = date('Y-m-d H:i:s', strtotime($activity['created_at']));
															$time_ago = time_ago($activity['created_at']);
															?>
															<tr>
																<td><?php echo $activity['id']; ?></td>
																<td>
																	<div class="d-flex align-items-center">
																		<div class="me-10">
																			<div class="bg-<?php echo $role_color; ?> rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																				<i class="fas fa-user-shield text-white"></i>
																			</div>
																		</div>
																		<div>
																			<p class="mb-0 fw-500"><?php echo htmlspecialchars($activity['admin_name']); ?></p>
																			<small class="text-mute">ID: <?php echo $activity['admin_id']; ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<span class="badge bg-<?php echo $role_color; ?>">
																		<?php echo ucfirst(str_replace('_', ' ', $activity['admin_role'])); ?>
																	</span>
																</td>
																<td>
																	<span class="badge bg-light text-dark"><?php echo htmlspecialchars($activity['action']); ?></span>
																</td>
																<td>
																	<p class="mb-0"><?php echo htmlspecialchars($activity['description']); ?></p>
																	<?php if ($activity['affected_table']): ?>
																		<small class="text-mute">Table: <?php echo $activity['affected_table']; ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<?php if ($activity['module']): ?>
																		<span class="badge bg-secondary"><?php echo htmlspecialchars($activity['module']); ?></span>
																	<?php else: ?>
																		<span class="text-mute">-</span>
																	<?php endif; ?>
																</td>
																<td>
																	<?php if ($activity['affected_id']): ?>
																		<span class="badge bg-info">#<?php echo $activity['affected_id']; ?></span>
																	<?php else: ?>
																		<span class="text-mute">-</span>
																	<?php endif; ?>
																</td>
																<td>
																	<code><?php echo htmlspecialchars($activity['ip_address']); ?></code>
																</td>
																<td>
																	<p class="mb-0"><?php echo $timestamp; ?></p>
																	<small class="text-mute"><?php echo $time_ago; ?> ago</small>
																</td>
																<td>
																	<button class="btn btn-sm btn-light" onclick="viewActivityDetails(<?php echo $activity['id']; ?>)">
																		<i class="fas fa-eye"></i>
																	</button>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="10" class="text-center py-20">
																<i class="fas fa-history fa-2x text-mute mb-3"></i>
																<h5>No activities found</h5>
																<p class="text-mute">Try adjusting your filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Pagination -->
										<?php if ($total_pages > 1): ?>
											<div class="row mt-20">
												<div class="col-sm-12 col-md-5">
													<div class="dataTables_info">
														Showing <?php echo min($offset + 1, $total_records); ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo number_format($total_records); ?> entries
													</div>
												</div>
												<div class="col-sm-12 col-md-7">
													<nav aria-label="Page navigation">
														<ul class="pagination justify-content-end">
															<li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
																<a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $page - 1))); ?>" aria-label="Previous">
																	<span aria-hidden="true">&laquo;</span>
																</a>
															</li>
															
															<?php for ($i = 1; $i <= $total_pages; $i++): ?>
																<?php if ($i == $page || $i == 1 || $i == $total_pages || ($i >= $page - 2 && $i <= $page + 2)): ?>
																	<li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
																		<a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $i))); ?>">
																			<?php echo $i; ?>
																		</a>
																	</li>
																<?php elseif ($i == $page - 3 || $i == $page + 3): ?>
																	<li class="page-item disabled">
																		<span class="page-link">...</span>
																	</li>
																<?php endif; ?>
															<?php endfor; ?>
															
															<li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
																<a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $page + 1))); ?>" aria-label="Next">
																	<span aria-hidden="true">&raquo;</span>
																</a>
															</li>
														</ul>
													</nav>
												</div>
											</div>
										<?php endif; ?>
									</div>
								</div>
							</div>
						</div>
						
						<!-- Charts Row -->
						<div class="row">
							<div class="col-xl-6 col-lg-6">
								<div class="box">
									<div class="box-header">
										<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Activities by Admin Role</h5>
									</div>
									<div class="box-body">
										<div id="roleChart" style="height: 300px;"></div>
									</div>
								</div>
							</div>
							<div class="col-xl-6 col-lg-6">
								<div class="box">
									<div class="box-header">
										<h5 class="box-title"><i class="fas fa-chart-pie me-2"></i>Activities by Module</h5>
									</div>
									<div class="box-body">
										<div id="moduleChart" style="height: 300px;"></div>
									</div>
								</div>
							</div>
						</div>
						
						<!-- Top Admins Row -->
						<div class="row">
							<div class="col-xl-6 col-lg-6">
								<div class="box">
									<div class="box-header">
										<h5 class="box-title"><i class="fas fa-trophy me-2"></i>Top 10 Most Active Admins</h5>
									</div>
									<div class="box-body p-0">
										<div class="table-responsive">
											<table class="table table-hover mb-0">
												<thead>
													<tr>
														<th>Rank</th>
														<th>Admin</th>
														<th>Role</th>
														<th>Activities</th>
														<th>Last Activity</th>
													</tr>
												</thead>
												<tbody>
													<?php
													$top_admins_sql = "SELECT 
														admin_id, admin_name, admin_role, 
														COUNT(*) as activity_count,
														MAX(created_at) as last_activity
														FROM admin_activities 
														GROUP BY admin_id, admin_name, admin_role 
														ORDER BY activity_count DESC 
														LIMIT 10";
													$top_admins_result = mysqli_query($conn, $top_admins_sql);
													$rank = 1;
													
													while ($admin = mysqli_fetch_assoc($top_admins_result)):
														$role_color = isset($role_colors[$admin['admin_role']]) ? $role_colors[$admin['admin_role']] : 'secondary';
													?>
														<tr>
															<td>
																<span class="badge bg-primary rounded-circle w-30 h-30 d-inline-flex align-items-center justify-content-center">
																	<?php echo $rank++; ?>
																</span>
															</td>
															<td><?php echo htmlspecialchars($admin['admin_name']); ?></td>
															<td><span class="badge bg-<?php echo $role_color; ?>"><?php echo ucfirst(str_replace('_', ' ', $admin['admin_role'])); ?></span></td>
															<td><span class="fw-500"><?php echo number_format($admin['activity_count']); ?></span></td>
															<td><?php echo date('M d, H:i', strtotime($admin['last_activity'])); ?></td>
														</tr>
													<?php endwhile; ?>
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>
							
							<div class="col-xl-6 col-lg-6">
								<div class="box">
									<div class="box-header">
										<h5 class="box-title"><i class="fas fa-clock me-2"></i>Recent Hourly Activity</h5>
									</div>
									<div class="box-body">
										<div id="hourlyChart" style="height: 300px;"></div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Activity Details -->
		<div class="modal fade" id="activityModal" tabindex="-1" aria-labelledby="activityModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="activityModalLabel">Activity Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="activityDetails">
						<!-- Details will be loaded via AJAX -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- Apex Charts -->
		<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
		
		<!-- Select2 -->
		<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
		<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#activitiesTable').DataTable({
				"pageLength": 50,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Initialize Select2
			$('.select2').select2({
				placeholder: "Select Admin",
				allowClear: true
			});
			
			// Load charts
			loadRoleChart();
			loadModuleChart();
			loadHourlyChart();
		});
		
		// View Activity Details
		function viewActivityDetails(activityId) {
			$.ajax({
				url: 'ajax/get_activity_details.php',
				type: 'GET',
				data: { id: activityId },
				success: function(data) {
					$('#activityDetails').html(data);
					$('#activityModal').modal('show');
				}
			});
		}
		
		// Load Role Distribution Chart
		function loadRoleChart() {
			$.ajax({
				url: 'ajax/get_activity_chart_data.php',
				type: 'GET',
				data: { chart: 'role_distribution' },
				dataType: 'json',
				success: function(data) {
					if (data.success) {
						var options = {
							series: data.series,
							chart: {
								type: 'bar',
								height: 300,
								toolbar: {
									show: false
								}
							},
							colors: ['#667eea', '#f093fb', '#4facfe'],
							plotOptions: {
								bar: {
									horizontal: false,
									columnWidth: '55%',
									endingShape: 'rounded'
								},
							},
							dataLabels: {
								enabled: false
							},
							xaxis: {
								categories: data.labels,
							},
							yaxis: {
								title: {
									text: 'Number of Activities'
								}
							},
							legend: {
								position: 'top'
							}
						};
						
						var chart = new ApexCharts(document.querySelector("#roleChart"), options);
						chart.render();
					}
				}
			});
		}
		
		// Load Module Distribution Chart
		function loadModuleChart() {
			$.ajax({
				url: 'ajax/get_activity_chart_data.php',
				type: 'GET',
				data: { chart: 'module_distribution' },
				dataType: 'json',
				success: function(data) {
					if (data.success) {
						var options = {
							series: data.series,
							chart: {
								type: 'donut',
								height: 300
							},
							labels: data.labels,
							colors: ['#667eea', '#f093fb', '#4facfe', '#43e97b', '#fa709a', '#30cfd0'],
							legend: {
								position: 'bottom'
							},
							responsive: [{
								breakpoint: 480,
								options: {
									chart: {
										width: 200
									},
									legend: {
										position: 'bottom'
									}
								}
							}]
						};
						
						var chart = new ApexCharts(document.querySelector("#moduleChart"), options);
						chart.render();
					}
				}
			});
		}
		
		// Load Hourly Activity Chart
		function loadHourlyChart() {
			$.ajax({
				url: 'ajax/get_activity_chart_data.php',
				type: 'GET',
				data: { chart: 'hourly_activity' },
				dataType: 'json',
				success: function(data) {
					if (data.success) {
						var options = {
							series: [{
								name: 'Activities',
								data: data.data
							}],
							chart: {
								type: 'area',
								height: 300,
								toolbar: {
									show: false
								}
							},
							colors: ['#667eea'],
							dataLabels: {
								enabled: false
							},
							stroke: {
								curve: 'smooth',
								width: 2
							},
							fill: {
								type: 'gradient',
								gradient: {
									shadeIntensity: 1,
									opacityFrom: 0.7,
									opacityTo: 0.3,
									stops: [0, 90, 100]
								}
							},
							xaxis: {
								categories: data.labels,
								labels: {
									style: {
										colors: '#8c8c8c'
									}
								}
							},
							yaxis: {
								title: {
									text: 'Number of Activities'
								},
								labels: {
									style: {
										colors: '#8c8c8c'
									}
								}
							},
							grid: {
								borderColor: '#f1f1f1'
							}
						};
						
						var chart = new ApexCharts(document.querySelector("#hourlyChart"), options);
						chart.render();
					}
				}
			});
		}
		
		// Auto-refresh every 60 seconds
		setInterval(function() {
			// Update the table with new activities
			$.ajax({
				url: 'ajax/get_new_activities.php',
				type: 'GET',
				success: function(data) {
					if (data) {
						// Reload the page to show new activities
						location.reload();
					}
				}
			});
		}, 60000); // 60 seconds
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
			cursor: pointer;
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.select2-container .select2-selection--single {
			height: 38px;
			border: 1px solid #ced4da;
		}
		.select2-container--default .select2-selection--single .select2-selection__rendered {
			line-height: 36px;
		}
		.select2-container--default .select2-selection--single .select2-selection__arrow {
			height: 36px;
		}
		.dataTables_wrapper .dataTables_filter input {
			border: 1px solid #ced4da;
			border-radius: 4px;
			padding: 6px 12px;
		}
		</style>
		
	</body>
</html>

<?php
// Helper function to show time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return $diff . " seconds";
    } elseif ($diff < 3600) {
        return floor($diff / 60) . " minutes";
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . " hours";
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . " days";
    } elseif ($diff < 2592000) {
        return floor($diff / 604800) . " weeks";
    } elseif ($diff < 31536000) {
        return floor($diff / 2592000) . " months";
    } else {
        return floor($diff / 31536000) . " years";
    }
}
?>