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

session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$id = (int)($_GET['id'] ?? 0);
$meldung = '';

// Kamerad laden
$stmt = $conn->prepare("SELECT * FROM kameraden WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$kamerad = $stmt->get_result()->fetch_assoc();
if (!$kamerad) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Kamerad nicht gefunden.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Spind-Zuordnungen prüfen
$spindnummern = range(1, 80);
$belegte_spinde = [];
$result = $conn->query("SELECT id, spindnr, vorname, nachname FROM kameraden WHERE id != $id");
while ($row = $result->fetch_assoc()) {
    if (!empty($row['spindnr'])) {
        $belegte_spinde[$row['spindnr']] = $row['vorname'] . ' ' . $row['nachname'];
    }
}

// Formular speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $vorname = trim($_POST['vorname']);
    $nachname = trim($_POST['nachname']);
    $email = trim($_POST['email']);
    $spindnr = trim($_POST['spindnr']);
    $groesse_jacke = trim($_POST['groesse_jacke']);
    $groesse_hose = trim($_POST['groesse_hose']);
    $groesse_hose_agt = trim($_POST['groesse_hose_agt']);
    $groesse_stiefel = trim($_POST['groesse_stiefel']);

    if (isset($belegte_spinde[$spindnr])) {
        $meldung = "<div class='alert alert-danger'>❌ Spind $spindnr ist bereits vergeben an {$belegte_spinde[$spindnr]}.</div>";
    } else {
        $stmt = $conn->prepare("UPDATE kameraden SET vorname = ?, nachname = ?, email = ?, spindnr = ?, groesse_jacke = ?, groesse_hose = ?, groesse_hose_agt = ?, groesse_stiefel = ? WHERE id = ?");
        $stmt->bind_param("sssssssii", $vorname, $nachname, $email, $spindnr, $groesse_jacke, $groesse_hose, $groesse_hose_agt, $groesse_stiefel, $id);
        $stmt->execute();

        $meldung = "<div class='alert alert-success'>✅ Kamerad erfolgreich aktualisiert.</div>";

        // Reload
        $stmt = $conn->prepare("SELECT * FROM kameraden WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $kamerad = $stmt->get_result()->fetch_assoc();
    }
}
?>

<div class="container my-5">
  <h2 class="mb-4">Kamerad bearbeiten</h2>

  <?= $meldung ?>

  <form method="post" class="card p-4 bg-white shadow-sm">
    <div class="mb-3">
      <label class="form-label">Vorname</label>
      <input type="text" name="vorname" value="<?= htmlspecialchars($kamerad['vorname']) ?>" class="form-control" required>
    </div>
    <div class="mb-3">
      <label class="form-label">Nachname</label>
      <input type="text" name="nachname" value="<?= htmlspecialchars($kamerad['nachname']) ?>" class="form-control" required>
    </div>
    <div class="mb-3">
      <label class="form-label">E-Mail</label>
      <input type="email" name="email" value="<?= htmlspecialchars($kamerad['email']) ?>" class="form-control">
    </div>
    <div class="mb-3">
      <label class="form-label">Spindnummer</label>
      <select name="spindnr" class="form-select" required>
        <option value="">– bitte wählen –</option>
        <?php foreach ($spindnummern as $nr): ?>
          <?php
            $ist_eigener = $kamerad['spindnr'] == $nr;
            $vergeben = isset($belegte_spinde[$nr]);
            $text = $vergeben ? " (vergeben an {$belegte_spinde[$nr]})" : '';
          ?>
          <option value="<?= $nr ?>"
            <?= $ist_eigener ? 'selected' : '' ?>
            <?= (!$ist_eigener && $vergeben) ? 'disabled' : '' ?>>
            <?= $nr . $text ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>

    <h4 class="mb-4">Größen</h4>
    <div class="row g-3 mb-4">
      <div class="col-md-6">
        <label class="form-label">Einsatzjacke</label>
        <input type="text" name="groesse_jacke" value="<?= htmlspecialchars($kamerad['groesse_jacke']) ?>" class="form-control">
      </div>
      <div class="col-md-6">
        <label class="form-label">Einsatzhose</label>
        <input type="text" name="groesse_hose" value="<?= htmlspecialchars($kamerad['groesse_hose']) ?>" class="form-control">
      </div>
      <div class="col-md-6">
        <label class="form-label">Einsatzhose AGT</label>
        <input type="text" name="groesse_hose_agt" value="<?= htmlspecialchars($kamerad['groesse_hose_agt']) ?>" class="form-control">
      </div>
      <div class="col-md-6">
        <label class="form-label">Stiefel</label>
        <input type="text" name="groesse_stiefel" value="<?= htmlspecialchars($kamerad['groesse_stiefel']) ?>" class="form-control">
      </div>
    </div>

    <button type="submit" name="save" class="btn btn-primary">Speichern</button>
  </form>
</div>

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