<?php
ob_start();
session_start();

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

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

// --- Flash aus Session ziehen ---
$fehler   = $_SESSION['geraet_fehler']   ?? null;
$success  = $_SESSION['geraet_success']  ?? null;
$formdata = $_SESSION['geraet_formdata'] ?? [];
unset($_SESSION['geraet_fehler'], $_SESSION['geraet_success'], $_SESSION['geraet_formdata']);

// --- Session-Werte ---
$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$barcode_car  = $_GET['c'] ?? '';

// --- CSRF Token (für Aktionen auf dieser Seite) ---
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(16));
}
$CSRF = $_SESSION['csrf'];

// --- POST: Gerät aussondern (auf gleicher Seite verarbeitet) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'aussondern') {
    if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
        $_SESSION['geraet_fehler'] = 'Sicherheitsprüfung fehlgeschlagen.';
        header("Location: " . strtok($_SERVER["REQUEST_URI"],'?') . (!empty($barcode_car) ? '?c='.urlencode($barcode_car) : ''));
        exit;
    }

    $geraet_id = (int)($_POST['geraet_id'] ?? 0);

    if ($geraet_id > 0 && $user_einheit !== '') {
        $stmt = $conn->prepare("UPDATE ffw_geraete SET status = 'Ausgesondert' WHERE id = ? AND einheit = ?");
        $stmt->bind_param("is", $geraet_id, $user_einheit);
        $stmt->execute();
        $rows = $stmt->affected_rows;
        $stmt->close();

        if ($rows > 0) {
            $_SESSION['geraet_success'] = "Gerät wurde ausgesondert.";
        } else {
            $_SESSION['geraet_fehler'] = "Gerät konnte nicht ausgesondert werden.";
        }
    } else {
        $_SESSION['geraet_fehler'] = "Ungültige Anfrage.";
    }

    header("Location: " . strtok($_SERVER["REQUEST_URI"],'?') . (!empty($barcode_car) ? '?c='.urlencode($barcode_car) : ''));
    exit;
}

// --- Daten vorbereiten ---
$einheiten = $conn->query("SELECT DISTINCT einheit, gemeinde_id FROM users WHERE einheit != ''")->fetch_all(MYSQLI_ASSOC);

// Fahrzeuge der eigenen Einheit
$stmtFzg = $conn->prepare("SELECT barcode_fzg, fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE einheit = ? ORDER BY fahrzeugbezeichnung ASC");
$stmtFzg->bind_param("s", $user_einheit);
$stmtFzg->execute();
$fahrzeuge_result = $stmtFzg->get_result();

// Fahrzeugname (wenn Auswahl gesetzt)
$fahrzeugname = '';
if (!empty($barcode_car)) {
    $stmtName = $conn->prepare("SELECT fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE barcode_fzg = ? AND einheit = ?");
    $stmtName->bind_param("ss", $barcode_car, $user_einheit);
    $stmtName->execute();
    $resultName = $stmtName->get_result();
    if ($row = $resultName->fetch_assoc()) {
        $fahrzeugname = $row["fahrzeugbezeichnung"];
    }
    $stmtName->close();
}

