<?php
require_once __DIR__.'/../config/config.php';
require_admin();
activity_ensure_table($pdo);

$PAGE_TITLE='User Activity'; require __DIR__.'/_layout.php';

$q=trim($_GET['q']??'');
$where=''; $params=[];
if($q!==''){
  $like='%'.$q.'%';
  $where="WHERE u.email LIKE ? OR u.name LIKE ? OR u.phone LIKE ? OR a.ip LIKE ? OR a.country LIKE ? OR a.city LIKE ?";
  $params=[$like,$like,$like,$like,$like,$like];
}
$sql="SELECT a.*, u.name AS uname, u.email, u.phone
      FROM user_activity a LEFT JOIN users u ON u.id=a.user_id
      $where
      ORDER BY a.id DESC LIMIT 300";
$st=$pdo->prepare($sql); $st->execute($params); $rows=$st->fetchAll();

function fmt_dur($from,$to){
  if(!$from||!$to) return '-';
  $s=strtotime($to)-strtotime($from);
  if($s<0)$s=0;
  if($s<60) return $s.'s';
  if($s<3600) return floor($s/60).'m '.($s%60).'s';
  if($s<86400) return floor($s/3600).'h '.floor(($s%3600)/60).'m';
  return floor($s/86400).'d '.floor(($s%86400)/3600).'h';
}
?>
<h2 style="margin-bottom:14px">🕒 কার্যকলাপ (User Activity)</h2>
<form method="get" style="margin-bottom:14px;display:flex;gap:8px;flex-wrap:wrap">
  <input class="input" name="q" value="<?=e($q)?>" placeholder="🔍 ইমেইল, নাম, ফোন, IP বা দেশ/শহর দিয়ে সার্চ" style="flex:1;min-width:240px">
  <button class="btn">সার্চ</button>
  <?php if($q!==''):?><a class="btn" style="background:#64748b" href="activity.php">✕ Clear</a><?php endif;?>
</form>
<p style="color:#64748b;font-size:12px;margin-bottom:10px">💡 প্রতিবার লগইন করলে ও সাইট ব্যবহার করলে এখানে রেকর্ড হয়। Location IP থেকে ip-api.com দিয়ে detect হয় (সার্ভারে outbound HTTP দরকার)।</p>

<div style="overflow-x:auto">
<table>
<thead><tr>
<th>#</th><th>User</th><th>Login</th><th>Last Seen</th><th>Duration</th>
<th>Browser</th><th>OS / Device</th><th>IP</th><th>Location</th><th>User-Agent</th>
</tr></thead>
<tbody>
<?php foreach($rows as $r):?>
<tr>
<td>#<?=$r['id']?></td>
<td><b><?=e($r['uname']??'—')?></b><br><small><?=e($r['email']??'')?></small><br><small><?=e($r['phone']??'')?></small></td>
<td><?=e($r['login_at'])?></td>
<td><?=e($r['last_seen_at'])?></td>
<td><b><?=fmt_dur($r['login_at'],$r['last_seen_at'])?></b></td>
<td><?=e($r['browser'])?> <small><?=e($r['browser_version'])?></small></td>
<td><?=e($r['os'])?><br><small><?=e($r['device'])?></small></td>
<td><code style="font-size:12px"><?=e($r['ip'])?></code></td>
<td><?=e(trim(($r['city']?$r['city'].', ':'').($r['region']?$r['region'].', ':'').($r['country']??''),', '))?:'—'?></td>
<td style="max-width:280px"><small style="word-break:break-all;color:#64748b"><?=e($r['user_agent'])?></small></td>
</tr>
<?php endforeach;?>
<?php if(!$rows):?><tr><td colspan="10" style="text-align:center;padding:20px;color:#64748b">কোনো activity রেকর্ড নেই। ইউজার লগইন করলে এখানে দেখাবে।</td></tr><?php endif;?>
</tbody>
</table>
</div>
<?php require __DIR__.'/_footer.php';
