<?php
// Admin dashboard (single-file, cleaned up)
// - session started once
// - headers (redirects) sent before any HTML output
// - hardcoded password (demo) defined once
// - loads DB + wallets.log and renders using main styles

session_start();

// hardcoded admin password (demo only)
const ADMIN_PASSWORD = 'admin';

// logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    unset($_SESSION['is_admin']);
    header('Location: admin.php');
    exit;
}

// handle login POST
$login_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    if ($_POST['password'] === ADMIN_PASSWORD) {
        $_SESSION['is_admin'] = true;
        header('Location: admin.php');
        exit;
    } else {
        $login_error = 'Invalid password';
    }
}

// if not authenticated show login form (no prior output)
if (empty($_SESSION['is_admin'])) {
    ?><!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <title>Admin Login</title>
      <link rel="stylesheet" href="./commonStyle.css">
      <link rel="stylesheet" href="./style.css">
      <style>
        body{font-family:Arial,Helvetica,sans-serif;padding:24px;background:#f6f7fb; display:flex;justify-content:center;align-items:center;min-height:100vh    }
        .card{max-width:520px;margin:40px auto;padding:18px;background:#fff;border-radius:8px;box-shadow:0 6px 18px rgba(0,0,0,.06)}
        input{width:100%;padding:10px;margin-top:8px;border:1px solid #000000ff;border-radius:6px}
        h2{color:black; text-align:center}
        button{margin-top:12px;padding:10px 14px;border-radius:6px;background:#2f5dff;color:#fff;border:none;cursor:pointer}
        .err{color:#b91c1c;margin-top:8px}
      </style>
    </head>
    <body>
      <div class="card">
        <h2>Admin Login</h2>
        <form method="post" action="admin.php">
          <label>Password</label>
          <input type="password" name="password" autocomplete="off" required />
          <button type="submit">Sign in</button>
        </form>
        <?php if (!empty($login_error)): ?><div class="err"><?= htmlspecialchars($login_error) ?></div><?php endif; ?>
        <div style="margin-top:12px;font-size:0.85rem;color:#666">This page uses a hardcoded password (demo).</div>
      </div>
    </body>
    </html><?php
    exit;
}

// Authenticated: collect records
$rows = [];

// read wallets.log (file entries as JSON)
$logDir = __DIR__ . '/logs';
if (is_dir($logDir)) {
    $logFile = $logDir . '/wallets.log';
    if (is_readable($logFile)) {
        $fh = fopen($logFile, 'r');
        if ($fh) {
            while (($line = fgets($fh)) !== false) {
                $line = trim($line);
                if ($line === '') continue;
                // Parse log format: "YYYY-MM-DD HH:MM:SS | {json}"
                if (preg_match('#^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*\|\s*(.+)$#', $line, $m)) {
                    $ts = $m[1];
                    $obj = json_decode($m[2], true);
                    if (!is_array($obj)) continue;
                    $rows[] = [
                        'source' => 'log',
                        'email' => $obj['email'] ?? '',
                        'wallet' => $obj['wallet'] ?? '',
                        'lat' => isset($obj['location']['lat']) ? (float)$obj['location']['lat'] : null,
                        'lng' => isset($obj['location']['lng']) ? (float)$obj['location']['lng'] : null,
                        'accuracy' => isset($obj['location']['accuracy']) ? (float)$obj['location']['accuracy'] : null,
                        'maps' => $obj['maps'] ?? null,
                        'ts' => $ts
                    ];
                }
            }
            fclose($fh);
        }
    }
}

// sort by timestamp (newest first)
usort($rows, function($a,$b){
    $ta = isset($a['ts']) ? strtotime($a['ts']) : 0;
    $tb = isset($b['ts']) ? strtotime($b['ts']) : 0;
    return $tb - $ta;
});

// render admin table using site styles
?><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Admin Dashboard</title>
  <link rel="stylesheet" href="./commonStyle.css">
  <link rel="stylesheet" href="./style.css">
  <style>
    body{font-family:Arial,Helvetica,sans-serif;padding:18px;background:#f6f7fb;color:#111}
    .header{display:flex;justify-content:space-between;align-items:center;gap:12px}
    .table{width:100%;border-collapse:collapse;margin-top:12px;background:#fff;border-radius:8px;overflow:hidden}
    .table th, .table td{padding:10px;border-bottom:1px solid #eef2f7;text-align:left;font-size:14px}
    .table th{background:#f1f5f9;font-weight:700}
    .badge{display:inline-block;padding:4px 8px;border-radius:6px;background:#eef2ff;color:#1e40af;font-size:12px}
    .maplink{color:#0b61ff;text-decoration:none}
    .empty{padding:18px;background:#fff;border-radius:8px;margin-top:12px}
    .actionsTop{display:flex;gap:8px;align-items:center}
    .btnInline{padding:8px 12px;border-radius:6px;background:#2f5dff;color:#fff;border:none;cursor:pointer;text-decoration:none}
  </style>
</head>
<body>
  <div class="header">
    <h2>Admin Dashboard</h2>
    <div class="actionsTop">
      <a class="btnInline" href="admin.php?action=logout">Logout</a>
    </div>
  </div>

  <?php if (empty($rows)): ?>
    <div class="empty">No wallet records found.</div>
  <?php else: ?>
    <table class="table" role="table" aria-label="wallets">
      <thead><tr>
        <th>Timestamp</th>
        <th>Email</th>
        <th>Wallet</th>
        <th>Location (lat, lng)</th>
        <th>Accuracy (m)</th>
        <th>Map</th>
        <th>Source</th>
      </tr></thead>
      <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= htmlspecialchars($r['ts'] ?? '') ?></td>
          <td><?= htmlspecialchars($r['email'] ?? '') ?></td>
          <td style="font-family:monospace"><?= htmlspecialchars($r['wallet'] ?? '') ?></td>
          <td>
            <?php
              if ($r['lat'] !== null && $r['lng'] !== null) {
                  echo htmlspecialchars($r['lat'] . ', ' . $r['lng']);
              } else {
                  echo '<span style="color:#666">n/a</span>';
              }
            ?>
          </td>
          <td><?= $r['accuracy'] !== null ? htmlspecialchars((string)$r['accuracy']) : '<span style="color:#666">n/a</span>' ?></td>
          <td>
            <?php if (!empty($r['maps'])): ?>
              <a class="maplink" href="<?= htmlspecialchars($r['maps']) ?>" target="_blank" rel="noopener noreferrer">Open Map</a>
            <?php else: ?>
              <span style="color:#666">n/a</span>
            <?php endif; ?>
          </td>
          <td><span class="badge"><?= htmlspecialchars(strtoupper($r['source'])) ?></span></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</body>
</html>