<?php
session_start();
include '../includes/db.php';
include '../includes/header.php';
include '../includes/nav.php';

if (!isset($_SESSION['user_id']) || $_SESSION['is_admin'] != 1) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Zugriff verweigert.</div></div>";
    include 'includes/footer.php';
    exit;
}

$result = $conn->query("SELECT vorname, nachname, email, einheit, eingeloggt FROM users ORDER BY nachname");
$result2 = $conn->query("SELECT lh.*, u.username FROM login_history lh JOIN users u ON lh.user_id = u.id ORDER BY lh.login_time DESC");
?>

<div class="container my-5">
  <h2 class="mb-4">🔐 Benutzerstatus</h2>

  <div class="table-responsive">
    <table class="table table-bordered table-hover bg-white">
      <thead class="table-dark">
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Einheit</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($user = $result->fetch_assoc()): ?>
          <tr>
            <td><?= htmlspecialchars($user['vorname'] . ' ' . $user['nachname']) ?></td>
            <td><?= htmlspecialchars($user['email']) ?></td>
            <td><?= htmlspecialchars($user['einheit']) ?></td>
            <td>
              <?php if ($user['eingeloggt']): ?>
                <span class="badge bg-success">🟢 Online</span>
              <?php else: ?>
                <span class="badge bg-secondary">⚫️ Offline</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>


<div class="container my-5">
  <h2>📋 Login-Historie</h2>
  <table class="table table-bordered table-hover bg-white mt-4">
    <thead class="table-dark">
      <tr>
        <th>Nutzer</th>
        <th>IP-Adresse</th>
        <th>Aktion</th>
        <th>Zeitpunkt</th>
      </tr>
    </thead>
    <tbody>
      <?php while ($row2 = $result2->fetch_assoc()): ?>
        <tr>
          <td><?= htmlspecialchars($row2['username']) ?></td>
          <td><?= htmlspecialchars($row2['ip_address']) ?></td>
          <td><?= $row2['action'] === 'login' ? '🔓 Login' : '🔒 Logout' ?></td>
          <td><?= date("d.m.Y H:i:s", strtotime($row2['login_time'])) ?></td>
        </tr>
      <?php endwhile; ?>
    </tbody>
  </table>
</div>

<?php include '../includes/footer.php'; ?>
