<?php
ob_start();
session_start();
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/admin_nav.php';

/* ---------------- Security: only root ---------------- */
if (!isset($_SESSION['user_id']) || (int)($_SESSION['root'] ?? 0) !== 1) {
    echo "<div class='container my-4'><div class='alert alert-danger'>Kein Zugriff.</div></div>";
    exit;
}

/* ---------------- Helpers ---------------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf'];

$flash_ok  = $_SESSION['flash_ok']  ?? '';
$flash_err = $_SESSION['flash_err'] ?? '';
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

/* ---------------- Delete (POST + CSRF) ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    if (!hash_equals($CSRF, $_POST['csrf'] ?? '')) {
        $_SESSION['flash_err'] = 'Sicherheitsprüfung fehlgeschlagen.';
        header('Location: admin_users.php'); exit;
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM users WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $_SESSION['flash_ok'] = 'Benutzer gelöscht.';
    }
    header('Location: admin_users.php'); exit;
}

/* ---------------- Create / Update (inline create; updates via separate page ok) ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save') {
    if (!hash_equals($CSRF, $_POST['csrf'] ?? '')) {
        $_SESSION['flash_err'] = 'Sicherheitsprüfung fehlgeschlagen.';
        header('Location: admin_users.php'); exit;
    }

    $id       = (int)($_POST['id'] ?? 0);
    $vorname  = trim($_POST['vorname'] ?? '');
    $nachname = trim($_POST['nachname'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $einheit  = trim($_POST['einheit'] ?? '');
    $root     = isset($_POST['root']) ? 1 : 0;

    if ($vorname === '' || $nachname === '' || $email === '' || $einheit === '') {
        $_SESSION['flash_err'] = 'Bitte alle Pflichtfelder ausfüllen.';
        header('Location: admin_users.php'); exit;
    }

    if ($id === 0) {
        // Neuer User – Standardpasswort „123456“ (Tipp: danach direkt zurücksetzen)
        $pass = password_hash('123456', PASSWORD_DEFAULT);
        $stmt = $conn->prepare("INSERT INTO users (vorname,nachname,email,einheit,password,root) VALUES (?,?,?,?,?,?)");
        $stmt->bind_param("sssssi", $vorname, $nachname, $email, $einheit, $pass, $root);
        $stmt->execute();
        $_SESSION['flash_ok'] = 'Benutzer angelegt.';
    } else {
        $stmt = $conn->prepare("UPDATE users SET vorname=?, nachname=?, email=?, einheit=?, root=? WHERE id=?");
        $stmt->bind_param("ssssii", $vorname, $nachname, $email, $einheit, $root, $id);
        $stmt->execute();
        $_SESSION['flash_ok'] = 'Benutzerdaten aktualisiert.';
    }

    header('Location: admin_users.php'); exit;
}

/* ---------------- Query: search + list ---------------- */
$q = trim($_GET['q'] ?? '');
$filter_sql = '';
$params = [];
$types  = '';

if ($q !== '') {
    $like = "%$q%";
    $filter_sql = " WHERE (vorname LIKE ? OR nachname LIKE ? OR email LIKE ? OR einheit LIKE ?)";
    $params = [$like, $like, $like, $like];
    $types  = "ssss";
}

$sql = "SELECT id, vorname, nachname, email, einheit, username, rolle, root FROM users". $filter_sql ." ORDER BY nachname, vorname";
$stmt = $conn->prepare($sql);
if ($params) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$nutzer = $stmt->get_result();

/* Einheiten für Datalist (komfortabler Eingabefeld) */
$einheiten = [];
$resE = $conn->query("SELECT DISTINCT einheit FROM users WHERE einheit<>'' ORDER BY einheit ASC");
if ($resE) while($row=$resE->fetch_assoc()) $einheiten[] = $row['einheit'];

