<?php
// lieferschein_neu.php – Neuer Lieferschein (logischere UI, wie geraete.php)
ob_start();
session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';

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

$einheit  = $_SESSION['einheit'] ?? '';
$user_id  = (int)($_SESSION['user_id'] ?? 0);
if ($einheit === '') {
  echo "<div class='container my-5'><div class='alert alert-warning'>⚠️ Keine Einheit in der Session gefunden. Bitte erneut einloggen.</div></div>";
  include 'includes/footer.php'; ob_end_flush(); exit;
}

/* ---- Fahrzeuge der eigenen Einheit laden (robust) ---- */
$stmtF = $conn->prepare("
  SELECT
    id,
    barcode_fzg,
    COALESCE(fahrzeugname, '') AS fzg_name,
    COALESCE(fahrzeugkurz, '') AS fzg_kurz
  FROM ffw_fahrzeuge
  WHERE einheit = ?
  ORDER BY fahrzeugname ASC
");
$stmtF->bind_param("s", $einheit);
$stmtF->execute();
$fahrzeuge = $stmtF->get_result()->fetch_all(MYSQLI_ASSOC);
$stmtF->close();


/* ---- Adressen laden ---- */
$adressen = [];
$resAdr = $conn->query("SELECT id, bezeichnung, strasse, plz, ort, hinweis FROM adressen ORDER BY bezeichnung ASC");
while($r = $resAdr->fetch_assoc()){ $adressen[] = $r; }

/* ---- Helper ---- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<style>
  .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
  .kpi-val{font-size:1.4rem;font-weight:700}
  .kpi-sub{font-size:.9rem;color:#6c757d}
  .sticky-summary{position:sticky; top:84px}
  .device-row small{color:#6c757d}
</style>

<div class="container my-5">
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">📦 Neuer Lieferschein</h2>
      <div class="text-muted">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>
    <div class="kpi-card">
      <div class="kpi-sub">Ausgewählte Positionen</div>
      <div class="kpi-val"><span id="kpiSelected">0</span></div>
    </div>
  </div>

  <form action="lieferschein_speichern.php" method="post" id="lsForm">
    <div class="row g-3">
      <!-- Linke Spalte: Formularfelder + Tabs -->
      <div class="col-lg-8">
        <div class="card shadow-sm mb-3">
          <div class="card-body">
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">Lieferdatum</label>
                <input type="date" name="lieferdatum" class="form-control" required value="<?= h(date('Y-m-d')) ?>">
              </div>
              <div class="col-md-8">
                <label class="form-label">Empfänger &amp; Zieladresse</label>
                <select name="adresse_id" id="adresse_id" class="form-select" required>
                  <option value="">-- Adresse wählen --</option>
                  <?php foreach ($adressen as $a):
                    $adrLine = trim(($a['strasse'] ?? '').', '.($a['plz'] ?? '').' '.($a['ort'] ?? ''));
                  ?>
                    <option
                      value="<?= (int)$a['id'] ?>"
                      data-bezeichnung="<?= h($a['bezeichnung']) ?>"
                      data-strasse="<?= h($a['strasse'] ?? '') ?>"
                      data-plz="<?= h($a['plz'] ?? '') ?>"
                      data-ort="<?= h($a['ort'] ?? '') ?>"
                      data-hinweis="<?= h($a['hinweis'] ?? '') ?>"
                    >
                      <?= h($a['bezeichnung']) ?> — <?= h($adrLine) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <input type="hidden" name="empfaenger" id="empfaenger_hidden" value="">
                <div id="adressePreview" class="form-text mt-2">
                  <em>Wähle eine Adresse, um Details hier anzuzeigen.</em>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Fahrzeug-Tabs -->
        <?php if (count($fahrzeuge) > 0): ?>
          <ul class="nav nav-tabs" id="geraeteTabs" role="tablist">
            <?php foreach ($fahrzeuge as $i => $fz): ?>
              <li class="nav-item" role="presentation">
                <button class="nav-link <?= $i===0?'active':'' ?>" id="tab-<?= $i ?>" data-bs-toggle="tab" data-bs-target="#fahrzeug-<?= $i ?>" type="button" role="tab">
                  <?= h($fz['fzg_name'] ?: 'Fahrzeug') ?><?= $fz['fzg_kurz'] ? ' ('.h($fz['fzg_kurz']).')' : '' ?>
                </button>
              </li>
            <?php endforeach; ?>
          </ul>

          <div class="tab-content border border-top-0 rounded-bottom p-3" id="geraeteTabContent">
            <?php foreach ($fahrzeuge as $i => $fz):
              // Geräte des Fahrzeugs laden
              $stmtG = $conn->prepare("
                SELECT id, bezeichnung, barcode, kat, gr
                  FROM ffw_geraete
                 WHERE fahrzeug = ? AND einheit = ? AND status != 'Ausgesondert'
              ORDER BY bezeichnung ASC
              ");
              $stmtG->bind_param("ss", $fz['barcode_fzg'], $einheit);
              $stmtG->execute();
              $geraete = $stmtG->get_result();
              $count = $geraete->num_rows;
            ?>
              <div class="tab-pane fade <?= $i===0?'show active':'' ?>" id="fahrzeug-<?= $i ?>" role="tabpanel" aria-labelledby="tab-<?= $i ?>">
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
                  <div class="text-muted">
                    <small><span class="badge text-bg-light"><?= (int)$count ?></span> Geräte</small>
                  </div>
                  <div class="d-flex gap-2">
                    <input type="text" class="form-control form-control-sm" placeholder="🔍 Suche in diesem Fahrzeug…" oninput="filterTab(<?= $i ?>, this.value)">
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllInTab(<?= $i ?>, true)">Alle</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllInTab(<?= $i ?>, false)">Keine</button>
                  </div>
                </div>

                <?php if ($count > 0): ?>
                  <div class="list-group" id="list-<?= $i ?>">
                    <?php while($g = $geraete->fetch_assoc()):
                      $searchBlob = mb_strtolower(($g['bezeichnung'] ?? '').' '.$g['barcode'].' '.$g['kat'].' '.$g['gr']);
                    ?>
                      <label class="list-group-item d-flex align-items-start gap-3 device-row" data-search="<?= h($searchBlob) ?>">
                        <input class="form-check-input mt-1 device-checkbox" type="checkbox" name="geraete[]" value="<?= (int)$g['id'] ?>" onchange="updateKPI()">
                        <div>
                          <div class="fw-semibold"><?= h($g['bezeichnung']) ?> <span class="text-muted">(#<?= h($g['barcode']) ?>)</span></div>
                          <small><?= h($g['kat'] ?: '—') ?> • Raum: <?= h($g['gr'] ?: '—') ?></small>
                        </div>
                      </label>
                    <?php endwhile; ?>
                  </div>
                <?php else: ?>
                  <div class="alert alert-light mb-0">Keine Geräte für dieses Fahrzeug.</div>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <div class="alert alert-warning">Für deine Einheit wurden noch keine Fahrzeuge hinterlegt.</div>
        <?php endif; ?>

        <hr class="my-4">

        <!-- Freie Positionen -->
        <h5 class="mb-2">➕ Freie Positionen (optional)</h5>
        <div class="table-responsive">
          <table class="table align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:45%;">Bezeichnung</th>
                <th style="width:20%;">Menge</th>
                <th style="width:25%;">Bemerkung</th>
                <th class="text-end" style="width:10%;"></th>
              </tr>
            </thead>
            <tbody id="freiePositionenBody">
              <tr>
                <td><input type="text" name="freie_bezeichnung[]" class="form-control" placeholder="z. B. Schläuche, Zubehör"></td>
                <td><input type="text" name="freie_menge[]" class="form-control" placeholder="z. B. 3 Stk."></td>
                <td><input type="text" name="freie_bemerkung[]" class="form-control" placeholder="optional"></td>
                <td class="text-end">
                  <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addPositionRow()">+</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="d-flex justify-content-between mt-4">
          <a href="lieferscheine.php" class="btn btn-outline-secondary">Abbrechen</a>
          <button class="btn btn-success">✅ Lieferschein speichern</button>
        </div>
      </div>

      <!-- Rechte Spalte: Zusammenfassung (sticky) -->
      <div class="col-lg-4">
        <div class="sticky-summary">
          <div class="card shadow-sm">
            <div class="card-body">
              <h5 class="card-title mb-3">Zusammenfassung</h5>
              <div class="d-flex justify-content-between">
                <span>Ausgewählte Geräte</span>
                <strong><span id="sumDevices">0</span></strong>
              </div>
              <div class="d-flex justify-content-between mt-1">
                <span>Freie Positionen</span>
                <strong><span id="sumFree">1</span></strong>
              </div>
              <hr>
              <div class="small text-muted">Adresse</div>
              <div id="addrCard" class="mt-1">
                <em>Noch keine Adresse gewählt.</em>
              </div>
            </div>
            <div class="card-footer d-flex gap-2">
              <button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="selectAllGlobal(true)">Alle Geräte</button>
              <button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="selectAllGlobal(false)">Keine Geräte</button>
            </div>
          </div>
          <div class="text-muted small mt-2">
            Tipp: Du kannst in jedem Tab suchen, alle/keine auswählen und unten freie Positionen ergänzen.
          </div>
        </div>
      </div>
    </div>
  </form>
</div>

<script>
/* ---- Adresse Preview + Hidden Empfänger ---- */
const sel = document.getElementById('adresse_id');
const empfaengerHidden = document.getElementById('empfaenger_hidden');
const preview = document.getElementById('adressePreview');
const addrCard = document.getElementById('addrCard');

function updateAdressePreview() {
  const opt = sel.options[sel.selectedIndex];
  if (!opt || !opt.value) {
    empfaengerHidden.value = '';
    preview.innerHTML = '<em>Wähle eine Adresse, um Details hier anzuzeigen.</em>';
    addrCard.innerHTML = '<em>Noch keine Adresse gewählt.</em>';
    return;
  }
  const bez = opt.dataset.bezeichnung || '';
  const str = opt.dataset.strasse || '';
  const plz = opt.dataset.plz || '';
  const ort = opt.dataset.ort || '';
  const hin = opt.dataset.hinweis || '';

  empfaengerHidden.value = bez;

  const block = `
    <div class="card card-body py-2">
      <div><strong>${bez}</strong></div>
      <div>${str ? str + '<br>' : ''}${(plz || ort) ? (plz + ' ' + ort) : ''}</div>
      ${hin ? `<div class="text-muted small mt-1"><i class="bi bi-info-circle"></i> ${hin}</div>` : ''}
    </div>`;
  preview.innerHTML = block;
  addrCard.innerHTML  = block;
}
sel.addEventListener('change', updateAdressePreview);
document.addEventListener('DOMContentLoaded', updateAdressePreview);

/* ---- Geräte-Auswahl KPI ---- */
function updateKPI() {
  const devices = document.querySelectorAll('.device-checkbox:checked');
  document.getElementById('kpiSelected').textContent = devices.length;
  document.getElementById('sumDevices').textContent  = devices.length;
}
function selectAllInTab(tabIndex, checked) {
  document.querySelectorAll(`#fahrzeug-${tabIndex} .device-checkbox`).forEach(cb => { cb.checked = checked; });
  updateKPI();
}
function selectAllGlobal(checked) {
  document.querySelectorAll('.device-checkbox').forEach(cb => { cb.checked = checked; });
  updateKPI();
}

/* ---- Tab-Suche ---- */
function filterTab(tabIndex, term) {
  const t = (term || '').trim().toLowerCase();
  document.querySelectorAll(`#fahrzeug-${tabIndex} [data-search]`).forEach(row => {
    const s = row.getAttribute('data-search') || '';
    row.style.display = (!t || s.includes(t)) ? '' : 'none';
  });
}

/* ---- Freie Positionen dynamisch ---- */
const bodyFree = document.getElementById('freiePositionenBody');
function addPositionRow() {
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td><input type="text" name="freie_bezeichnung[]" class="form-control" placeholder="Bezeichnung"></td>
    <td><input type="text" name="freie_menge[]" class="form-control" placeholder="Menge"></td>
    <td><input type="text" name="freie_bemerkung[]" class="form-control" placeholder="Bemerkung"></td>
    <td class="text-end">
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)">×</button>
    </td>
  `;
  bodyFree.appendChild(tr);
  updateFreeCount();
}
function removeRow(btn) {
  const tr = btn.closest('tr');
  if (!tr) return;
  tr.remove();
  updateFreeCount();
}
function updateFreeCount() {
  const rows = bodyFree.querySelectorAll('tr');
  document.getElementById('sumFree').textContent = rows.length;
}

/* ---- Init ---- */
document.addEventListener('DOMContentLoaded', () => {
  updateKPI();
  updateFreeCount();
});
</script>

<?php include 'includes/footer.php'; ob_end_flush(); ?>
