<?php
// geraet_landing.php – Read-only Landingpage für ein Gerät (ohne Menü, ohne Login)

declare(strict_types=1);
ini_set('display_errors', '1');
error_reporting(E_ALL);

// DB-Verbindung einbinden (Pfad ggf. anpassen)
require __DIR__ . '/includes/db.php';

// ID aus Query lesen (Pflicht)
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    http_response_code(400);
    echo "<!doctype html><html lang='de'><head><meta charset='utf-8'><title>Fehler</title></head><body><div style='padding:2rem;font-family:system-ui,sans-serif'>Ungültige ID.</div></body></html>";
    exit;
}

// Gerät laden (per ID); Barcode wird für verknüpfte Tabellen benötigt
$stmt = $conn->prepare("SELECT * FROM ffw_geraete WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$geraet = $stmt->get_result()->fetch_assoc();

if (!$geraet) {
    http_response_code(404);
    echo "<!doctype html><html lang='de'><head><meta charset='utf-8'><title>Nicht gefunden</title></head><body><div style='padding:2rem;font-family:system-ui,sans-serif'>Gerät wurde nicht gefunden.</div></body></html>";
    exit;
}

$barcode = $geraet['barcode'] ?? '';

// Daten für die Tabs (read-only) vorausladen
// Uploads (eigene)
$stmt = $conn->prepare("SELECT id, dateiname, typ, hochgeladen_am FROM geraete_uploads WHERE barcode = ? ORDER BY hochgeladen_am DESC");
$stmt->bind_param("s", $barcode);
$stmt->execute();
$uploads = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Dokumente (DMS)
$stmt = $conn->prepare("SELECT id, kategorie, dateiname, hochgeladen_am FROM dokumente WHERE barcode = ? ORDER BY hochgeladen_am DESC");
$stmt->bind_param("s", $barcode);
$stmt->execute();
$dokumente = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Kommentare (nur Anzeige)
$stmt = $conn->prepare("SELECT benutzer, kommentar, zeitstempel FROM geraete_kommentare WHERE barcode = ? ORDER BY zeitstempel DESC");
$stmt->bind_param("s", $barcode);
$stmt->execute();
$kommentare = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Verlauf/Log (nur Anzeige)
$stmt = $conn->prepare("SELECT benutzer, aktion, zeitstempel FROM geraete_log WHERE barcode = ? ORDER BY zeitstempel DESC");
$stmt->bind_param("s", $barcode);
$stmt->execute();
$logs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Wartungen (nur Anzeige)
$stmt = $conn->prepare("SELECT datum, benutzer, notiz FROM geraete_wartung WHERE barcode = ? ORDER BY datum DESC");
$stmt->bind_param("s", $barcode);
$stmt->execute();
$wartungen = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Hilfsfunktionen
function h(?string $v): string { return htmlspecialchars((string)($v ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function d(?int $ts): string { return is_numeric($ts) && (int)$ts > 0 ? date('d.m.Y', (int)$ts) : '—'; }

/**
 * Mappt Status -> Bootstrap-Badge-Klasse.
 * Bekannte Status:
 * - Einsatzbereit            -> success (grün)
 * - Bedingt Einsatzbereit    -> warning (gelb)
 * - Nicht Einsatzbereit      -> danger (rot)
 * - In Prüfung               -> info (blau)
 * - Ausgesondert             -> dark (dunkel)
 * Fallback: secondary (grau)
 */
function status_badge_class(?string $status): string {
    $s = mb_strtolower(trim((string)$status));
    return match ($s) {
        'einsatzbereit'               => 'text-bg-success',
        'bedingt einsatzbereit'       => 'text-bg-warning',
        'nicht einsatzbereit'         => 'text-bg-danger',
        'in prüfung', 'in pruefung'   => 'text-bg-info',
        'ausgesondert'                => 'text-bg-dark',
        default                       => 'text-bg-secondary',
    };
}
$badgeClass = status_badge_class($geraet['status'] ?? '');
?>
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= h($geraet['bezeichnung']) ?> – Gerät</title>

  <!-- Bootstrap 5 (CDN) -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    :root { --brand:#0d6efd; }
    body { background:#f6f7fb; }
    .page { max-width: 1100px; margin: 40px auto; }
    .card { box-shadow: 0 6px 20px rgba(0,0,0,.06); border:0; }
    .badge-status { font-weight: 600; letter-spacing:.2px; }
    .label { color:#6c757d; font-size:.875rem; }
    .value { font-weight:600; }
    .file-tile { display:flex; align-items:center; gap:.75rem; padding:.75rem; border:1px solid #e9ecef; border-radius:.5rem; background:#fff; }
    .muted { color:#6c757d; }
    .tab-pane { background:#fff; border:1px solid #dee2e6; border-top:0; border-radius:0 0 .5rem .5rem; padding:1.25rem; }
    .topbar { display:flex; flex-wrap:wrap; align-items:center; gap:1rem; margin-bottom:1rem; }
    @media print {
      .no-print { display:none !important; }
      body { background:#fff; }
      .page { margin:0; max-width:100%; }
      .tab-pane { border:0; padding:0; }
      .nav-tabs { display:none; }
    }
  </style>
</head>
<body>
  <div class="page">
    <div class="card p-4">
      <div class="topbar">
        <div>
          <div class="label">Asset</div>
          <h2 class="mb-0"><?= h($geraet['bezeichnung']) ?></h2>
        </div>
        <div class="ms-auto d-flex align-items-center gap-2 no-print">
          <a href="javascript:window.print()" class="btn btn-outline-secondary"><i class="bi bi-printer"></i> Drucken</a>
        </div>
      </div>

      <div class="d-flex flex-wrap gap-4 mb-3">
        <div>
          <div class="label">Barcode</div>
          <div class="value"><?= h($geraet['barcode']) ?></div>
        </div>
        <div>
          <div class="label">Seriennummer</div>
          <div class="value"><?= h($geraet['snnr']) ?: '—' ?></div>
        </div>
        <div>
          <div class="label">Baujahr</div>
          <div class="value"><?= d((int)$geraet['baujahr']) ?></div>
        </div>
        <div>
          <div class="label">Letzte Prüfung</div>
          <div class="value"><?= d((int)$geraet['lpruefung']) ?></div>
        </div>
        <div>
          <div class="label">Prüfintervall</div>
          <div class="value"><?= h($geraet['p_intervall']) ?> Monate</div>
        </div>
        <div>
          <div class="label">Status</div>
          <span class="badge <?= $badgeClass ?> badge-status"><?= h($geraet['status']) ?></span>
        </div>
        <div>
          <div class="label">Geräteraum</div>
          <div class="value"><?= h($geraet['gr']) ?: '—' ?></div>
        </div>
      </div>

      <!-- Tabs -->
      <ul class="nav nav-tabs no-print" id="viewTabs" role="tablist">
        <li class="nav-item"><a class="nav-link active" id="daten-tab" data-bs-toggle="tab" href="#daten" role="tab">Daten</a></li>
        <li class="nav-item"><a class="nav-link" id="bilder-tab" data-bs-toggle="tab" href="#bilder" role="tab">Bilder / Dokumente</a></li>
        <li class="nav-item"><a class="nav-link" id="kommentare-tab" data-bs-toggle="tab" href="#kommentare" role="tab">Kommentare (<?= count($kommentare) ?>)</a></li>
        <li class="nav-item"><a class="nav-link" id="log-tab" data-bs-toggle="tab" href="#log" role="tab">Verlauf</a></li>
        <li class="nav-item"><a class="nav-link" id="wartung-tab" data-bs-toggle="tab" href="#wartung" role="tab">Wartung</a></li>
      </ul>

      <div class="tab-content" id="viewTabsContent">
        <!-- Daten -->
        <div class="tab-pane fade show active" id="daten" role="tabpanel" aria-labelledby="daten-tab">
          <div class="row g-3">
            <div class="col-md-6">
              <div class="label">Bezeichnung</div>
              <div class="value"><?= h($geraet['bezeichnung']) ?></div>
            </div>
            <div class="col-md-3">
              <div class="label">Anzahl</div>
              <div class="value"><?= h($geraet['anzahl']) ?></div>
            </div>
            <div class="col-md-3">
              <div class="label">Ist-Anzahl</div>
              <div class="value"><?= h($geraet['anzahlist']) ?></div>
            </div>
            <div class="col-12">
              <div class="label">Memo</div>
              <div class="value" style="white-space:pre-wrap"><?= h($geraet['memo']) ?: '—' ?></div>
            </div>
          </div>
        </div>

        <!-- Bilder / Dokumente -->
        <div class="tab-pane fade" id="bilder" role="tabpanel" aria-labelledby="bilder-tab">
          <h6 class="mb-3">Geräte-Anhänge</h6>
          <?php if (!count($uploads)): ?>
            <p class="muted">Keine Geräte-Anhänge vorhanden.</p>
          <?php else: ?>
            <div class="row g-3">
              <?php foreach ($uploads as $file): ?>
                <div class="col-md-6">
                  <div class="file-tile">
                    <div><?= $file['typ'] === 'application/pdf' ? '📄' : '🖼️' ?></div>
                    <div>
                      <a href="<?= 'uploads/geraete/' . h($file['dateiname']) ?>" target="_blank"><?= h($file['dateiname']) ?></a><br>
                      <small class="muted"><?= date("d.m.Y H:i", strtotime($file['hochgeladen_am'])) ?></small>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

          <hr class="my-4">
          <h6 class="mb-3">Verknüpfte Dokumente (DMS)</h6>
          <?php if (!count($dokumente)): ?>
            <p class="muted">Keine verknüpften Dokumente vorhanden.</p>
          <?php else: ?>
            <div class="row g-3">
              <?php foreach ($dokumente as $doc): ?>
                <div class="col-md-6">
                  <div class="file-tile">
                    <div>📁</div>
                    <div>
                      <div class="muted"><?= h($doc['kategorie']) ?></div>
                      <a href="<?= 'uploads/dokumente/' . h($doc['dateiname']) ?>" target="_blank"><?= h($doc['dateiname']) ?></a><br>
                      <small class="muted"><?= date("d.m.Y H:i", strtotime($doc['hochgeladen_am'])) ?></small>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>

        <!-- Kommentare (nur Anzeige) -->
        <div class="tab-pane fade" id="kommentare" role="tabpanel" aria-labelledby="kommentare-tab">
          <?php if (!count($kommentare)): ?>
            <p class="muted">Keine Kommentare vorhanden.</p>
          <?php else: ?>
            <?php foreach ($kommentare as $k): ?>
              <div class="mb-3">
                <div class="small text-muted">
                  <strong><?= h($k['benutzer']) ?></strong> am <?= date("d.m.Y H:i", strtotime($k['zeitstempel'])) ?>:
                </div>
                <div class="border rounded p-2 bg-light"><?= nl2br(h($k['kommentar'])) ?></div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>

        <!-- Verlauf (nur Anzeige) -->
        <div class="tab-pane fade" id="log" role="tabpanel" aria-labelledby="log-tab">
          <?php if (!count($logs)): ?>
            <p class="muted">Keine Einträge vorhanden.</p>
          <?php else: ?>
            <ul class="list-group">
              <?php foreach ($logs as $log): ?>
                <li class="list-group-item">
                  <div class="small text-muted">
                    <?= h($log['benutzer']) ?> am <?= date("d.m.Y H:i", strtotime($log['zeitstempel'])) ?>:
                  </div>
                  <div><?= h($log['aktion']) ?></div>
                </li>
              <?php endforeach; ?>
            </ul>
          <?php endif; ?>
        </div>

        <!-- Wartung (nur Anzeige) -->
        <div class="tab-pane fade" id="wartung" role="tabpanel" aria-labelledby="wartung-tab">
          <?php if (!count($wartungen)): ?>
            <p class="muted">Keine Wartungen vorhanden.</p>
          <?php else: ?>
            <table class="table table-bordered">
              <thead class="table-light">
                <tr><th>Datum</th><th>Benutzer</th><th>Notiz</th></tr>
              </thead>
              <tbody>
                <?php foreach ($wartungen as $w): ?>
                  <tr>
                    <td><?= date("d.m.Y", strtotime($w['datum'])) ?></td>
                    <td><?= h($w['benutzer']) ?></td>
                    <td><?= h($w['notiz']) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap JS (Tabs) -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</body>
</html>
