<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../config/db.php';

// ── Filters ──────────────────────────────────────────────────────────────────
$filterUser   = intval($_GET['user_id']   ?? 0);
$filterAction = trim($_GET['action']      ?? '');
$filterFrom   = trim($_GET['date_from']   ?? '');
$filterTo     = trim($_GET['date_to']     ?? '');
$page         = max(1, intval($_GET['page'] ?? 1));
$perPage      = 50;
$offset       = ($page - 1) * $perPage;

// Build WHERE
$where  = [];
$params = [];

if ($filterUser) {
    $where[]  = 'al.surveyor_id = ?';
    $params[] = $filterUser;
}
if ($filterAction) {
    $where[]  = 'al.action = ?';
    $params[] = $filterAction;
}
if ($filterFrom) {
    $where[]  = 'al.created_at >= ?';
    $params[] = $filterFrom . ' 00:00:00';
}
if ($filterTo) {
    $where[]  = 'al.created_at <= ?';
    $params[] = $filterTo . ' 23:59:59';
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// Count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM activity_logs al $whereSql");
$countStmt->execute($params);
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = (int)ceil($totalRows / $perPage);

// Rows
$stmt = $pdo->prepare("
    SELECT al.*, s.name AS surveyor_name
    FROM activity_logs al
    JOIN surveyors s ON al.surveyor_id = s.id
    $whereSql
    ORDER BY al.created_at DESC
    LIMIT ? OFFSET ?
");
$stmt->execute([...$params, $perPage, $offset]);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Surveyor list for filter
$surveyors = $pdo->query("SELECT id, name FROM surveyors WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Distinct actions for filter
$actions = $pdo->query("SELECT DISTINCT action FROM activity_logs ORDER BY action")->fetchAll(PDO::FETCH_COLUMN);

// Action config
function actionConfig(string $a): array {
    return match($a) {
        'map_open'      => ['📍', 'bg-blue-50 text-blue-700',   'Opened Map'],
        'parcel_tap'    => ['👆', 'bg-purple-50 text-purple-700','Tapped Parcel'],
        'survey_start'  => ['📝', 'bg-yellow-50 text-yellow-700','Started Survey'],
        'survey_save'   => ['💾', 'bg-green-50 text-green-700',  'Saved Survey'],
        'sync_start'    => ['🔄', 'bg-orange-50 text-orange-700','Sync Started'],
        'sync_complete' => ['✅', 'bg-emerald-50 text-emerald-700','Synced'],
        'zone_selected' => ['🗺', 'bg-cyan-50 text-cyan-700',    'Zone Changed'],
        'app_open'      => ['📱', 'bg-slate-100 text-slate-600', 'App Opened'],
        'login'         => ['🔑', 'bg-indigo-50 text-indigo-700','Logged In'],
        default         => ['•',  'bg-gray-100 text-gray-600',    ucfirst(str_replace('_',' ',$a))],
    };
}

// Build pagination URL helper
function pageUrl(int $p): string {
    $q = $_GET;
    $q['page'] = $p;
    return '?' . http_build_query($q);
}
?>

<!-- Filter bar -->
<form method="get" class="bg-white rounded-xl border border-gray-200 p-4 mb-4 flex flex-wrap gap-3 items-end">
  <div class="flex flex-col gap-1">
    <label class="text-xs font-medium text-slate-600">Surveyor</label>
    <select name="user_id" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      <option value="0">All Surveyors</option>
      <?php foreach ($surveyors as $sv): ?>
        <option value="<?= $sv['id'] ?>" <?= $filterUser == $sv['id'] ? 'selected' : '' ?>>
          <?= htmlspecialchars($sv['name']) ?>
        </option>
      <?php endforeach ?>
    </select>
  </div>

  <div class="flex flex-col gap-1">
    <label class="text-xs font-medium text-slate-600">Action</label>
    <select name="action" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      <option value="">All Actions</option>
      <?php foreach ($actions as $act): ?>
        <option value="<?= htmlspecialchars($act) ?>" <?= $filterAction === $act ? 'selected' : '' ?>>
          <?= htmlspecialchars($act) ?>
        </option>
      <?php endforeach ?>
    </select>
  </div>

  <div class="flex flex-col gap-1">
    <label class="text-xs font-medium text-slate-600">From</label>
    <input type="date" name="date_from" value="<?= htmlspecialchars($filterFrom) ?>"
           class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
  </div>

  <div class="flex flex-col gap-1">
    <label class="text-xs font-medium text-slate-600">To</label>
    <input type="date" name="date_to" value="<?= htmlspecialchars($filterTo) ?>"
           class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
  </div>

  <div class="flex gap-2">
    <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700 transition">Filter</button>
    <a href="activity_log.php" class="border border-gray-300 text-slate-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-50 transition">Clear</a>
  </div>

  <div class="ml-auto text-sm text-slate-400 self-center">
    <?= number_format($totalRows) ?> records
  </div>
</form>

<!-- Table -->
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
  <div class="overflow-x-auto">
    <table class="w-full text-sm">
      <thead>
        <tr class="bg-slate-50 border-b border-gray-200">
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Time</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Surveyor</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Action</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Details</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Location</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-100">
        <?php if (empty($logs)): ?>
          <tr><td colspan="5" class="text-center py-12 text-slate-400">No activity found</td></tr>
        <?php else: foreach ($logs as $log):
          [$icon, $badge, $label] = actionConfig($log['action']);
          $hasLoc = $log['latitude'] && $log['longitude'];
        ?>
          <tr class="hover:bg-slate-50 transition-colors">
            <td class="px-4 py-3 whitespace-nowrap">
              <div class="text-slate-800 font-medium"><?= date('M j, H:i', strtotime($log['created_at'])) ?></div>
              <div class="text-slate-400 text-xs"><?= date('Y', strtotime($log['created_at'])) ?></div>
            </td>
            <td class="px-4 py-3">
              <a href="?user_id=<?= $log['surveyor_id'] ?>"
                 class="font-medium text-blue-600 hover:underline">
                <?= htmlspecialchars($log['surveyor_name']) ?>
              </a>
            </td>
            <td class="px-4 py-3">
              <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium <?= $badge ?>">
                <?= $icon ?> <?= $label ?>
              </span>
            </td>
            <td class="px-4 py-3 text-slate-600 max-w-xs truncate" title="<?= htmlspecialchars($log['details']) ?>">
              <?= htmlspecialchars($log['details'] ?: '—') ?>
            </td>
            <td class="px-4 py-3">
              <?php if ($hasLoc): ?>
                <a href="https://www.openstreetmap.org/?mlat=<?= $log['latitude'] ?>&mlon=<?= $log['longitude'] ?>#map=17/<?= $log['latitude'] ?>/<?= $log['longitude'] ?>"
                   target="_blank"
                   class="text-xs text-blue-500 hover:underline flex items-center gap-1">
                  📍 <?= round($log['latitude'], 5) ?>, <?= round($log['longitude'], 5) ?>
                </a>
              <?php else: ?>
                <span class="text-slate-300 text-xs">—</span>
              <?php endif ?>
            </td>
          </tr>
        <?php endforeach; endif ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($totalPages > 1): ?>
  <div class="px-4 py-3 border-t border-gray-200 flex items-center justify-between">
    <div class="text-xs text-slate-500">
      Page <?= $page ?> of <?= $totalPages ?>
      (<?= number_format(($page-1)*$perPage + 1) ?>–<?= number_format(min($page*$perPage, $totalRows)) ?> of <?= number_format($totalRows) ?>)
    </div>
    <div class="flex gap-1">
      <?php if ($page > 1): ?>
        <a href="<?= pageUrl(1) ?>" class="px-3 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-gray-50">«</a>
        <a href="<?= pageUrl($page-1) ?>" class="px-3 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-gray-50">‹</a>
      <?php endif ?>
      <?php
        $start = max(1, $page - 2);
        $end   = min($totalPages, $page + 2);
        for ($i = $start; $i <= $end; $i++):
      ?>
        <a href="<?= pageUrl($i) ?>"
           class="px-3 py-1.5 text-xs rounded-lg border <?= $i === $page
             ? 'bg-blue-600 text-white border-blue-600'
             : 'border-gray-300 hover:bg-gray-50' ?>">
          <?= $i ?>
        </a>
      <?php endfor ?>
      <?php if ($page < $totalPages): ?>
        <a href="<?= pageUrl($page+1) ?>" class="px-3 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-gray-50">›</a>
        <a href="<?= pageUrl($totalPages) ?>" class="px-3 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-gray-50">»</a>
      <?php endif ?>
    </div>
  </div>
  <?php endif ?>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
