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

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

$meldung = '';

// Benutzer löschen
if (isset($_GET['delete'])) {
    $delId = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $delId);
    $stmt->execute();
    $meldung = "<div class='alert alert-success'>✅ Benutzer wurde gelöscht.</div>";
}

// Benutzer speichern (neu oder update)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $username = trim($_POST['username']);
    $vorname = trim($_POST['vorname']);
    $nachname = trim($_POST['nachname']);
    $email = trim($_POST['email']);
    $rolle = (int)$_POST['rolle'];
    $bereich = trim($_POST['bereich']);
    $is_admin = isset($_POST['is_admin']) ? 1 : 0;
    $root = isset($_POST['root']) ? 1 : 0;
    $pass = trim($_POST['password']);
    $hash = $pass ? password_hash($pass, PASSWORD_DEFAULT) : null;

    if ($id === 0) {
        // Neuer Benutzer
        $stmt = $conn->prepare("INSERT INTO users (username, password, vorname, nachname, email, rolle, bereich, is_admin, root, feuerwehr_id, gemeinde_id, lk_id, einheit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'A2BZ', 'Bad Zwischenahn', 'Landkreis Ammerland', 'A2BZ')");
        $stmt->bind_param("sssssiiii", $username, $hash, $vorname, $nachname, $email, $rolle, $bereich, $is_admin, $root);
        $stmt->execute();
        $meldung = "<div class='alert alert-success'>✅ Benutzer wurde erstellt.</div>";
    } else {
        // Bestehenden Benutzer aktualisieren
        if ($hash) {
            $stmt = $conn->prepare("UPDATE users SET username=?, password=?, vorname=?, nachname=?, email=?, rolle=?, bereich=?, is_admin=?, root=? WHERE id=?");
            $stmt->bind_param("sssssiiiii", $username, $hash, $vorname, $nachname, $email, $rolle, $bereich, $is_admin, $root, $id);
        } else {
            $stmt = $conn->prepare("UPDATE users SET username=?, vorname=?, nachname=?, email=?, rolle=?, bereich=?, is_admin=?, root=? WHERE id=?");
            $stmt->bind_param("ssssiiiii", $username, $vorname, $nachname, $email, $rolle, $bereich, $is_admin, $root, $id);
        }
        $stmt->execute();
        $meldung = "<div class='alert alert-success'>✅ Benutzer wurde aktualisiert.</div>";
    }
}

// Benutzer laden
$benutzer = $conn->query("SELECT * FROM users ORDER BY nachname, vorname")->fetch_all(MYSQLI_ASSOC);

// Zu bearbeitender Benutzer
$edit = null;
if (isset($_GET['edit'])) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $_GET['edit']);
    $stmt->execute();
    $edit = $stmt->get_result()->fetch_assoc();
}
?>

<div class="container my-5">
  <h2 class="mb-4">Benutzerverwaltung</h2>
  <?= $meldung ?>

  <form method="post" class="card p-4 mb-4 shadow-sm">
    <input type="hidden" name="id" value="<?= $edit['id'] ?? 0 ?>">
    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Benutzername</label>
        <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($edit['username'] ?? '') ?>" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">Passwort <?= $edit ? '(leer lassen für unverändert)' : '' ?></label>
        <input type="password" name="password" class="form-control">
      </div>
      <div class="col-md-4">
        <label class="form-label">E-Mail</label>
        <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($edit['email'] ?? '') ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Vorname</label>
        <input type="text" name="vorname" class="form-control" value="<?= htmlspecialchars($edit['vorname'] ?? '') ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Nachname</label>
        <input type="text" name="nachname" class="form-control" value="<?= htmlspecialchars($edit['nachname'] ?? '') ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Rolle</label>
        <input type="number" name="rolle" class="form-control" value="<?= $edit['rolle'] ?? 5 ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Bereich</label>
        <input type="text" name="bereich" class="form-control" value="<?= htmlspecialchars($edit['bereich'] ?? '') ?>">
      </div>
      <div class="col-md-1 form-check mt-4">
        <input type="checkbox" name="is_admin" class="form-check-input" <?= !empty($edit['is_admin']) ? 'checked' : '' ?>>
        <label class="form-check-label">Admin</label>
      </div>
      <div class="col-md-1 form-check mt-4">
        <input type="checkbox" name="root" class="form-check-input" <?= !empty($edit['root']) ? 'checked' : '' ?>>
        <label class="form-check-label">Root</label>
      </div>
    </div>
    <button class="btn btn-success mt-3">Speichern</button>
  </form>

  <table class="table table-striped table-bordered">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Benutzername</th>
        <th>Name</th>
        <th>E-Mail</th>
        <th>Rolle</th>
        <th>Admin</th>
        <th>Aktionen</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($benutzer as $u): ?>
        <tr>
          <td><?= $u['id'] ?></td>
          <td><?= htmlspecialchars($u['username']) ?></td>
          <td><?= htmlspecialchars($u['vorname'] . ' ' . $u['nachname']) ?></td>
          <td><?= htmlspecialchars($u['email']) ?></td>
          <td><?= $u['rolle'] ?></td>
          <td><?= $u['is_admin'] ? '✅' : '' ?></td>
          <td>
            <a href="?edit=<?= $u['id'] ?>" class="btn btn-sm btn-primary">Bearbeiten</a>
            <a href="?delete=<?= $u['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Wirklich löschen?')">Löschen</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

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