// Geräte laden
$rows = [];
if (!empty($barcode_car)) {
  $stmt = $conn->prepare("SELECT * FROM ffw_geraete
                          WHERE fahrzeug = ?
                          AND einheit = ?
                          AND status != 'Ausgesondert'
                          ORDER BY gr, bezeichnung");
  $stmt->bind_param("ss", $barcode_car, $user_einheit);
  $stmt->execute();
  $res = $stmt->get_result();
  while ($r = $res->fetch_assoc()) { $rows[] = $r; }
}

// Dropdown-Daten (für Modal)
$kategorien    = $conn->query("SELECT DISTINCT kat FROM ffw_geraete WHERE kat != '' ORDER BY kat ASC");
$geraeteraeume = $conn->query("SELECT DISTINCT gr FROM ffw_geraete WHERE gr != '' ORDER BY gr ASC");
$statuswerte   = $conn->query("SELECT DISTINCT status FROM ffw_geraete WHERE status != '' ORDER BY status ASC");

// KPI berechnen
$total = count($rows);
$frei  = 0;
$f30   = 0; // fällig < 30 Tage
$f7    = 0; // fällig < 7 Tage
$now   = time();

foreach ($rows as $r) {
    if (mb_strtolower((string)$r['status']) === 'frei') $frei++;

    $lpruef_ts = is_numeric($r['lpruefung'] ?? null) ? (int)$r['lpruefung'] : 0;
    $naechste  = $lpruef_ts > 0 ? strtotime('+1 year', $lpruef_ts) : 0;
    if ($naechste > 0) {
        $tage = floor(($naechste - $now) / 86400);
        if ($tage < 30) $f30++;
        if ($tage < 7)  $f7++;
    }
}

// für Favoritenstatus pro Zeile brauchen wir schnelle Checks → sammeln IDs
$geraeteFav = [];
if ($total > 0) {
    $ids = array_map(fn($r)=>(int)$r['id'], $rows);
    $in  = implode(',', array_fill(0, count($ids), '?'));
    $typesFav = str_repeat('i', count($ids));
    $stmtFav = $conn->prepare("SELECT geraet_id FROM ffw_favoriten WHERE user_id = ? AND geraet_id IN ($in)");
    $bind = [$typesFav]; $params = [];
    foreach($ids as $i=>$v){ $params[] = &$ids[$i]; }
    // bind user_id + ids
    $stmtFav->bind_param('i'.$typesFav, $user_id, ...$ids);
    $stmtFav->execute();
    $rf = $stmtFav->get_result();
    while($f = $rf->fetch_assoc()){ $geraeteFav[(int)$f['geraet_id']] = true; }
    $stmtFav->close();
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Geräteübersicht</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
    .kpi-val{font-size:1.6rem;font-weight:700}
    .kpi-sub{font-size:.9rem;color:#6c757d}
    .table thead th{white-space:nowrap}
    .status-pill{border-radius:999px;padding:.2rem .6rem;font-size:.85rem;border:1px solid rgba(0,0,0,.08)}
    .status-frei{background:#e7f5ff}
    .status-einsatz{background:#e6fcf5}
    .status-wartung{background:#fff4e6}
    .due-good{background:#e6fcf5}
    .due-warn{background:#fff4e6}
    .due-bad{background:#fff5f5}
    .filter-chip{border-radius:999px;border:1px solid #e9ecef;padding:.35rem .6rem;cursor:pointer;user-select:none}
    .filter-chip.active{background:#e9ecef}
    .search-mini{max-width:260px}
    .table tr td .text-muted.small{line-height:1}
    .table > :not(caption) > * > *{ vertical-align: middle; }
  </style>
</head>
<body>

<div class="container mt-4">
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-3">
    <div>
      <h1 class="mb-1">Geräteübersicht</h1>
      <?php if ($fahrzeugname): ?>
        <div class="text-muted">Fahrzeug: <strong><?= htmlspecialchars($fahrzeugname) ?></strong></div>
      <?php endif; ?>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#geraeteModal">➕ Gerät hinzufügen</button>
    </div>
  </div>

  <?php if ($fehler): ?>
    <div class="alert alert-danger mt-3"><?= htmlspecialchars($fehler) ?></div>
  <?php endif; ?>
  <?php if ($success): ?>
    <div class="alert alert-success mt-3"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <!-- Auswahl Fahrzeug -->
  <form method="get" class="card shadow-sm mt-3 p-3">
    <div class="row g-3 align-items-center">
      <div class="col-md-6">
        <label class="form-label mb-1">Fahrzeug wählen</label>
        <select name="c" id="c" onchange="this.form.submit()" class="form-select">
          <option value="">– Fahrzeug auswählen –</option>
          <?php if ($fahrzeuge_result): while ($fzg = $fahrzeuge_result->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($fzg['barcode_fzg']) ?>" <?= ($fzg['barcode_fzg'] == $barcode_car ? 'selected' : '') ?>>
              <?= htmlspecialchars($fzg['fahrzeugbezeichnung']) ?>
            </option>
          <?php endwhile; endif; ?>
        </select>
      </div>
      <div class="col-md-6 text-md-end">
        <span class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= htmlspecialchars($user_einheit) ?></span></span>
      </div>
    </div>
  </form>

  <!-- KPIs -->
  <div class="row g-3 mt-3">
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-val"><?= $total ?></div><div class="kpi-sub">Gesamt</div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-val"><?= $frei ?></div><div class="kpi-sub">Status „frei“</div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-val"><?= $f30 ?></div><div class="kpi-sub">Fälligkeit &lt; 30 Tage</div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-val"><?= $f7 ?></div><div class="kpi-sub">Fälligkeit &lt; 7 Tage</div></div></div>
  </div>

  <!-- Client-Filter -->
  <div class="card shadow-sm mt-3">
    <div class="card-body">
      <div class="d-flex flex-wrap align-items-center gap-2">
        <input type="text" id="q" class="form-control search-mini" placeholder="Suchen (Bezeichnung, Barcode, Kategorie, Raum, Status)">
        <div class="vr d-none d-md-block"></div>
        <div class="d-flex flex-wrap gap-2">
          <span class="filter-chip" data-filter="due:good">grün (OK)</span>
          <span class="filter-chip" data-filter="due:warn">gelb (&lt;30)</span>
          <span class="filter-chip" data-filter="due:bad">rot (&lt;7)</span>
          <span class="filter-chip" data-filter="fav:yes">★ Favoriten</span>
        </div>
        <div class="ms-auto">
          <button class="btn btn-outline-secondary btn-sm" id="resetFilters">Filter löschen</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Tabelle -->
  <div class="card shadow-sm mt-3">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0" id="tbl">
        <thead class="table-light">
          <tr>
            <th>Bezeichnung</th>
            <th>Barcode</th>
            <th>Kategorie</th>
            <th>Geräteraum</th>
            <th>Status</th>
            <th>Letzte Prüfung</th>
            <th>Nächste Prüfung</th>
            <th class="text-end" style="width:60px;"></th>
          </tr>
        </thead>
        <tbody>
        <?php if (empty($rows) && !empty($barcode_car)): ?>
          <tr><td colspan="8" class="text-center text-muted py-4">Keine Geräte für dieses Fahrzeug gefunden.</td></tr>
        <?php elseif (empty($rows)): ?>
          <tr><td colspan="8" class="text-center text-muted py-4">Bitte oben ein Fahrzeug auswählen.</td></tr>
        <?php else: foreach ($rows as $row):
          // Prüfdaten
          $lpruef_ts = is_numeric($row['lpruefung'] ?? null) ? (int)$row['lpruefung'] : 0;
          $naechste  = $lpruef_ts > 0 ? strtotime('+1 year', $lpruef_ts) : 0;
          $tage_diff = $naechste > 0 ? floor(($naechste - time()) / 86400) : null;

          // Due Klasse
          $dueCls = 'due-good';
          if (!is_null($tage_diff)) {
            if ($tage_diff < 7)      $dueCls = 'due-bad';
            elseif ($tage_diff < 30) $dueCls = 'due-warn';
          } else {
            $dueCls = ''; // kein Datum
          }

          // Status Pill
          $st = strtolower((string)$row['status']);
          $stClass = 'status-pill';
          if (str_contains($st,'frei')) $stClass .= ' status-frei';
          elseif (str_contains($st,'einsatz')) $stClass .= ' status-einsatz';
          elseif (str_contains($st,'wart')) $stClass .= ' status-wartung';

          // Favorit
          $is_fav = !empty($geraeteFav[(int)$row['id']]);
        ?>
          <tr data-search="<?= htmlspecialchars(strtolower(($row['bezeichnung']??'').' '.$row['barcode'].' '.$row['kat'].' '.$row['gr'].' '.$row['status'])) ?>"
              data-due="<?= $dueCls ?: 'none' ?>"
              data-fav="<?= $is_fav ? 'yes' : 'no' ?>">
            <td>
              <div class="fw-semibold"><?= htmlspecialchars($row['bezeichnung']) ?></div>
              <div class="text-muted small"><?= htmlspecialchars($row['kat'] ?: '—') ?></div>
            </td>
            <td class="text-monospace"><?= htmlspecialchars($row['barcode']) ?></td>
            <td><?= htmlspecialchars($row['kat'] ?: '—') ?></td>
            <td><?= htmlspecialchars($row['gr'] ?: '—') ?></td>
            <td><span class="<?= $stClass ?>"><?= htmlspecialchars($row['status'] ?: '—') ?></span></td>
            <td><?= $lpruef_ts > 0 ? date("d.m.Y", $lpruef_ts) : '—' ?></td>
            <td class="<?= $dueCls ?> fw-semibold"><?= $naechste > 0 ? date("d.m.Y", $naechste) : '—' ?></td>
            <td class="text-end">
              <div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                  Aktionen
                </button>
                <div class="dropdown-menu dropdown-menu-end">
                  <form method="post" action="geraet_edit.php" class="px-3 py-1">
                    <input type="hidden" name="barcode" value="<?= htmlspecialchars($row['barcode']) ?>">
                    <button type="submit" class="dropdown-item">Bearbeiten</button>
                  </form>

                  <div class="px-3 py-1">
                    <form method="post" action="favorit_toggle.php">
                      <input type="hidden" name="geraet_id" value="<?= (int)$row['id'] ?>">
                      <button class="dropdown-item" name="toggle_fav">
                        <?= $is_fav ? '★ Favorit entfernen' : '☆ Als Favorit merken' ?>
                      </button>
                    </form>
                  </div>

                  <?php if (mb_strtolower($row['status']) !== 'ausgesondert'): ?>
                    <div><hr class="dropdown-divider"></div>
                    <form method="post" class="px-3 py-1" onsubmit="return confirm('Soll dieses Gerät wirklich ausgesondert werden?');">
                      <input type="hidden" name="action" value="aussondern">
                      <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                      <input type="hidden" name="geraet_id" value="<?= (int)$row['id'] ?>">
                      <button type="submit" class="dropdown-item text-danger">🗑 Aussondern</button>
                    </form>
                  <?php endif; ?>
                </div>
              </div>
            </td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- MODAL: Neues Gerät -->
<div class="modal fade <?= $fehler ? 'show d-block' : '' ?>" id="geraeteModal" tabindex="-1" aria-labelledby="geraeteModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form method="post" action="geraet_add.php" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Neues Gerät hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body">
        <?php
        // Fahrzeuge-Liste fürs Modal erneut laden
        $stmtFzg->execute();
        $fahrzeuge_neu = $stmtFzg->get_result();
        ?>
        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label">Einheit</label>
            <select name="einheit" id="einheit" class="form-select" required onchange="setGemeinde(this.value)">
              <option value="">Bitte wählen</option>
              <?php foreach ($einheiten as $e): ?>
                <option value="<?= htmlspecialchars($e['einheit']) ?>" <?= ($formdata['einheit'] ?? '') === $e['einheit'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($e['einheit']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Gemeinde-ID</label>
            <input type="text" name="gemeinde" id="gemeinde" class="form-control" readonly value="<?= htmlspecialchars($formdata['gemeinde'] ?? '') ?>">
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label">Fahrzeug</label>
          <select name="fahrzeug" class="form-select" required>
            <option value="">Bitte wählen</option>
            <?php while ($f = $fahrzeuge_neu->fetch_assoc()): ?>
              <option value="<?= htmlspecialchars($f['barcode_fzg']) ?>" <?= ($formdata['fahrzeug'] ?? '') === $f['barcode_fzg'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($f['fahrzeugbezeichnung']) ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>

        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label">Bezeichnung</label>
            <input type="text" name="bezeichnung" class="form-control" required value="<?= htmlspecialchars($formdata['bezeichnung'] ?? '') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Barcode</label>
            <input type="text" name="barcode" id="barcode" class="form-control" required value="<?= htmlspecialchars($formdata['barcode'] ?? '') ?>">
            <div id="barcode-feedback" class="small mt-1"></div>
          </div>
        </div>

        <div class="row mb-3">
          <div class="col-md-4">
            <label class="form-label">Kategorie</label>
            <select name="kat" class="form-select">
              <option value="">Bitte wählen</option>
              <?php if ($kategorien) while ($k = $kategorien->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($k['kat']) ?>" <?= ($formdata['kat'] ?? '') === $k['kat'] ? 'selected' : '' ?>><?= htmlspecialchars($k['kat']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Geräteraum</label>
            <select name="gr" class="form-select">
              <option value="">Bitte wählen</option>
              <?php if ($geraeteraeume) while ($g = $geraeteraeume->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($g['gr']) ?>" <?= ($formdata['gr'] ?? '') === $g['gr'] ? 'selected' : '' ?>><?= htmlspecialchars($g['gr']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option value="">Bitte wählen</option>
              <?php if ($statuswerte) while ($s = $statuswerte->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($s['status']) ?>" <?= ($formdata['status'] ?? '') === $s['status'] ? 'selected' : '' ?>><?= htmlspecialchars($s['status']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
        </div>

        <div class="row mb-2">
          <div class="col-md-6">
            <label class="form-label">Letzte Prüfung</label>
            <input type="date" name="lpruefung" class="form-control" value="<?= htmlspecialchars($formdata['lpruefung'] ?? '') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Baujahr</label>
            <input type="number" name="baujahr" class="form-control" min="1900" max="<?= date('Y') ?>" value="<?= htmlspecialchars($formdata['baujahr'] ?? '') ?>">
          </div>
        </div>

      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success" id="submitBtn">💾 Speichern</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const einheitZuGemeinde = <?= json_encode(array_column($einheiten, 'gemeinde_id', 'einheit'), JSON_UNESCAPED_UNICODE) ?>;
function setGemeinde(einheit) {
  document.getElementById('gemeinde').value = einheitZuGemeinde[einheit] ?? '';
}

document.addEventListener("DOMContentLoaded", function () {
  // Barcode Livecheck (wie gehabt)
  const barcodeInput = document.getElementById('barcode');
  const einheitSelect = document.getElementById('einheit');
  const feedback = document.getElementById('barcode-feedback');
  const submitBtn = document.getElementById('submitBtn');

  async function checkBarcode() {
    if (!barcodeInput || !einheitSelect) return;
    const barcode = barcodeInput.value.trim();
    const einheit = einheitSelect.value;

    if (!barcode || !einheit) {
      feedback.textContent = '';
      feedback.className = 'small mt-1';
      if (submitBtn) submitBtn.disabled = false;
      return;
    }
    try {
      const res = await fetch(`ajax_check_barcode.php?barcode=${encodeURIComponent(barcode)}&einheit=${encodeURIComponent(einheit)}`);
      const data = await res.json();
      if (data.exists) {
        feedback.textContent = '❌ Dieser Barcode ist in dieser Einheit bereits vergeben.';
        feedback.className = 'text-danger small mt-1';
        if (submitBtn) submitBtn.disabled = true;
      } else {
        feedback.textContent = '✅ Barcode ist verfügbar.';
        feedback.className = 'text-success small mt-1';
        if (submitBtn) submitBtn.disabled = false;
      }
    } catch (err) {
      feedback.textContent = '';
      if (submitBtn) submitBtn.disabled = false;
    }
  }
  if (barcodeInput) barcodeInput.addEventListener('input', checkBarcode);
  if (einheitSelect) einheitSelect.addEventListener('change', checkBarcode);

  // Client-Filter / Suche
  const q = document.getElementById('q');
  const chips = document.querySelectorAll('.filter-chip');
  const reset = document.getElementById('resetFilters');
  const rows = Array.from(document.querySelectorAll('#tbl tbody tr'));

  function applyFilters() {
    const text = (q.value || '').trim().toLowerCase();
    const active = Array.from(chips).filter(c => c.classList.contains('active')).map(c => c.dataset.filter);

    rows.forEach(tr => {
      const s = tr.dataset.search || '';
      const due = tr.dataset.due || 'none';
      const fav = tr.dataset.fav || 'no';

      let ok = true;

      if (text) ok = ok && s.includes(text);

      for (const f of active) {
        if (f.startsWith('due:')) {
          const want = f.split(':')[1];
          ok = ok && (due === want);
        }
        if (f === 'fav:yes') ok = ok && (fav === 'yes');
      }

      tr.style.display = ok ? '' : 'none';
    });
  }

  chips.forEach(c => c.addEventListener('click', () => { c.classList.toggle('active'); applyFilters(); }));
  if (q) q.addEventListener('input', applyFilters);
  if (reset) reset.addEventListener('click', (e) => {
    e.preventDefault();
    q.value = '';
    chips.forEach(c => c.classList.remove('active'));
    applyFilters();
  });
});
</script>
</body>
</html>
