<?php
// lieferschein_neu.php – Sidebar Layout + Freitextfeld
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 ---- */
$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>
  /* --- GLOBAL SETTINGS --- */
  body {
      color: #000000;
      background-color: #f8f9fa;
  }

  /* Erzwinge schwarze Schrift für Standard-Elemente */
  .text-muted, .text-secondary, .form-text, .small, label, p, h1, h2, h3, h4, h5, h6 {
      color: #000000 !important;
  }

  /* Inputs: Weißer Hintergrund, Schwarze Schrift, dunklerer Rahmen */
  .form-control, .form-select, textarea {
      background-color: #ffffff !important;
      color: #000000 !important;
      border: 1px solid #adb5bd; /* Etwas dunkleres Grau */
  }
  .form-control:focus, .form-select:focus, textarea:focus {
      border-color: #0d6efd;
      box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
  }

  /* --- Sidebar Navigation (Links) --- */
  .nav-pills-vertical .nav-link {
      background-color: #ffffff; /* Weißer Hintergrund */
      color: #000000 !important; /* Schwarze Schrift */
      border: 1px solid #dee2e6;
      border-radius: 8px;
      margin-bottom: 8px;
      padding: 12px 16px;
      text-align: left;
      font-weight: 600;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: all 0.2s;
  }

  .nav-pills-vertical .nav-link:hover {
      background-color: #e9ecef; /* Hellgrau beim Hover */
      color: #000000 !important;
  }

  /* AKTIVER ZUSTAND: Blau mit WEISSER Schrift */
  .nav-pills-vertical .nav-link.active {
      background-color: #0d6efd !important; /* Blau */
      color: #ffffff !important; /* Weiß */
      border-color: #0d6efd;
      box-shadow: 0 4px 6px rgba(13, 110, 253, 0.3);
  }

  /* Icon im aktiven Tab weiß färben */
  .nav-pills-vertical .nav-link.active i {
      color: #ffffff !important;
  }

  /* --- Device Item (Mitte) --- */
  .device-item {
      background: #fff;
      border-bottom: 1px solid #dee2e6;
      padding: 12px 16px;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 15px;
      color: #000000;
  }
  .device-item:last-child { border-bottom: none; }
  .device-item:hover { background-color: #f1f1f1; }

  /* Wenn ausgewählt: Hellblau */
  .device-item:has(.device-checkbox:checked) {
      background-color: #e7f1ff;
      border-left: 4px solid #0d6efd; /* Markierung links */
  }

  /* Checkbox */
  .device-checkbox {
      width: 1.2em; height: 1.2em; cursor: pointer;
      border: 1px solid #000;
  }

  /* --- Cards & Layout --- */
  .card-section {
      border: 1px solid #dee2e6;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
      background: #fff;
      overflow: hidden;
  }

  .sticky-summary {
      position: sticky;
      top: 90px;
  }

  /* Suchleiste Header */
  .search-header {
      background: #ffffff;
      padding: 10px 15px;
      border-bottom: 1px solid #dee2e6;
  }

  /* Badges: Lesbar machen */
  .badge {
      color: #000 !important;
      border: 1px solid #ccc;
  }
  /* Dunkle Badges invertieren für Lesbarkeit */
  .badge.bg-dark {
      background-color: #343a40 !important;
      color: #fff !important; /* Weiß auf Dunkelgrau ist okay */
      border: none;
  }
  /* Helle Badges */
  .badge.bg-light {
      background-color: #f8f9fa !important;
      color: #000 !important;
  }
</style>

<div class="container-fluid px-4 my-4">

  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h3 class="fw-bold mb-0 text-black">📦 Neuer Lieferschein</h3>
      <div class="text-black">Einheit: <strong><?= h($einheit) ?></strong></div>
    </div>
    <div class="d-flex align-items-center gap-3">
       <div class="text-end d-none d-sm-block">
          <div class="small text-uppercase fw-bold text-black">Positionen</div>
          <div class="fs-4 fw-bold lh-1 text-black" id="kpiSelectedTop">0</div>
       </div>
    </div>
  </div>

  <form action="lieferschein_speichern.php" method="post" id="lsForm">

    <div class="card card-section mb-4 p-4">
       <div class="row g-3">
          <div class="col-md-3">
             <label class="form-label small text-uppercase">Lieferdatum</label>
             <input type="date" name="lieferdatum" class="form-control" required value="<?= h(date('Y-m-d')) ?>">
          </div>
          <div class="col-md-9">
             <label class="form-label small text-uppercase">Empfänger & 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>

          <div class="col-12">
             <label class="form-label small text-uppercase">Zusätzliche Infos / Hinweis</label>
             <textarea name="hinweis" class="form-control" rows="2" placeholder="Optionale Anmerkungen zum Lieferschein (z.B. Rückgabefrist, Defektinfo)..."></textarea>
          </div>
       </div>
    </div>

    <div class="row g-4">

      <div class="col-lg-3">
         <h6 class="fw-bold text-uppercase mb-3 small text-black">Fahrzeuge</h6>
         <?php if (count($fahrzeuge) > 0): ?>
            <div class="nav flex-column nav-pills nav-pills-vertical" id="v-pills-tab" role="tablist" aria-orientation="vertical">
               <?php foreach ($fahrzeuge as $i => $fz): ?>
                  <button class="nav-link <?= $i===0?'active':'' ?>" id="tab-<?= $i ?>" data-bs-toggle="pill" data-bs-target="#fahrzeug-<?= $i ?>" type="button" role="tab">
                     <span>
                        <?= h($fz['fzg_name'] ?: 'Fahrzeug') ?>
                        <?php if($fz['fzg_kurz']): ?>
                           <small class="ms-1 fw-bold">(<?= h($fz['fzg_kurz']) ?>)</small>
                        <?php endif; ?>
                     </span>
                     <i class="bi bi-chevron-right small"></i>
                  </button>
               <?php endforeach; ?>
            </div>
         <?php else: ?>
            <div class="alert alert-warning text-black">Keine Fahrzeuge gefunden.</div>
         <?php endif; ?>
      </div>

      <div class="col-lg-6">
         <h6 class="fw-bold text-uppercase mb-3 small text-black">Geräteauswahl</h6>

         <div class="card card-section min-vh-50">
            <?php if (count($fahrzeuge) > 0): ?>
               <div class="tab-content" id="v-pills-tabContent">
                  <?php foreach ($fahrzeuge as $i => $fz):
                     $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">

                     <div class="search-header d-flex gap-2">
                        <input type="text" class="form-control form-control-sm" placeholder="🔍 Suche in <?= h($fz['fzg_name']) ?>..." oninput="filterTab(<?= $i ?>, this.value)">
                        <button type="button" class="btn btn-sm btn-outline-dark" onclick="selectAllInTab(<?= $i ?>, true)">Alle</button>
                        <button type="button" class="btn btn-sm btn-outline-dark" onclick="selectAllInTab(<?= $i ?>, false)">Keine</button>
                     </div>

                     <div id="list-<?= $i ?>">
                        <?php if ($count > 0): ?>
                           <?php while($g = $geraete->fetch_assoc()):
                              $searchBlob = mb_strtolower(($g['bezeichnung'] ?? '').' '.$g['barcode'].' '.$g['kat'].' '.$g['gr']);
                           ?>
                              <label class="device-item" data-search="<?= h($searchBlob) ?>">
                                 <input class="form-check-input device-checkbox mt-0" type="checkbox" name="geraete[]" value="<?= (int)$g['id'] ?>" onchange="updateKPI()">
                                 <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                       <span class="fw-bold"><?= h($g['bezeichnung']) ?></span>
                                       <span class="badge bg-light"><?= h($g['gr'] ?: '?') ?></span>
                                    </div>
                                    <div class="small text-black">
                                       <i class="bi bi-upc-scan me-1"></i><?= h($g['barcode']) ?>
                                       <?= $g['kat'] ? ' &bull; '.h($g['kat']) : '' ?>
                                    </div>
                                 </div>
                              </label>
                           <?php endwhile; ?>
                        <?php else: ?>
                           <div class="p-5 text-center text-black">
                              <i class="bi bi-inbox fs-1 mb-2 d-block"></i>
                              Keine Geräte in diesem Fahrzeug.
                           </div>
                        <?php endif; ?>
                     </div>
                  </div>
                  <?php endforeach; ?>
               </div>
            <?php else: ?>
               <div class="p-5 text-center text-black">Bitte Fahrzeuge anlegen.</div>
            <?php endif; ?>
         </div>

         <h6 class="fw-bold text-uppercase mt-5 mb-3 small text-black">Zusatzmaterial</h6>
         <div class="card card-section">
            <div class="table-responsive">
              <table class="table align-middle mb-0" style="color:#000;">
                <thead class="bg-light">
                  <tr>
                    <th class="ps-3 border-0">Bezeichnung</th>
                    <th class="border-0" style="width:20%;">Menge</th>
                    <th class="border-0" style="width:25%;">Notiz</th>
                    <th class="border-0 text-end pe-3" style="width:50px;"></th>
                  </tr>
                </thead>
                <tbody id="freiePositionenBody">
                  <tr>
                    <td class="ps-3"><input type="text" name="freie_bezeichnung[]" class="form-control border-0 bg-light" placeholder="Freitext"></td>
                    <td><input type="text" name="freie_menge[]" class="form-control border-0 bg-light" placeholder="1"></td>
                    <td><input type="text" name="freie_bemerkung[]" class="form-control border-0 bg-light"></td>
                    <td class="pe-3 text-end">
                      <button type="button" class="btn btn-sm btn-light text-danger" onclick="addPositionRow()"><i class="bi bi-trash"></i></button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="card-footer bg-white border-0 text-center">
               <button type="button" class="btn btn-sm btn-link text-decoration-none text-black fw-bold" onclick="addPositionRow()">+ Zeile hinzufügen</button>
            </div>
         </div>

      </div>

      <div class="col-lg-3">
         <div class="sticky-summary">
            <div class="card card-section border shadow-sm bg-white mb-3">
               <div class="card-body">
                  <h6 class="text-uppercase fw-bold small mb-3 border-bottom pb-2 text-black">Gesamtstatus</h6>
                  <div class="d-flex justify-content-between align-items-center mb-2">
                     <span class="text-black">Geräte</span>
                     <span class="fs-5 fw-bold text-black" id="sumDevices">0</span>
                  </div>
                  <div class="d-flex justify-content-between align-items-center pt-2">
                     <span class="text-black">Freie Pos.</span>
                     <span class="fs-5 fw-bold text-black" id="sumFree">1</span>
                  </div>
               </div>
            </div>

            <div class="card card-section mb-3">
               <div class="card-body p-3">
                  <h6 class="fw-bold text-uppercase small mb-2 border-bottom pb-2 text-black">Empfänger</h6>
                  <div id="adressePreview">
                     <span class="small fst-italic text-black">Bitte oben auswählen...</span>
                  </div>
               </div>
            </div>

            <button class="btn btn-success w-100 py-3 fw-bold shadow text-white">
               <i class="bi bi-check-lg me-2"></i> Lieferschein erstellen
            </button>
            <div class="text-center mt-2">
               <a href="lieferscheine.php" class="small text-decoration-none text-black">Abbrechen</a>
            </div>
         </div>
      </div>

    </div>
  </form>
</div>

<script>
/* ---- Adresse Preview ---- */
const sel = document.getElementById('adresse_id');
const empfaengerHidden = document.getElementById('empfaenger_hidden');
const preview = document.getElementById('adressePreview');

function updateAdressePreview() {
  const opt = sel.options[sel.selectedIndex];
  if (!opt || !opt.value) {
    empfaengerHidden.value = '';
    preview.innerHTML = '<span class="small fst-italic">Bitte oben auswählen...</span>';
    return;
  }
  const bez = opt.dataset.bezeichnung || '';
  const ort = opt.dataset.ort || '';
  const str = opt.dataset.strasse || '';

  empfaengerHidden.value = bez;

  preview.innerHTML = `
    <div class="fw-bold">${bez}</div>
    <div class="small">${str}</div>
    <div class="small">${ort}</div>
  `;
}
sel.addEventListener('change', updateAdressePreview);

/* ---- KPI & Logic ---- */
function updateKPI() {
  const devices = document.querySelectorAll('.device-checkbox:checked');
  const count = devices.length;
  document.getElementById('kpiSelectedTop').textContent = count;
  document.getElementById('sumDevices').textContent = count;
}

function selectAllInTab(tabIndex, checked) {
  document.querySelectorAll(`#fahrzeug-${tabIndex} .device-checkbox`).forEach(cb => { cb.checked = checked; });
  updateKPI();
}

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)) ? 'flex' : 'none';
  });
}

const bodyFree = document.getElementById('freiePositionenBody');
function addPositionRow() {
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td class="ps-3"><input type="text" name="freie_bezeichnung[]" class="form-control border-0 bg-light" placeholder="Bezeichnung"></td>
    <td><input type="text" name="freie_menge[]" class="form-control border-0 bg-light" placeholder="1"></td>
    <td><input type="text" name="freie_bemerkung[]" class="form-control border-0 bg-light"></td>
    <td class="pe-3 text-end">
      <button type="button" class="btn btn-sm btn-light text-danger" onclick="this.closest('tr').remove(); updateFreeCount();"><i class="bi bi-trash"></i></button>
    </td>
  `;
  bodyFree.appendChild(tr);
  updateFreeCount();
}
function updateFreeCount() {
  document.getElementById('sumFree').textContent = bodyFree.querySelectorAll('tr').length;
}

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

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