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

$meldung = '';

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

// Einheit des Admins
$admin_einheit = $_SESSION['einheit'] ?? null;

// Benutzer anlegen
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vorname = trim($_POST['vorname']);
    $nachname = trim($_POST['nachname']);
    $username = strtolower($vorname . '.' . $nachname);
    $username = str_replace(['ä','ö','ü','ß',' '], ['ae','oe','ue','ss',''], $username);

    $pass_raw = $_POST['password'];
    $pass_hash = password_hash($pass_raw, PASSWORD_DEFAULT);
    $email = trim($_POST['email']);
    $email2 = $_POST['email'];
    $einheit = $admin_einheit;

    $sql = "INSERT INTO users (username, password, is_admin, einheit, vorname, nachname, email, bereich, rolle)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        "ssisssssi",
        $username,
        $pass_hash,
        $_POST['is_admin'],
        $einheit,
        $vorname,
        $nachname,
        $email,
        $_POST['bereich'],
        $_POST['rolle']
    );
    if ($stmt->execute()) {
        include 'mail/mail_register.php'; // Hier E-Mail mit Zugangsdaten versenden

        $meldung = "<div class='alert alert-success'>Benutzer erfolgreich angelegt und E-Mail versendet.</div>";
    } else {
        $meldung = "<div class='alert alert-danger'>Fehler beim Anlegen des Benutzers.</div>";
    }
}
?>

<div class="container my-5">
  <h2 class="mb-4">Benutzer anlegen</h2>
  <?= $meldung ?>
  <form method="post" class="card p-4 shadow-sm bg-light">
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label">Vorname</label>
        <input name="vorname" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Nachname</label>
        <input name="nachname" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Benutzername</label>
        <input name="username" class="form-control" readonly>
      </div>
      <div class="col-md-6">
        <label class="form-label">Passwort</label>
        <input name="password" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">E-Mail</label>
        <input type="email" name="email" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Bereich</label>
        <input name="bereich" class="form-control">
      </div>
      <input type="hidden" name="einheit" value="<?= htmlspecialchars($admin_einheit) ?>">
      <div class="col-md-3">
        <label class="form-label">Rolle (Zahl)</label>
        <input name="rolle" type="number" class="form-control" value="5">
      </div>
      <div class="col-md-3">
        <label class="form-label">Admin</label>
        <select name="is_admin" class="form-select">
          <option value="0">Nein</option>
          <option value="1">Ja</option>
        </select>
      </div>
      <div class="col-12 d-grid mt-4">
        <button class="btn btn-primary">Benutzer erstellen & Mail senden</button>
      </div>
    </div>
  </form>
</div>

<script>
document.querySelector('input[name="nachname"]').addEventListener('input', function () {
    const vorname = document.querySelector('input[name="vorname"]').value.trim().toLowerCase();
    const nachname = this.value.trim().toLowerCase();

    if (vorname && nachname) {
        let username = vorname + '.' + nachname;
        username = username
            .replace(/ä/g, 'ae')
            .replace(/ö/g, 'oe')
            .replace(/ü/g, 'ue')
            .replace(/ß/g, 'ss')
            .replace(/\s/g, '');
        document.querySelector('input[name="username"]').value = username;
    }
});
</script>

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