<?php
session_start();
if (!isset($_SESSION['admin_id'])) { http_response_code(401); exit; }
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');

// Latest location per surveyor within last 24 hours
$sql = "
    SELECT ul.surveyor_id, ul.latitude, ul.longitude, ul.accuracy, ul.battery_level, ul.recorded_at,
           s.name, s.email,
           al.action  AS last_action,
           al.details AS last_action_details
    FROM user_locations ul
    INNER JOIN (
        SELECT surveyor_id, MAX(recorded_at) AS max_t
        FROM user_locations
        WHERE recorded_at > NOW() - INTERVAL 24 HOUR
        GROUP BY surveyor_id
    ) latest ON ul.surveyor_id = latest.surveyor_id AND ul.recorded_at = latest.max_t
    JOIN surveyors s ON ul.surveyor_id = s.id
    LEFT JOIN activity_logs al ON al.id = (
        SELECT id FROM activity_logs
        WHERE surveyor_id = ul.surveyor_id
        ORDER BY created_at DESC LIMIT 1
    )
    ORDER BY ul.recorded_at DESC
";

$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$now  = time();
$out  = [];

foreach ($rows as $r) {
    $ts   = strtotime($r['recorded_at']);
    $diff = $now - $ts;
    if      ($diff < 60)    $lastSeen = 'just now';
    elseif  ($diff < 3600)  $lastSeen = floor($diff / 60) . ' min ago';
    elseif  ($diff < 86400) $lastSeen = floor($diff / 3600) . 'h ago';
    else                    $lastSeen = date('M j H:i', $ts);

    $out[] = [
        'user_id'             => (int)$r['surveyor_id'],
        'name'                => $r['name'],
        'email'               => $r['email'],
        'lat'                 => (float)$r['latitude'],
        'lng'                 => (float)$r['longitude'],
        'accuracy'            => round((float)$r['accuracy'], 1),
        'battery'             => (int)$r['battery_level'],
        'last_seen'           => $lastSeen,
        'last_seen_ts'        => $ts,
        'is_active'           => $diff < 300,    // green  < 5 min
        'is_recent'           => $diff < 1800,   // yellow < 30 min
        'last_action'         => $r['last_action']         ?? '',
        'last_action_details' => $r['last_action_details'] ?? '',
    ];
}

echo json_encode(['users' => $out, 'server_ts' => $now]);
