<?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;
}

// Hilfsfunktionen
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function badge_due($lpruefung_ts){
    if (!is_numeric($lpruefung_ts) || $lpruefung_ts <= 0) {
        return ['label'=>'kein Datum','class'=>'badge bg-secondary'];
    }
    $naechste = strtotime('+1 year', (int)$lpruefung_ts);
    $tage = floor(($naechste - time())/86400);
    if ($tage < 7)      return ['label'=>"$tage T", 'class'=>'badge bg-danger'];
    if ($tage < 30)     return ['label'=>"$tage T", 'class'=>'badge bg-warning text-dark'];
    return ['label'=>"$tage T", 'class'=>'badge bg-success'];
}

// Request-Parameter
$barcode  = $_POST['barcode'] ?? $_GET['barcode'] ?? '';
$benutzer = trim((($_SESSION['user_vorname'] ?? '') . ' ' . ($_SESSION['user_nachname'] ?? ''))) ?: ($_SESSION['username'] ?? 'Unbekannt');

$success = false;

// Datei löschen (eigene Uploads)
if (isset($_POST['delete_file'])) {
    $file_id = (int)$_POST['delete_file'];
    $stmt = $conn->prepare("SELECT dateiname FROM geraete_uploads WHERE id = ?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();

    if ($res) {
        $filePath = __DIR__ . '/uploads/geraete/' . $res['dateiname'];
        if (is_file($filePath)) {
            @unlink($filePath);
        }
        $stmt = $conn->prepare("DELETE FROM geraete_uploads WHERE id = ?");
        $stmt->bind_param("i", $file_id);
        $stmt->execute();
    }
}

// Formular speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $stmt = $conn->prepare("UPDATE ffw_geraete
        SET bezeichnung=?, baujahr=?, gr=?, status=?, lpruefung=?, memo=?, anzahl=?, anzahlist=?, p_intervall=?, snnr=?, fahrzeug=?
        WHERE barcode=?");
    $stmt->bind_param(
        "sississsssss",
        $_POST['bezeichnung'],
        strtotime($_POST['baujahr']),
        $_POST['gr'],
        $_POST['status'],
        strtotime($_POST['lpruefung']),
        $_POST['memo'],
        $_POST['anzahl'],
        $_POST['anzahlist'],
        $_POST['p_intervall'],
        $_POST['snnr'],
        $_POST['fahrzeug'],
        $barcode
    );
    $stmt->execute();

    // Log
    $aktion = "Gerät bearbeitet (Status: {$_POST['status']}, GR: {$_POST['gr']}, Intervall: {$_POST['p_intervall']} Monate)";
    $stmt_log = $conn->prepare("INSERT INTO geraete_log (barcode, benutzer, aktion) VALUES (?, ?, ?)");
    $stmt_log->bind_param("sss", $barcode, $benutzer, $aktion);
    $stmt_log->execute();

    // Uploads
    $uploadPath    = __DIR__ . '/uploads/geraete/';
    $allowedTypes  = ['image/jpeg', 'image/png', 'application/pdf'];

    if (!empty($_FILES['anhang']['name'][0])) {
        foreach ($_FILES['anhang']['name'] as $index => $name) {
            $tmp    = $_FILES['anhang']['tmp_name'][$index];
            $type   = $_FILES['anhang']['type'][$index];
            $fehler = $_FILES['anhang']['error'][$index];

            if ($fehler === UPLOAD_ERR_OK && in_array($type, $allowedTypes, true)) {
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $newName = uniqid('g_', true) . '.' . $ext;
                if (!is_dir($uploadPath)) { @mkdir($uploadPath, 0775, true); }
                if (@move_uploaded_file($tmp, $uploadPath . $newName)) {
                    $stmt_upload = $conn->prepare("INSERT INTO geraete_uploads (barcode, dateiname, typ) VALUES (?, ?, ?)");
                    $stmt_upload->bind_param("sss", $barcode, $newName, $type);
                    $stmt_upload->execute();
                }
            }
        }
    }

    $success = true;
}

// Kommentar speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kommentar_absenden'])) {
    $kommentar = trim($_POST['kommentar']);
    if ($kommentar !== '') {
        $stmt_k = $conn->prepare("INSERT INTO geraete_kommentare (barcode, benutzer, kommentar) VALUES (?, ?, ?)");
        $stmt_k->bind_param("sss", $barcode, $benutzer, $kommentar);
        $stmt_k->execute();
    }
}

