<?php
// helper kecil untuk format "last seen"
function pg_last_seen($dt){
	if(!$dt) return '-';
	$ts = strtotime($dt);
	if(!$ts) return '-';
	$diff = time() - $ts;
	if($diff < 0) $diff = 0;

	if($diff < 60) return $diff.' detik lalu';
	if($diff < 3600) return floor($diff/60).' menit lalu';
	if($diff < 86400) return floor($diff/3600).' jam lalu';
	return floor($diff/86400).' hari lalu';
}
?>

<div class="table-responsive-sm">
	<div class="card-block">
		<table class="table">
			<thead class="thead-dark">
				<tr>
					<th style="width:1% !important;">No.</th>
					<th>User</th>
					<th>IP</th>
					<th>Browser</th>
					<th>OS</th>
					<th>Create Date</th>
					<th>Update Date</th>
					<th>Online</th>
					<th>Terakhir Online</th>
					<th style="width:1%;">Counter</th>
				</tr>
			</thead>

			<?php
			$onlineWindow = 180; // 3 menit
			if(!empty($posts)) {
				$no = $start + 1;
				foreach($posts as $row){

					$lastActivity = !empty($row["last_activity"]) ? $row["last_activity"] : null;
					$isOnline = $lastActivity ? (strtotime($lastActivity) >= (time() - $onlineWindow)) : false;

					$seenTxt = pg_last_seen($lastActivity);
			?>
			<tr>
				<td><?= $no++; ?></td>
				<td><?= !empty($row["nama_user"]) ? $row["nama_user"] : '-'; ?></td>
				<td><?= $row["ip"]; ?></td>
				<td><?= kata($row["browser"],12); ?></td>
				<td><?= $row["os"]; ?></td>
				<td><?= date_time($row["create_date"]); ?></td>
				<td><?= date_time($row["update_date"]); ?></td>

				<td>
					<?php if($isOnline){ ?>
						<span class="badge badge-success">ONLINE</span>
						<small class="text-muted d-block">aktif <?= $seenTxt; ?></small>
					<?php } else { ?>
						<span class="badge badge-secondary">OFFLINE</span>
						<small class="text-muted d-block">last seen <?= $seenTxt; ?></small>
					<?php } ?>
				</td>

				<td><?= $lastActivity ? date_time($lastActivity) : '-'; ?></td>
				<td align="center"><?= $row["counter"]; ?></td>
			</tr>
			<?php
				}
			} else {
			?>
				<tr><th colspan="10">Data belum ada</th></tr>
			<?php } ?>
		</table>
	</div>

	<nav aria-label="Page navigation example" class="p-2">
		<?php echo $this->ajax_pagination->create_links(); ?>
	</nav>
</div>
