<?php
require_once __DIR__ . '/../config.php';
session_start();
if (empty($_SESSION['admin_logged'])) { header('Location: login.php'); exit; }

function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    }
    return $pdo;
}

$key  = $_GET['key'] ?? '';
$pdo  = db();
$logs = $pdo->prepare("SELECT * FROM license_logs WHERE license_key = ? ORDER BY created_at DESC LIMIT 200");
$logs->execute([$key]);
$rows = $logs->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Logs — <?= htmlspecialchars($key) ?></title>
<style>
  body { font-family: sans-serif; background: #0f172a; color: #e2e8f0; padding: 1rem; }
  h1 { color: #38bdf8; }
  a { color: #94a3b8; }
  table { width: 100%; border-collapse: collapse; font-size: .85rem; }
  th { background: #1e293b; padding: .5rem; text-align: left; color: #94a3b8; }
  td { padding: .5rem; border-bottom: 1px solid #1e293b; }
  .ok { color: #4ade80; } .fail { color: #f87171; } .warn { color: #fbbf24; }
</style>
</head>
<body>
<h1>Logs: <?= htmlspecialchars($key) ?></h1>
<p><a href="index.php">← Voltar</a></p>
<table>
  <thead><tr><th>Data/Hora</th><th>Ação</th><th>IP</th><th>Hardware ID</th><th>Mensagem</th></tr></thead>
  <tbody>
  <?php foreach ($rows as $r):
      $act = $r['action'];
      if ($act === 'validate' || $act === 'activate') $cls = 'ok';
      elseif ($act === 'revoke' || $act === 'fail')   $cls = 'fail';
      else                                             $cls = 'warn';
  ?>
  <tr>
    <td><?= htmlspecialchars(date('d/m/Y H:i:s', strtotime($r['created_at']))) ?></td>
    <td class="<?= $cls ?>"><?= htmlspecialchars($r['action']) ?></td>
    <td><?= htmlspecialchars($r['ip_address'] ?? '—') ?></td>
    <td style="font-family:monospace;font-size:.75rem"><?= htmlspecialchars($r['hardware_id'] ?? '—') ?></td>
    <td><?= htmlspecialchars($r['message'] ?? '—') ?></td>
  </tr>
  <?php endforeach; ?>
  </tbody>
</table>
</body>
</html>
