<?php
// mobile_app.php – Mobile Version der Geräteübersicht (PWA)
ob_start();
session_start();

// Datenbank und Session-Logik (Pfad ggf. anpassen!)
require_once __DIR__ . '/includes/db.php';

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

// --- Identische Logik wie im Original-Skript ---
$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$barcode_car  = $_GET['c'] ?? '';

// CSRF
if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf'];

// Datenabfrage (Identisch zur Desktop-Version)
$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();
    $resName = $stmtName->get_result();
    if ($r = $resName->fetch_assoc()) $fahrzeugname = $r["fahrzeugbezeichnung"];
}

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

// Favoriten laden
$geraeteFav = [];
if (count($rows) > 0) {
    $ids = array_map(fn($r)=>(int)$r['id'], $rows);
    $in  = implode(',', array_fill(0, count($ids), '?'));
    $stmtFav = $conn->prepare("SELECT geraet_id FROM ffw_favoriten WHERE user_id = ? AND geraet_id IN ($in)");
    $stmtFav->execute(array_merge([$user_id], $ids)); // PHP 8.1+ style execute
    $rf = $stmtFav->get_result();
    while($f = $rf->fetch_assoc()){ $geraeteFav[(int)$f['geraet_id']] = true; }
}

// Fahrzeuge für Dropdown (Header)
$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();
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Geräte App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#0d6efd">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

  <link rel="manifest" href="manifest.json">

  <link rel="icon" type="image/png" sizes="192x192" href="icon-192.png">
  <link rel="apple-touch-icon" href="icon-192.png">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

  <style>
    body { background-color: #f0f2f5; padding-bottom: 80px; /* Platz für FAB */ }
    .app-header { background: #0d6efd; color: white; padding: 15px; position: sticky; top:0; z-index: 1000; shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .select-vehicle { background: rgba(255,255,255,0.2); border:none; color:white; }
    .select-vehicle option { color: black; }

    /* Card Design */
    .device-card { border: none; border-radius: 12px; margin-bottom: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); background: white; transition: transform 0.1s; }
    .device-card:active { transform: scale(0.98); }
    .card-status-bar { height: 6px; border-radius: 12px 12px 0 0; }
    .status-ok { background-color: #198754; }
    .status-warn { background-color: #ffc107; }
    .status-bad { background-color: #dc3545; }

    /* Floating Action Button */
    .fab { position: fixed; bottom: 20px; right: 20px; width: 60px; height: 60px; border-radius: 50%; background: #0d6efd; color: white; display: flex; align-items: center; justify-content: center; font-size: 28px; box-shadow: 0 4px 10px rgba(13, 110, 253, 0.4); border: none; z-index: 2000; }

    /* Search Bar */
    .search-sticky { position: sticky; top: 60px; z-index: 990; background: #f0f2f5; padding: 10px 0; }
    .search-input { border-radius: 20px; border: none; box-shadow: 0 2px 5px rgba(0,0,0,0.05); padding-left: 40px; }
    .search-icon { position: absolute; left: 15px; top: 18px; color: #999; }
  </style>
</head>
<body>

<div class="app-header d-flex justify-content-between align-items-center">
  <div class="fw-bold fs-5"><i class="bi bi-box-seam"></i> Inventar</div>
  <a href="index.php" class="text-white text-decoration-none small">Desktop <i class="bi bi-box-arrow-up-right"></i></a>
</div>

<div class="container">

  <div class="mt-3">
    <form method="get">
      <select name="c" class="form-select form-select-lg shadow-sm border-0" onchange="this.form.submit()">
        <option value="">-- Fahrzeug wählen --</option>
        <?php while($f = $fahrzeuge_result->fetch_assoc()): ?>
          <option value="<?= $f['barcode_fzg'] ?>" <?= $barcode_car==$f['barcode_fzg']?'selected':'' ?>>
             <?= htmlspecialchars($f['fahrzeugbezeichnung']) ?>
          </option>
        <?php endwhile; ?>
      </select>
    </form>
  </div>

  <?php if (!empty($barcode_car)): ?>
    <div class="search-sticky">
       <i class="bi bi-search search-icon"></i>
       <input type="text" id="mobSearch" class="form-control search-input" placeholder="Gerät suchen...">
    </div>

    <div id="deviceList">
      <?php if(empty($rows)): ?>
         <div class="text-center text-muted mt-5">Keine Geräte geladen.</div>
      <?php else: foreach($rows as $r):
          // Logik für Statusfarben
          $lpruef = (int)$r['lpruefung'];
          $next   = $lpruef > 0 ? strtotime('+1 year', $lpruef) : 0;
          $days   = $next > 0 ? floor(($next - time())/86400) : 999;

          $colorClass = 'status-ok';
          if($days < 30) $colorClass = 'status-warn';
          if($days < 7)  $colorClass = 'status-bad';

          $isFav = isset($geraeteFav[$r['id']]);
      ?>

      <div class="card device-card" data-search="<?= strtolower($r['bezeichnung'].' '.$r['barcode']) ?>">
        <div class="card-status-bar <?= $colorClass ?>"></div>
        <div class="card-body py-3">
          <div class="d-flex justify-content-between align-items-start">
             <div>
               <h6 class="fw-bold mb-1"><?= htmlspecialchars($r['bezeichnung']) ?></h6>
               <span class="badge bg-light text-dark border"><?= htmlspecialchars($r['kat']) ?></span>
               <span class="badge bg-light text-dark border"><?= htmlspecialchars($r['gr']) ?></span>
             </div>
             <?php if($isFav): ?><i class="bi bi-star-fill text-warning fs-5"></i><?php endif; ?>
          </div>

          <div class="d-flex justify-content-between align-items-end mt-3">
             <div class="small text-muted">
                <div><i class="bi bi-qr-code"></i> <?= htmlspecialchars($r['barcode']) ?></div>
                <div class="<?= $days<30?'text-danger fw-bold':'' ?>">
                   <i class="bi bi-calendar-event"></i> <?= $next>0 ? date('d.m.y', $next) : '—' ?>
                </div>
             </div>
             <div>
                <button class="btn btn-sm btn-outline-secondary rounded-circle" data-bs-toggle="dropdown">
                  <i class="bi bi-three-dots-vertical"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end shadow">
                   <li><a class="dropdown-item" href="geraet_edit.php?barcode=<?= $r['barcode'] ?>">Bearbeiten</a></li>
                   <li>
                     <form method="post" action="favorit_toggle.php">
                       <input type="hidden" name="geraet_id" value="<?= $r['id'] ?>">
                       <button class="dropdown-item" name="toggle_fav"><?= $isFav?'Favorit entfernen':'Favorit setzen' ?></button>
                     </form>
                   </li>
                </ul>
             </div>
          </div>
        </div>
      </div>

      <?php endforeach; endif; ?>
    </div>
  <?php else: ?>
    <div class="text-center mt-5">
      <i class="bi bi-truck fs-1 text-muted"></i>
      <p class="text-muted mt-2">Bitte wähle oben ein Fahrzeug aus.</p>
    </div>
  <?php endif; ?>

</div>

<button class="fab" data-bs-toggle="modal" data-bs-target="#geraeteModal">
  <i class="bi bi-plus-lg"></i>
</button>

<?php /* Füge hier den Modal-Code aus deinem ursprünglichen Skript ein (ID="geraeteModal") */ ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Live Suche
  document.getElementById('mobSearch')?.addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();
    let cards = document.querySelectorAll('.device-card');
    cards.forEach(card => {
       let text = card.getAttribute('data-search');
       card.style.display = text.includes(filter) ? '' : 'none';
    });
  });

  // Service Worker registrieren (PWA)
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js');
  }
</script>
</body>
</html>