?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Benutzerverwaltung</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .card-elev{ box-shadow:0 6px 20px rgba(0,0,0,.06); border:1px solid #eef0f2; border-radius:1rem; }
    .table thead th{ white-space:nowrap; }
  </style>
</head>
<body class="bg-light">
<div class="container my-4">

  <div class="d-flex align-items-center justify-content-between mb-3">
    <h2 class="mb-0">👤 Benutzerverwaltung</h2>
    <a class="btn btn-outline-secondary" href="../index.php">Zurück</a>
  </div>

  <?php if ($flash_ok): ?><div class="alert alert-success"><?= h($flash_ok) ?></div><?php endif; ?>
  <?php if ($flash_err): ?><div class="alert alert-danger"><?= h($flash_err) ?></div><?php endif; ?>

  <!-- Toolbar -->
  <div class="card card-elev mb-4">
    <div class="card-body">
      <form class="row g-2 align-items-end" method="get">
        <div class="col-12 col-md-6">
          <label class="form-label">Suchen (Name, E-Mail, Einheit)</label>
          <input type="text" name="q" value="<?= h($q) ?>" class="form-control" placeholder="z. B. „Müller“ oder „Bad Zwischenahn“">
        </div>
        <div class="col-auto">
          <button class="btn btn-primary">🔎 Suchen</button>
        </div>
        <div class="col-auto">
          <a href="admin_users.php" class="btn btn-outline-secondary">Zurücksetzen</a>
        </div>
        <div class="col-auto ms-auto">
          <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#userModal">
            ➕ Benutzer hinzufügen
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Tabelle -->
  <div class="card card-elev">
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-hover align-middle">
          <thead class="table-light">
            <tr>
              <th>Name</th>
              <th>E-Mail</th>
              <th>Einheit</th>
              <th>Benutzername</th>
              <th>Rolle</th>
              <th>Root</th>
              <th style="width:260px">Aktion</th>
            </tr>
          </thead>
          <tbody>
          <?php if ($nutzer && $nutzer->num_rows): while($row = $nutzer->fetch_assoc()): ?>
            <tr>
              <td><?= h($row['nachname'].', '.$row['vorname']) ?></td>
              <td><a href="mailto:<?= h($row['email']) ?>"><?= h($row['email']) ?></a></td>
              <td><?= h($row['einheit']) ?></td>
              <td><?= h($row['username'] ?? '') ?></td>
              <td><?= h($row['rolle'] ?? '') ?></td>
              <td>
                <?php if ((int)$row['root'] === 1): ?>
                  <span class="badge text-bg-success">Admin</span>
                <?php else: ?>
                  <span class="badge text-bg-secondary">User</span>
                <?php endif; ?>
              </td>
              <td>
                <div class="d-flex flex-wrap gap-2">
                  <a href="admin_users_edit.php?id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-warning">Bearbeiten</a>

                  <form method="post" onsubmit="return confirm('Benutzer wirklich löschen?');" class="d-inline">
                    <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                    <button class="btn btn-sm btn-danger">Löschen</button>
                  </form>

                  <a href="../mail/admin_user_pwreset.php?id=<?= (int)$row['id'] ?>"
                     class="btn btn-sm btn-info">Passwort-Reset</a>
                </div>
              </td>
            </tr>
          <?php endwhile; else: ?>
            <tr><td colspan="7" class="text-center text-muted py-4">Keine Benutzer gefunden.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="small text-muted">Hinweis: Neue Benutzer erhalten initial das Passwort <code>123456</code> und sollten es nach dem ersten Login sofort ändern.</div>
    </div>
  </div>
</div>

<!-- Modal: Benutzer hinzufügen -->
<div class="modal fade" id="userModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="post">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="id" value="0">

      <div class="modal-header">
        <h5 class="modal-title">Benutzer hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>

      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Vorname *</label>
            <input type="text" name="vorname" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Nachname *</label>
            <input type="text" name="nachname" class="form-control" required>
          </div>
          <div class="col-md-7">
            <label class="form-label">E-Mail *</label>
            <input type="email" name="email" class="form-control" required>
          </div>
          <div class="col-md-5">
            <label class="form-label">Einheit *</label>
            <input list="dl_einheiten" name="einheit" class="form-control" placeholder="Einheit wählen/angeben" required>
            <datalist id="dl_einheiten">
              <?php foreach($einheiten as $e): ?>
                <option value="<?= h($e) ?>"></option>
              <?php endforeach; ?>
            </datalist>
          </div>
          <div class="col-12">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="root" id="rootCheck">
              <label class="form-check-label" for="rootCheck">Admin-Rechte (root)</label>
            </div>
            <div class="form-text">Standardpasswort: <code>123456</code> – bitte nach dem ersten Login ändern.</div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-success">➕ Benutzer anlegen</button>
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Abbrechen</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
