<?php
session_start();
include 'includes/header.php';
include 'includes/nav.php';
include 'includes/db.php';

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

$user_id = (int)$_SESSION['user_id'];
$einheit = $_SESSION['einheit'] ?? '';

// Favoriten laden (nur eigene Einheit)
$sql = "
  SELECT g.*
  FROM ffw_geraete g
  JOIN ffw_favoriten f ON g.id = f.geraet_id
  WHERE f.user_id = ? AND g.einheit = ?
  ORDER BY g.bezeichnung ASC
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $user_id, $einheit);
$stmt->execute();
$result = $stmt->get_result();

// Helper
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function date_or_dash($ts){
  if ($ts === null || $ts === '' ) return '–';
  // lpruefung ist bei dir i.d.R. ein UNIX-TS
  if (is_numeric($ts)) return date("d.m.Y", (int)$ts);
  // falls doch als DATETIME-String gespeichert (failsafe)
  $t = strtotime($ts);
  return $t ? date("d.m.Y", $t) : '–';
}
?>
<style>
  .fav-toolbar { gap:.5rem; }
  .fav-kpi { border-radius:14px; }
  .status-chip {
    display:inline-flex; align-items:center; gap:.4rem; padding:.2rem .6rem;
    border-radius:999px; font-size:.85rem; font-weight:600;
  }
  .chip-ok { background:#e8f5e9; color:#1b5e20; }
  .chip-warn { background:#fff8e1; color:#8a6d00; }
  .chip-danger { background:#ffebee; color:#b71c1c; }
  .chip-gray { background:#eceff1; color:#37474f; }

  .cell-tight { white-space:nowrap; }
  .table-fav thead th { position:sticky; top:0; background:#f8f9fa; z-index:2; }
  .legend-dot { width:10px;height:10px;border-radius:50%;display:inline-block;margin-right:.35rem; }
  .dot-ok { background:#2e7d32; }
  .dot-warn { background:#f9a825; }
  .dot-danger { background:#c62828; }

  @media (max-width: 768px){
    .table-responsive { border-radius:12px; overflow:hidden; }
    .hide-sm { display:none; }
  }
</style>

<div class="container mt-5">
  <div class="d-flex flex-wrap align-items-center justify-content-between mb-3">
    <h1 class="mb-2 mb-md-0">📌 Meine Favoriten</h1>

    <div class="fav-toolbar d-flex align-items-center">
      <div class="input-group">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input id="favSearch" type="text" class="form-control" placeholder="In Favoriten suchen … (Bezeichnung, Barcode, Kategorie)">
      </div>
      <button class="btn btn-outline-secondary" id="btnReset">
        <i class="bi bi-x-circle"></i> Reset
      </button>
    </div>
  </div>

  <div class="row g-3 mb-3">
    <div class="col-12 col-md-4">
      <div class="card fav-kpi shadow-sm h-100">
        <div class="card-body d-flex align-items-center justify-content-between">
          <div>
            <div class="small text-muted">Gesamt</div>
            <div class="h3 mb-0">
              <?= (int)$result->num_rows ?>
            </div>
          </div>
          <div class="text-primary fs-3"><i class="bi bi-star-fill"></i></div>
        </div>
      </div>
    </div>
    <?php
      // kleine Verteilung: ok / bald / kritisch
      $res_all = $result->fetch_all(MYSQLI_ASSOC);
      $cnt_ok = $cnt_warn = $cnt_danger = 0;
      foreach($res_all as $row){
        $l = $row['lpruefung'] ?? null;
        if ($l === null || $l === '') continue;
        $next = is_numeric($l) ? strtotime('+1 year', (int)$l) : strtotime('+1 year', strtotime($l));
        $days = floor(($next - time())/86400);
        if ($days < 7) $cnt_danger++; elseif ($days < 30) $cnt_warn++; else $cnt_ok++;
      }
    ?>
    <div class="col-6 col-md-4">
      <div class="card fav-kpi shadow-sm h-100">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between mb-1">
            <div class="small text-muted">Fälligkeiten</div>
            <i class="bi bi-calendar-event text-secondary"></i>
          </div>
          <div class="d-flex flex-column gap-1">
            <div><span class="legend-dot dot-danger"></span><strong><?= $cnt_danger ?></strong> kritisch (&lt; 7 Tage)</div>
            <div><span class="legend-dot dot-warn"></span><strong><?= $cnt_warn ?></strong> bald (&lt; 30 Tage)</div>
            <div><span class="legend-dot dot-ok"></span><strong><?= $cnt_ok ?></strong> i.O. (≥ 30 Tage)</div>
          </div>
        </div>
      </div>
    </div>
    <?php
      // für Tabelle müssen wir wieder einen Iterator haben:
      // baue ein neues Array $rows auf (wir haben $res_all bereits)
      $rows = $res_all;
    ?>
    <div class="col-6 col-md-4">
      <div class="card fav-kpi shadow-sm h-100">
        <div class="card-body d-flex align-items-center justify-content-between">
          <div>
            <div class="small text-muted">Einheit</div>
            <div class="h6 mb-0"><?= h($einheit ?: '–') ?></div>
          </div>
          <div class="text-secondary fs-3"><i class="bi bi-people"></i></div>
        </div>
      </div>
    </div>
  </div>

  <?php if (empty($rows)): ?>
    <div class="alert alert-info">Keine Favoriten gefunden.</div>
  <?php else: ?>
    <div class="table-responsive shadow-sm rounded">
      <table class="table table-hover align-middle mb-0 table-fav" id="favTable">
        <thead class="table-light">
          <tr>
            <th>Bezeichnung</th>
            <th class="hide-sm">Barcode</th>
            <th>Kategorie</th>
            <th class="hide-sm">Geräteraum</th>
            <th class="hide-sm">Status</th>
            <th>Letzte Prüfung</th>
            <th>Nächste Prüfung</th>
            <th class="text-center">Aktion</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $row): ?>
            <?php
              // Nächste Prüfung + Ampel
              $l = $row['lpruefung'] ?? null;
              $nextTs = null;
              if ($l !== null && $l !== '') {
                $nextTs = is_numeric($l) ? strtotime('+1 year', (int)$l) : strtotime('+1 year', strtotime($l));
              }
              $tage_diff = $nextTs ? floor(($nextTs - time()) / 86400) : null;

              $chipClass = 'chip-gray';
              $chipText  = '–';
              if ($tage_diff !== null) {
                if ($tage_diff < 7) { $chipClass = 'chip-danger'; $chipText = 'kritisch'; }
                elseif ($tage_diff < 30) { $chipClass = 'chip-warn'; $chipText = 'bald'; }
                else { $chipClass = 'chip-ok'; $chipText = 'i.O.'; }
              }

              // Status-Badge
              $status = strtolower($row['status'] ?? '');
              $statusBadge = '<span class="badge text-bg-secondary">–</span>';
              if ($status === 'einsatzbereit' || $status === 'ok' || $status === 'bereit') {
                $statusBadge = '<span class="badge text-bg-success">einsatzbereit</span>';
              } elseif ($status === 'wartung' || $status === 'in wartung') {
                $statusBadge = '<span class="badge text-bg-warning text-dark">Wartung</span>';
              } elseif ($status === 'defekt') {
                $statusBadge = '<span class="badge text-bg-danger">Defekt</span>';
              } elseif ($status === 'ausgesondert') {
                $statusBadge = '<span class="badge text-bg-dark">Ausgesondert</span>';
              }
            ?>
            <tr>
              <td class="fw-semibold">
                <?= h($row['bezeichnung']) ?>
                <?php if (!empty($row['fahrzeug'])): ?>
                  <div class="small text-muted"><?= h($row['fahrzeug']) ?></div>
                <?php endif; ?>
              </td>
              <td class="hide-sm"><?= h($row['barcode']) ?></td>
              <td><?= h($row['kat'] ?? '-') ?></td>
              <td class="hide-sm"><?= h($row['gr'] ?? '-') ?></td>
              <td class="hide-sm"><?= $statusBadge ?></td>
              <td class="cell-tight"><?= date_or_dash($row['lpruefung']) ?></td>
              <td class="cell-tight">
                <span class="status-chip <?= $chipClass ?>">
                  <i class="bi bi-circle-fill" style="font-size:.55rem;"></i>
                  <?= $nextTs ? date("d.m.Y", $nextTs) : '–' ?>
                  <?php if ($tage_diff !== null): ?>
                    <span class="text-muted ms-1">(<?= $tage_diff ?> T.)</span>
                  <?php endif; ?>
                </span>
              </td>
              <td class="text-center">
                <div class="d-flex justify-content-center gap-1">
                  <form method="post" action="geraet_edit.php" class="m-0">
                    <input type="hidden" name="barcode" value="<?= h($row['barcode']) ?>">
                    <button type="submit" class="btn btn-sm btn-outline-primary">
                      <i class="bi bi-pencil"></i> Bearbeiten
                    </button>
                  </form>
                  <form method="post" action="favorit_toggle.php" class="m-0 d-inline">
                    <input type="hidden" name="geraet_id" value="<?= (int)$row['id'] ?>">
                    <button class="btn btn-sm btn-warning" name="toggle_fav" title="Favorit entfernen">
                      ★ Entfernen
                    </button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>

<script>
  (function(){
    const q = document.getElementById('favSearch');
    const reset = document.getElementById('btnReset');
    const table = document.getElementById('favTable');
    if(!q || !table) return;

    const rows = Array.from(table.querySelectorAll('tbody tr'));

    function filter(){
      const term = q.value.trim().toLowerCase();
      rows.forEach(tr => {
        const txt = tr.innerText.toLowerCase();
        tr.style.display = txt.includes(term) ? '' : 'none';
      });
    }
    q.addEventListener('input', filter);

    reset.addEventListener('click', () => {
      q.value = '';
      filter();
      q.focus();
    });
  })();
</script>

<?php include 'includes/footer.php'; ?>
