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

$meldung = '';
$filter_status = $_GET['status'] ?? 'alle';

// SQL-Filter
$sql = "SELECT * FROM email_log";
if ($filter_status === 'erfolgreich') {
    $sql .= " WHERE status = 'erfolgreich'";
} elseif ($filter_status === 'fehler') {
    $sql .= " WHERE status = 'fehler'";
}
$sql .= " ORDER BY zeitstempel DESC";

$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>📨 E-Mail Log</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light p-4">
  <div class="container bg-white p-4 rounded shadow">
    <h2 class="mb-4">📨 E-Mail-Versandprotokoll</h2>

    <form method="GET" class="mb-4">
      <div class="row g-3 align-items-center">
        <div class="col-auto">
          <label for="status" class="form-label">Filtern nach Status:</label>
        </div>
        <div class="col-auto">
          <select name="status" id="status" class="form-select" onchange="this.form.submit()">
            <option value="alle" <?= $filter_status === 'alle' ? 'selected' : '' ?>>Alle</option>
            <option value="erfolgreich" <?= $filter_status === 'erfolgreich' ? 'selected' : '' ?>>✅ Erfolgreich</option>
            <option value="fehler" <?= $filter_status === 'fehler' ? 'selected' : '' ?>>❌ Fehler</option>
          </select>
        </div>
      </div>
    </form>

    <table class="table table-bordered table-hover">
      <thead class="table-light">
        <tr>
          <th>Zeit</th>
          <th>Empfänger</th>
          <th>Betreff</th>
          <th>Status</th>
          <th>Fehlertext</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($row = $result->fetch_assoc()): ?>
          <tr>
            <td><?= date('d.m.Y H:i', strtotime($row['zeitstempel'])) ?></td>
            <td><?= htmlspecialchars($row['empfaenger']) ?></td>
            <td><?= htmlspecialchars($row['betreff']) ?></td>
            <td>
              <span class="badge <?= $row['status'] === 'erfolgreich' ? 'bg-success' : 'bg-danger' ?>">
                <?= ucfirst($row['status']) ?>
              </span>
            </td>
            <td style="max-width: 300px; white-space: pre-wrap;"><?= htmlspecialchars($row['fehlertext'] ?: '-') ?></td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</body>
</html>
