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

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

$einheit = $_SESSION['einheit'];
$user_id = $_SESSION['user_id'];

// Fahrzeuge laden, die zur Einheit gehören
$stmt = $conn->prepare("SELECT * FROM ffw_fahrzeuge WHERE einheit = ? ORDER BY fahrzeugname ASC");
$stmt->bind_param("s", $einheit);
$stmt->execute();
$fahrzeuge = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Adressen laden
$adressen = $conn->query("SELECT * FROM adressen ORDER BY bezeichnung ASC")->fetch_all(MYSQLI_ASSOC);
?>

<div class="container my-5">
  <h2>📦 Neuer Lieferschein</h2>

  <form action="lieferschein_speichern.php" method="post">
    <div class="row mb-3">
      <div class="col-md-6">
        <label class="form-label">Empfänger</label>
        <input type="text" name="empfaenger" class="form-control" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">Lieferdatum</label>
        <input type="date" name="lieferdatum" class="form-control" required value="<?= date('Y-m-d') ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Zieladresse</label>
        <select name="adresse_id" class="form-select" required>
          <option value="">-- Adresse wählen --</option>
          <?php foreach ($adressen as $a): ?>
            <option value="<?= $a['id'] ?>"><?= htmlspecialchars($a['bezeichnung']) ?> – <?= $a['ort'] ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <ul class="nav nav-tabs mt-4" id="geraeteTabs" role="tablist">
      <?php foreach ($fahrzeuge as $index => $fahrzeug): ?>
        <li class="nav-item" role="presentation">
          <button class="nav-link <?= $index === 0 ? 'active' : '' ?>" id="tab-<?= $index ?>" data-bs-toggle="tab" data-bs-target="#fahrzeug-<?= $index ?>" type="button" role="tab">
            <?= htmlspecialchars($fahrzeug['fahrzeugname']) ?> (<?= htmlspecialchars($fahrzeug['fahrzeugkurz']) ?>)
          </button>
        </li>
      <?php endforeach; ?>
    </ul>

    <div class="tab-content border p-3" id="geraeteTabContent">
      <?php foreach ($fahrzeuge as $index => $fahrzeug):
        $stmt = $conn->prepare("SELECT * FROM ffw_geraete WHERE fahrzeug = ? AND einheit = ? AND status != 'Ausgesondert' ORDER BY bezeichnung ASC");
        $stmt->bind_param("ss", $fahrzeug['barcode_fzg'], $einheit);
        $stmt->execute();
        $geraete = $stmt->get_result();
      ?>
        <div class="tab-pane fade <?= $index === 0 ? 'show active' : '' ?>" id="fahrzeug-<?= $index ?>" role="tabpanel">
          <?php if ($geraete->num_rows > 0): ?>
            <div class="form-check">
              <?php while ($g = $geraete->fetch_assoc()): ?>
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="geraete[]" value="<?= $g['id'] ?>" id="g<?= $g['id'] ?>">
                  <label class="form-check-label" for="g<?= $g['id'] ?>">
                    <?= htmlspecialchars($g['bezeichnung']) ?> (<?= htmlspecialchars($g['barcode']) ?>)
                  </label>
                </div>
              <?php endwhile; ?>
            </div>
          <?php else: ?>
            <p>Keine Geräte für dieses Fahrzeug.</p>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>

    <hr class="my-4">

    <h5>➕ Freie Positionen (optional)</h5>
    <div id="freiePositionenContainer">
      <div class="row g-3 mb-2">
        <div class="col-md-5"><input type="text" name="freie_bezeichnung[]" class="form-control" placeholder="Bezeichnung"></div>
        <div class="col-md-3"><input type="text" name="freie_menge[]" class="form-control" placeholder="Menge"></div>
        <div class="col-md-4"><input type="text" name="freie_bemerkung[]" class="form-control" placeholder="Bemerkung"></div>
      </div>
    </div>
    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addPosition()">+ Weitere Position</button>

    <hr class="my-4">

    <button class="btn btn-success">✅ Lieferschein speichern</button>
  </form>
</div>

<script>
function addPosition() {
  const container = document.getElementById('freiePositionenContainer');
  const block = document.createElement('div');
  block.className = "row g-3 mb-2";
  block.innerHTML = `
    <div class="col-md-5"><input type="text" name="freie_bezeichnung[]" class="form-control" placeholder="Bezeichnung"></div>
    <div class="col-md-3"><input type="text" name="freie_menge[]" class="form-control" placeholder="Menge"></div>
    <div class="col-md-4"><input type="text" name="freie_bemerkung[]" class="form-control" placeholder="Bemerkung"></div>
  `;
  container.appendChild(block);
}
</script>

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