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

$barcode = $_POST['barcode'] ?? $_GET['barcode'] ?? '';
$benutzer = ($_SESSION['user_vorname'] ?? '') . ' ' . ($_SESSION['user_nachname'] ?? '');
if (trim($benutzer) === '') {
    $benutzer = $_SESSION['username'] ?? 'Unbekannt';
}

$success = false;

// Datei löschen
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 (file_exists($filePath)) {
            unlink($filePath);
        }

        $stmt = $conn->prepare("DELETE FROM geraete_uploads WHERE id = ?");
        $stmt->bind_param("i", $file_id);
        $stmt->execute();
    }
}

// Formular gespeichert?
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();

    $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();

    $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)) {
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $newName = uniqid() . '.' . $ext;
                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;
}

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();
    }
}

$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='alert alert-danger m-4'>Gerät nicht gefunden.</div>";
    include 'includes/footer.php';
    exit;
}

if ($success) {
    echo "<div class='alert alert-success m-4'>Gerät erfolgreich aktualisiert.</div>";
}

?>
<div class="container my-4">
  <a href="geraete.php" class="btn btn-secondary mb-3">&laquo; Zurück zur Übersicht</a>
  <h2 class="mb-4"><?= htmlspecialchars($geraet['bezeichnung']) ?></h2>

  <ul class="nav nav-tabs" id="editTabs" 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>
    <?php
$kommentar_count = 0;
$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 = $res['anzahl'] ?? 0;
?>
<li class="nav-item"><a class="nav-link" id="kommentare-tab" data-bs-toggle="tab" href="#kommentare" role="tab">Kommentare (<?= $kommentar_count ?>)</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 p-4 border border-top-0 bg-white rounded-bottom" id="editTabsContent">
    <div class="tab-pane fade show active" id="daten" role="tabpanel">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="barcode" value="<?= htmlspecialchars($barcode) ?>">
        <div class="mb-3"><label class="form-label">Bezeichnung</label><input type="text" name="bezeichnung" value="<?= htmlspecialchars($geraet['bezeichnung']) ?>" class="form-control"></div>
        <div class="mb-3"><label class="form-label">Baujahr</label><input type="date" name="baujahr" value="<?= is_numeric($geraet['baujahr']) ? date('Y-m-d', $geraet['baujahr']) : '' ?>" class="form-control"></div>
        <div class="mb-3"><label class="form-label">Letzte Prüfung</label><input type="date" name="lpruefung" value="<?= is_numeric($geraet['lpruefung']) ? date('Y-m-d', $geraet['lpruefung']) : '' ?>" class="form-control"></div>
        <div class="mb-3"><label class="form-label">Geräteraum</label><input type="text" name="gr" value="<?= htmlspecialchars($geraet['gr']) ?>" class="form-control"></div>
        <div class="mb-3"><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="mb-3"><label class="form-label">Seriennummer</label><input type="text" name="snnr" value="<?= htmlspecialchars($geraet['snnr']) ?>" class="form-control"></div>
        <div class="row">
          <div class="col"><label class="form-label">Anzahl</label><input type="text" name="anzahl" value="<?= htmlspecialchars($geraet['anzahl']) ?>" class="form-control"></div>
          <div class="col"><label class="form-label">Ist-Anzahl</label><input type="text" name="anzahlist" value="<?= htmlspecialchars($geraet['anzahlist']) ?>" class="form-control"></div>
        </div>
        <div class="mb-3 mt-3"><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="mb-3"><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="<?= htmlspecialchars($fz['barcode_fzg']) ?>" <?= $fz['barcode_fzg'] == $geraet['fahrzeug'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($fz['fahrzeugbezeichnung']) ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="mb-3"><label class="form-label">Memo</label><textarea name="memo" class="form-control"><?= htmlspecialchars($geraet['memo']) ?></textarea></div>
        <div class="mb-3"><label class="form-label">Anhänge</label><input type="file" name="anhang[]" multiple class="form-control"></div>
        <button type="submit" name="save" class="btn btn-primary">Speichern</button>
      </form>
    </div>

    <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();
      }
  }

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

  <form method="post" class="mb-4">
    <h5>Neue Wartung eintragen</h5>
    <input type="hidden" name="barcode" value="<?= htmlspecialchars($barcode) ?>">
    <div class="row">
      <div class="col-md-4">
        <label class="form-label">Wartungsdatum</label>
        <input type="date" name="wartung_datum" class="form-control" required>
      </div>
      <div class="col-md-6">
        <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 mt-4">
        <button type="submit" name="wartung_durchfuehren" class="btn btn-success mt-2">Speichern</button>
      </div>
    </div>
  </form>


  <h5>Vergangene Wartungen</h5>
  <?php if ($wartungen->num_rows === 0): ?>
    <p class="text-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 while ($w = $wartungen->fetch_assoc()): ?>
          <tr>
            <td><?= date("d.m.Y", strtotime($w['datum'])) ?></td>
            <td><?= htmlspecialchars($w['benutzer']) ?></td>
            <td><?= htmlspecialchars($w['notiz']) ?></td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>


    <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();

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

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

      <hr>
      <h5>Verknüpfte Dokumente</h5>
      <?php if ($dokumente->num_rows === 0): ?>
        <p class="text-muted">Keine verknüpften Dokumente vorhanden.</p>
      <?php else: ?>
        <div class="row">
          <?php while ($doc = $dokumente->fetch_assoc()): ?>
            <div class="col-md-6 mb-3">
              <div class="border p-3 rounded">
                📁 <?= htmlspecialchars($doc['kategorie']) ?> –
                <a href="uploads/dokumente/<?= htmlspecialchars($doc['dateiname']) ?>" target="_blank">
                  <?= htmlspecialchars($doc['dateiname']) ?>
                </a>
                <br><small class="text-muted"><?= date("d.m.Y H:i", strtotime($doc['hochgeladen_am'])) ?></small>
              </div>
            </div>
          <?php endwhile; ?>
        </div>
      <?php endif; ?>
    </div>


    <div class="tab-pane fade" id="kommentare" role="tabpanel">
      <form method="post" class="mb-3">
        <input type="hidden" name="barcode" value="<?= htmlspecialchars($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();
      while ($kommentar = $kommentare->fetch_assoc()): ?>
        <div class="mb-3">
          <div class="text-muted small">
  <strong><?= htmlspecialchars($kommentar['benutzer']) ?></strong> am <?= date("d.m.Y H:i", strtotime($kommentar['zeitstempel'])) ?>:
</div>
          <div class="border rounded p-2 bg-light"><?= nl2br(htmlspecialchars($kommentar['kommentar'])) ?></div>
        </div>
      <?php endwhile; ?>
    </div>

    <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">
                <?= htmlspecialchars($log['benutzer']) ?> am <?= date("d.m.Y H:i", strtotime($log['zeitstempel'])) ?>:
              </div>
              <div><?= htmlspecialchars($log['aktion']) ?></div>
            </li>
          <?php endwhile; ?>
        </ul>
      <?php endif; ?>
    </div>
  </div>
</div>

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