// Gerät laden
$stmt = $conn->prepare("SELECT * FROM ffw_geraete WHERE barcode = ?");
$stmt->bind_param("s", $barcode);
$stmt->execute();
$geraet = $stmt->get_result()->fetch_assoc();

if (!$geraet) {
    echo "<div class='container my-4'><div class='alert alert-danger'>Gerät nicht gefunden.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Due-Badge
$due = badge_due($geraet['lpruefung'] ?? 0);

// Fahrzeugbezeichnung laden
$fzgName = '';
if (!empty($geraet['fahrzeug'])) {
    $ef = $_SESSION['einheit'] ?? '';
    $sf = $conn->prepare("SELECT fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE barcode_fzg=? AND einheit=?");
    $sf->bind_param("ss", $geraet['fahrzeug'], $ef);
    $sf->execute();
    $rowF = $sf->get_result()->fetch_assoc();
    $fzgName = $rowF['fahrzeugbezeichnung'] ?? '';
}
?>
<style>
  .page-head { display:flex; gap:16px; align-items:flex-start; justify-content:space-between; }
  .meta { color:#6c757d; }
  .kpi-dot { display:inline-block; width:.6rem; height:.6rem; border-radius:999px; margin-right:.3rem; }
  .kpi-green { background:#198754; }
  .kpi-yellow{ background:#ffc107; }
  .kpi-red   { background:#dc3545; }
  .sticky-actions { position:sticky; top:60px; z-index:10; background:#fff; border-bottom:1px solid #eee; padding:.75rem 0; }
  .card-soft { border:1px solid #eee; border-radius:12px; }
  .doc-card { border:1px solid #eee; border-radius:10px; padding:12px }
  .doc-icon { font-size:1.4rem; }
  .small-muted { font-size:.9rem; color:#6c757d; }
</style>

<div class="container my-4">
  <a href="geraete.php" class="btn btn-outline-secondary mb-3">&laquo; Zurück zur Übersicht</a>

  <div class="page-head mb-2">
    <div>
      <h2 class="mb-1"><?= h($geraet['bezeichnung']) ?></h2>
      <div class="meta">
        <span class="me-3">Barcode: <span class="text-monospace"><?= h($geraet['barcode']) ?></span></span>
        <?php if ($fzgName): ?>
          <span class="me-3">Fahrzeug: <strong><?= h($fzgName) ?></strong></span>
        <?php endif; ?>
        <span>Fälligkeit: <span class="<?= h($due['class']) ?>"><?= h($due['label']) ?></span></span>
      </div>
    </div>
    <div class="text-end small text-muted">
      <div><span class="kpi-dot kpi-green"></span> ≥ 30 Tage</div>
      <div><span class="kpi-dot kpi-yellow"></span> &lt; 30 Tage</div>
      <div><span class="kpi-dot kpi-red"></span> &lt; 7 Tage</div>
    </div>
  </div>

  <?php if ($success): ?>
    <div class="alert alert-success">Gerät erfolgreich aktualisiert.</div>
  <?php endif; ?>

  <div class="sticky-actions">
    <div class="d-flex justify-content-between align-items-center">
      <ul class="nav nav-tabs border-0">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#daten">Daten</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#bilder">Dokumente</a></li>
        <?php
          $stmt = $conn->prepare("SELECT COUNT(*) AS anzahl FROM geraete_kommentare WHERE barcode=?");
          $stmt->bind_param("s", $barcode);
          $stmt->execute();
          $res = $stmt->get_result()->fetch_assoc();
          $kommentar_count = (int)($res['anzahl'] ?? 0);
        ?>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#kommentare">Kommentare (<?= $kommentar_count ?>)</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#log">Verlauf</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#wartung">Wartung</a></li>
      </ul>
      <button form="editForm" name="save" class="btn btn-primary">
        💾 Speichern
      </button>
    </div>
  </div>

  <div class="tab-content p-4 border border-top-0 bg-white rounded-bottom" id="editTabsContent">
    <!-- TAB: DATEN -->
    <div class="tab-pane fade show active" id="daten" role="tabpanel">
      <form method="post" id="editForm" enctype="multipart/form-data" class="row g-4">
        <input type="hidden" name="barcode" value="<?= h($barcode) ?>">

        <div class="col-lg-8">
          <div class="card-soft p-3">
            <div class="row g-3">
              <div class="col-md-8">
                <label class="form-label">Bezeichnung</label>
                <input type="text" name="bezeichnung" value="<?= h($geraet['bezeichnung']) ?>" class="form-control" required>
              </div>
              <div class="col-md-4">
                <label class="form-label">Baujahr</label>
                <input type="date" name="baujahr" value="<?= is_numeric($geraet['baujahr']) ? date('Y-m-d', (int)$geraet['baujahr']) : '' ?>" class="form-control">
              </div>

              <div class="col-md-4">
                <label class="form-label">Letzte Prüfung</label>
                <input type="date" name="lpruefung" value="<?= is_numeric($geraet['lpruefung']) ? date('Y-m-d', (int)$geraet['lpruefung']) : '' ?>" class="form-control">
                <div class="form-text">Nächste automatisch: +1 Jahr</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">Geräteraum</label>
                <input type="text" name="gr" value="<?= h($geraet['gr']) ?>" class="form-control">
              </div>
              <div class="col-md-4">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                  <option <?= $geraet['status'] == 'Einsatzbereit' ? 'selected' : '' ?>>Einsatzbereit</option>
                  <option <?= $geraet['status'] == 'Bedingt Einsatzbereit' ? 'selected' : '' ?>>Bedingt Einsatzbereit</option>
                  <option <?= $geraet['status'] == 'Nicht Einsatzbereit' ? 'selected' : '' ?>>Nicht Einsatzbereit</option>
                </select>
              </div>

              <div class="col-md-6">
                <label class="form-label">Seriennummer</label>
                <input type="text" name="snnr" value="<?= h($geraet['snnr']) ?>" class="form-control">
              </div>
              <div class="col-md-3">
                <label class="form-label">Anzahl</label>
                <input type="text" name="anzahl" value="<?= h($geraet['anzahl']) ?>" class="form-control">
              </div>
              <div class="col-md-3">
                <label class="form-label">Ist-Anzahl</label>
                <input type="text" name="anzahlist" value="<?= h($geraet['anzahlist']) ?>" class="form-control">
              </div>

              <div class="col-md-4">
                <label class="form-label">Prüfintervall</label>
                <select name="p_intervall" class="form-select">
                  <option value="1"  <?= $geraet['p_intervall'] == '1'  ? 'selected' : '' ?>>monatlich</option>
                  <option value="6"  <?= $geraet['p_intervall'] == '6'  ? 'selected' : '' ?>>halbjährlich</option>
                  <option value="12" <?= $geraet['p_intervall'] == '12' ? 'selected' : '' ?>>jährlich</option>
                  <option value="48" <?= $geraet['p_intervall'] == '48' ? 'selected' : '' ?>>alle 4 Jahre</option>
                </select>
              </div>

              <div class="col-md-8">
                <label class="form-label">Fahrzeug</label>
                <select name="fahrzeug" class="form-select">
                  <?php
                  $einheit = $_SESSION['einheit'] ?? '';
                  $stmt_fahrzeuge = $conn->prepare("SELECT barcode_fzg, fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE einheit = ? ORDER BY fahrzeugbezeichnung");
                  $stmt_fahrzeuge->bind_param("s", $einheit);
                  $stmt_fahrzeuge->execute();
                  $fahrzeuge = $stmt_fahrzeuge->get_result();
                  while ($fz = $fahrzeuge->fetch_assoc()): ?>
                    <option value="<?= h($fz['barcode_fzg']) ?>" <?= $fz['barcode_fzg'] == $geraet['fahrzeug'] ? 'selected' : '' ?>>
                      <?= h($fz['fahrzeugbezeichnung']) ?>
                    </option>
                  <?php endwhile; ?>
                </select>
              </div>

              <div class="col-12">
                <label class="form-label">Memo</label>
                <textarea name="memo" rows="4" class="form-control" placeholder="Hinweise, Besonderheiten, letzte Maßnahmen …"><?= h($geraet['memo']) ?></textarea>
              </div>

              <div class="col-12">
                <label class="form-label">Anhänge</label>
                <input type="file" name="anhang[]" multiple class="form-control">
                <div class="form-text">Erlaubt: JPG, PNG, PDF</div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-lg-4">
          <div class="card-soft p-3">
            <h6 class="mb-3">Geräte-Kurzinfo</h6>
            <div class="d-flex justify-content-between">
              <span>Letzte Prüfung</span>
              <strong><?= is_numeric($geraet['lpruefung']) ? date("d.m.Y", (int)$geraet['lpruefung']) : '—' ?></strong>
            </div>
            <div class="d-flex justify-content-between">
              <span>Nächste Prüfung</span>
              <?php
                $lp = is_numeric($geraet['lpruefung']) ? (int)$geraet['lpruefung'] : 0;
                $np = $lp ? strtotime('+1 year', $lp) : 0;
              ?>
              <strong><?= $np ? date("d.m.Y", $np) : '—' ?></strong>
            </div>
            <hr>
            <div class="d-flex justify-content-between">
              <span>Status</span>
              <span class="badge bg-light text-dark"><?= h($geraet['status'] ?: '—') ?></span>
            </div>
            <div class="d-flex justify-content-between">
              <span>Geräteraum</span>
              <span class="text-monospace"><?= h($geraet['gr'] ?: '—') ?></span>
            </div>
            <div class="d-flex justify-content-between">
              <span>Fahrzeug</span>
              <span class="text-end" style="max-width:60%"><?= $fzgName ? h($fzgName) : '—' ?></span>
            </div>
          </div>
        </div>

        <!-- Der eigentliche Speichern-Button ist oben in der Sticky-Bar -->
      </form>
    </div>

    <!-- TAB: WARTUNG -->
    <div class="tab-pane fade" id="wartung" role="tabpanel">
      <?php
      if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['wartung_durchfuehren'])) {
          $wartung_datum = $_POST['wartung_datum'] ?? '';
          $wartung_notiz = $_POST['wartung_notiz'] ?? '';

          if ($wartung_datum) {
              $timestamp = strtotime($wartung_datum);

              // Wartung eintragen
              $stmt = $conn->prepare("INSERT INTO geraete_wartung (barcode, datum, benutzer, notiz) VALUES (?, ?, ?, ?)");
              $stmt->bind_param("ssss", $barcode, date('Y-m-d H:i:s', $timestamp), $benutzer, $wartung_notiz);
              $stmt->execute();

              // lpruefung aktualisieren
              $stmt = $conn->prepare("UPDATE ffw_geraete SET lpruefung = ? WHERE barcode = ?");
              $stmt->bind_param("is", $timestamp, $barcode);
              $stmt->execute();

              echo "<div class='alert alert-success'>Wartung erfolgreich gespeichert.</div>";

              // Gerät neu laden
              $stmt = $conn->prepare("SELECT * FROM ffw_geraete WHERE barcode = ?");
              $stmt->bind_param("s", $barcode);
              $stmt->execute();
              $geraet = $stmt->get_result()->fetch_assoc();
              $due = badge_due($geraet['lpruefung'] ?? 0);
          }
      }

      $stmt = $conn->prepare("SELECT * FROM geraete_wartung WHERE barcode = ? ORDER BY datum DESC");
      $stmt->bind_param("s", $barcode);
      $stmt->execute();
      $wartungen = $stmt->get_result();
      ?>

      <div class="card-soft p-3 mb-4">
        <form method="post" class="row g-3 align-items-end">
          <input type="hidden" name="barcode" value="<?= h($barcode) ?>">
          <div class="col-md-3">
            <label class="form-label">Wartungsdatum</label>
            <input type="date" name="wartung_datum" class="form-control" required>
          </div>
          <div class="col-md-7">
            <label class="form-label">Notiz</label>
            <input type="text" name="wartung_notiz" class="form-control" placeholder="z. B. Filter getauscht">
          </div>
          <div class="col-md-2">
            <button type="submit" name="wartung_durchfuehren" class="btn btn-success w-100">Speichern</button>
          </div>
        </form>
      </div>

      <h5>Vergangene Wartungen</h5>
      <?php if ($wartungen->num_rows === 0): ?>
        <p class="text-muted">Keine Wartungen vorhanden.</p>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-striped align-middle">
            <thead class="table-light">
              <tr>
                <th>Datum</th>
                <th>Benutzer</th>
                <th>Notiz</th>
              </tr>
            </thead>
            <tbody>
              <?php while ($w = $wartungen->fetch_assoc()): ?>
                <tr>
                  <td><?= date("d.m.Y", strtotime($w['datum'])) ?></td>
                  <td><?= h($w['benutzer']) ?></td>
                  <td><?= h($w['notiz']) ?></td>
                </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>

    <!-- TAB: DOKUMENTE -->
    <div class="tab-pane fade" id="bilder" role="tabpanel">
      <?php
      // Eigene Anhänge
      $stmt = $conn->prepare("SELECT * FROM geraete_uploads WHERE barcode = ? ORDER BY hochgeladen_am DESC");
      $stmt->bind_param("s", $barcode);
      $stmt->execute();
      $uploads = $stmt->get_result();

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

      <div class="mb-3 d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Geräte-Anhänge</h5>
        <span class="small-muted">Neu hochladen im Tab „Daten“</span>
      </div>

      <?php if ($uploads->num_rows === 0): ?>
        <p class="text-muted">Keine Geräte-Anhänge vorhanden.</p>
      <?php else: ?>
        <div class="row g-3">
          <?php while ($file = $uploads->fetch_assoc()): ?>
            <div class="col-md-6">
              <div class="doc-card">
                <div class="d-flex align-items-start justify-content-between">
                  <div>
                    <div class="doc-icon"><?= $file['typ'] === 'application/pdf' ? '📄' : '🖼️' ?></div>
                    <a href="uploads/geraete/<?= h($file['dateiname']) ?>" target="_blank">
                      <?= h($file['dateiname']) ?>
                    </a>
                    <div class="small-muted"><?= date("d.m.Y H:i", strtotime($file['hochgeladen_am'])) ?></div>
                  </div>
                  <form method="post" onsubmit="return confirm('Wirklich löschen?')">
                    <input type="hidden" name="delete_file" value="<?= (int)$file['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger">Löschen</button>
                  </form>
                </div>
              </div>
            </div>
          <?php endwhile; ?>
        </div>
      <?php endif; ?>

      <hr class="my-4">

      <h5>Verknüpfte Dokumente (DMS)</h5>
      <?php if ($dokumente->num_rows === 0): ?>
        <p class="text-muted">Keine verknüpften Dokumente vorhanden.</p>
      <?php else: ?>
        <div class="row g-3">
          <?php while ($doc = $dokumente->fetch_assoc()): ?>
            <div class="col-md-6">
              <div class="doc-card">
                <div class="d-flex align-items-start justify-content-between">
                  <div>
                    <div>📁 <?= h($doc['kategorie']) ?></div>
                    <a href="uploads/dokumente/<?= h($doc['dateiname']) ?>" target="_blank">
                      <?= h($doc['dateiname']) ?>
                    </a>
                    <div class="small-muted"><?= date("d.m.Y H:i", strtotime($doc['hochgeladen_am'])) ?></div>
                  </div>
                </div>
              </div>
            </div>
          <?php endwhile; ?>
        </div>
      <?php endif; ?>
    </div>

    <!-- TAB: KOMMENTARE -->
    <div class="tab-pane fade" id="kommentare" role="tabpanel">
      <form method="post" class="mb-3">
        <input type="hidden" name="barcode" value="<?= h($barcode) ?>">
        <textarea name="kommentar" class="form-control mb-2" placeholder="Kommentar hinzufügen …"></textarea>
        <button type="submit" name="kommentar_absenden" class="btn btn-dark">Kommentar speichern</button>
      </form>
      <hr>
      <?php
      $stmt = $conn->prepare("SELECT * FROM geraete_kommentare WHERE barcode = ? ORDER BY zeitstempel DESC");
      $stmt->bind_param("s", $barcode);
      $stmt->execute();
      $kommentare = $stmt->get_result();
      if ($kommentare->num_rows === 0): ?>
        <p class="text-muted">Keine Kommentare vorhanden.</p>
      <?php else:
        while ($kommentar = $kommentare->fetch_assoc()): ?>
          <div class="mb-3">
            <div class="small text-muted mb-1">
              <strong><?= h($kommentar['benutzer']) ?></strong>
              am <?= date("d.m.Y H:i", strtotime($kommentar['zeitstempel'])) ?>:
            </div>
            <div class="border rounded p-2 bg-light"><?= nl2br(h($kommentar['kommentar'])) ?></div>
          </div>
        <?php endwhile; ?>
      <?php endif; ?>
    </div>

    <!-- TAB: VERLAUF -->
    <div class="tab-pane fade" id="log" role="tabpanel">
      <?php
      $stmt = $conn->prepare("SELECT * FROM geraete_log WHERE barcode = ? ORDER BY zeitstempel DESC");
      $stmt->bind_param("s", $barcode);
      $stmt->execute();
      $logs = $stmt->get_result();
      if ($logs->num_rows === 0): ?>
        <p class="text-muted">Keine Einträge vorhanden.</p>
      <?php else: ?>
        <ul class="list-group">
          <?php while ($log = $logs->fetch_assoc()): ?>
            <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 endwhile; ?>
        </ul>
      <?php endif; ?>
    </div>
  </div>
</div>

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