<?php
// index.php – Startseite (komplett überarbeitet, modular & clean)
ob_start();
session_start();

require_once __DIR__ . "/includes/db.php";
require_once __DIR__ . "/includes/header.php";
require_once __DIR__ . "/includes/nav.php";

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

// Helper
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// User-/Session-Daten
$vorname   = $_SESSION['user_vorname'] ?? $_SESSION['vorname'] ?? $_SESSION['username'] ?? 'Kamerad';
$einheit   = $_SESSION['einheit'] ?? '';
$user_id   = (int)($_SESSION['user_id'] ?? 0);

// ---------- KPI-Daten ziehen ----------
$kpi_aufgaben = 0;
if ($user_id) {
  $st = $conn->prepare("SELECT COUNT(*) AS c FROM aufgaben WHERE empfaenger_id = ? AND status != 'erledigt'");
  $st->bind_param("i", $user_id);
  $st->execute();
  $kpi_aufgaben = (int)($st->get_result()->fetch_assoc()['c'] ?? 0);
  $st->close();
}

$kpi_tickets = 0;
if ($einheit !== '') {
  $st = $conn->prepare("SELECT COUNT(*) AS c FROM neue_tickets WHERE einheit = ? AND status != 'erledigt'");
  $st->bind_param("s", $einheit);
  $st->execute();
  $kpi_tickets = (int)($st->get_result()->fetch_assoc()['c'] ?? 0);
  $st->close();
}

$kpi_pruefungen = 0;
if ($einheit !== '') {
  // lpruefung als UNIX-Timestamp (int) – fällig in den nächsten 30 Tagen
  $in30 = strtotime('+30 days');
  $st = $conn->prepare("
    SELECT COUNT(*) AS c
    FROM ffw_geraete
    WHERE einheit = ?
      AND status != 'Ausgesondert'
      AND lpruefung IS NOT NULL
      AND lpruefung <= ?
  ");
  $st->bind_param("si", $einheit, $in30);
  $st->execute();
  $kpi_pruefungen = (int)($st->get_result()->fetch_assoc()['c'] ?? 0);
  $st->close();
}

// ---------- News laden (Info-Kategorie priorisieren) ----------
$sqlNews = "SELECT * FROM news ORDER BY (kategorie = 'Info') DESC, highlight DESC, erstellt_am DESC";
$newsRes = $conn->query($sqlNews);
$kpi_news = (int)($newsRes->num_rows ?? 0);

// Zusätzlich: Badge-Hinweis für offene Aufgaben (weiter unten auch im KPI)
$aufgaben_anzahl = $kpi_aufgaben;

// ---------- Styles (dezent, keine Brüche zum vorhandenen Design) ----------
?>
<style>
  .card-img-top{max-height:180px;object-fit:cover;width:100%}
  .card:hover{transform:translateY(-2px);box-shadow:0 6px 20px rgba(0,0,0,.1);transition:all .2s ease-in-out}
  .card-info{background-color:#fff0f0;border-left:4px solid #dc3545}
  .kpi-card{border-radius:14px}
  .kpi-sub{font-size:.85rem;color:#6c757d}
  .kpi-val{font-weight:700}
  .quick-link .card-body{min-height:72px}
</style>

<div class="container my-5">

  <!-- Gruß + Kontext -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">Moin <?= h($vorname) ?> 👋</h2>
      <div class="text-muted">
        Einheit: <span class="badge text-bg-secondary"><?= h($einheit ?: '–') ?></span>
      </div>
    </div>
    <div>
      <a href="/helpcenter" class="btn btn-outline-secondary btn-sm d-flex align-items-center">
        <i class="bi bi-question-circle me-1"></i> Helpcenter
      </a>
    </div>
  </div>

  <!-- KPI-Deck -->
  <div class="row g-3">
    <div class="col-6 col-md-3">
      <div class="card kpi-card shadow-sm">
        <div class="card-body">
          <div class="kpi-sub">Offene Aufgaben</div>
          <div class="kpi-val fs-3"><?= $kpi_aufgaben ?></div>
        </div>
        <div class="card-footer bg-transparent"><a href="aufgaben.php" class="small text-decoration-none">Öffnen →</a></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="card kpi-card shadow-sm">
        <div class="card-body">
          <div class="kpi-sub">Offene Tickets</div>
          <div class="kpi-val fs-3"><?= $kpi_tickets ?></div>
        </div>
        <div class="card-footer bg-transparent"><a href="tickets.php" class="small text-decoration-none">Öffnen →</a></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="card kpi-card shadow-sm">
        <div class="card-body">
          <div class="kpi-sub">Bald fällige Prüfungen (30T)</div>
          <div class="kpi-val fs-3"><?= $kpi_pruefungen ?></div>
        </div>
        <div class="card-footer bg-transparent"><a href="geraete_stats.php" class="small text-decoration-none">Details →</a></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="card kpi-card shadow-sm">
        <div class="card-body">
          <div class="kpi-sub">News gesamt</div>
          <div class="kpi-val fs-3"><?= $kpi_news ?></div>
        </div>
        <div class="card-footer bg-transparent"><a href="#news" class="small text-decoration-none">Nach unten →</a></div>
      </div>
    </div>
  </div>

  <!-- Schnellzugriff -->
  <div class="row g-3 mt-3">
    <div class="col-6 col-md-3">
      <a href="geraete.php" class="text-decoration-none quick-link">
        <div class="card shadow-sm h-100">
          <div class="card-body d-flex align-items-center gap-2">
            <i class="bi bi-tools fs-3"></i>
            <div><div class="fw-semibold">Geräte</div><small class="text-muted">Suchen & bearbeiten</small></div>
          </div>
        </div>
      </a>
    </div>
    <div class="col-6 col-md-3">
      <a href="lager.php" class="text-decoration-none quick-link">
        <div class="card shadow-sm h-100">
          <div class="card-body d-flex align-items-center gap-2">
            <i class="bi bi-box-seam fs-3"></i>
            <div><div class="fw-semibold">Lager</div><small class="text-muted">Bestände & Buchungen</small></div>
          </div>
        </div>
      </a>
    </div>
    <div class="col-6 col-md-3">
      <a href="cart.php" class="text-decoration-none quick-link">
        <div class="card shadow-sm h-100">
          <div class="card-body d-flex align-items-center gap-2">
            <i class="bi bi-bag-check fs-3"></i>
            <div><div class="fw-semibold">Bestellwesen</div><small class="text-muted">Warenkorb & Orders</small></div>
          </div>
        </div>
      </a>
    </div>
    <div class="col-6 col-md-3">
      <a href="dokumente.php" class="text-decoration-none quick-link">
        <div class="card shadow-sm h-100">
          <div class="card-body d-flex align-items-center gap-2">
            <i class="bi bi-files fs-3"></i>
            <div><div class="fw-semibold">Dokumente</div><small class="text-muted">Uploads & Kategorien</small></div>
          </div>
        </div>
      </a>
    </div>
  </div>

  <!-- Barcode Quick-Edit (aus deiner alten Startseite übernommen) -->
  <div class="card bg-light shadow-sm mt-4">
    <div class="card-body">
      <h5 class="mb-3">Gerät schnell aufrufen</h5>
      <form method="post" action="geraet_edit.php" class="mt-1">
        <div class="input-group">
          <input type="text" name="barcode" class="form-control" placeholder="Geräte-Barcode eingeben..." required>
          <button type="submit" class="btn btn-primary">Bearbeiten</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Hinweis auf neues Modul -->
  <div class="alert alert-primary d-flex justify-content-between align-items-center rounded-3 shadow-sm p-3 my-4" role="alert">
    <div>
      <h5 class="mb-1">🆕 Neues Modul: Bestellwesen <span class="badge bg-danger">BETA</span></h5>
      <p class="mb-0 small">Stelle Artikel zusammen, sende Bestellungen ab und behalte alles im Blick – direkt im neuen Bestellwesen.</p>
    </div>
    <a href="cart.php" class="btn btn-sm btn-outline-primary position-relative">
      Modul öffnen
      <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">NEU</span>
    </a>
  </div>

  <?php if ($aufgaben_anzahl > 0): ?>
    <div class="alert alert-info">
      🔔 Du hast noch <strong><?= $aufgaben_anzahl ?></strong> offene Aufgabe<?= $aufgaben_anzahl == 1 ? '' : 'n' ?>!
      <a href="aufgaben.php" class="btn btn-sm btn-outline-primary ms-2">Jetzt ansehen</a>
    </div>
  <?php endif; ?>

  <!-- News -->
  <div class="d-flex justify-content-between align-items-center mt-5 mb-2" id="news">
    <h3 class="mb-0">📢 Aktuelle News & Infos</h3>
    <?php if (($newsRes->num_rows ?? 0) > 6): ?>
      <small class="text-muted"><?= (int)$newsRes->num_rows ?> Einträge</small>
    <?php endif; ?>
  </div>

  <div class="row g-4">
    <?php
    // kleine Hilfsfunktion für Snippet
    function news_snippet($text, $len=240){
      $t = trim(strip_tags((string)$text));
      if (mb_strlen($t) <= $len) return [$t,false];
      return [mb_substr($t,0,$len).'…', true];
    }

    if ($newsRes && $newsRes->num_rows > 0):
      while ($n = $newsRes->fetch_assoc()):
        [$short, $hasMore] = news_snippet($n['inhalt'] ?? '');
        $isInfo    = ($n['kategorie'] ?? '') === 'Info';
        $cardClass = $isInfo ? 'card-info' : (($n['highlight'] ?? 0) ? 'bg-warning-subtle border-warning' : 'bg-light');
        $nid       = (int)($n['id'] ?? 0);
    ?>
      <div class="col-md-6">
        <div class="card shadow-sm h-100 border-0 <?= $cardClass ?>">
          <?php if (!empty($n['bild'])): ?>
            <img loading="lazy" src="uploads/news_bilder/<?= h($n['bild']) ?>" class="card-img-top rounded-top" alt="News-Bild">
          <?php endif; ?>

          <div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-1">
              <h5 class="card-title mb-0 fw-bold text-dark"><?= h($n['titel'] ?? 'Ohne Titel') ?></h5>
              <span class="badge <?= $isInfo ? 'text-bg-danger' : 'text-bg-secondary' ?>">
                <?= h($n['kategorie'] ?: 'News') ?>
              </span>
            </div>

            <p class="card-text small text-muted mb-2">
              <?php if ($hasMore): ?>
                <span><?= nl2br(h($short)) ?></span>
                <a class="small" data-bs-toggle="collapse" href="#n<?= $nid ?>">Mehr lesen</a>
                <div id="n<?= $nid ?>" class="collapse mt-2"><?= nl2br(h($n['inhalt'])) ?></div>
              <?php else: ?>
                <?= nl2br(h($short)) ?>
              <?php endif; ?>
            </p>

            <div class="d-flex gap-2">
              <?php if (!empty($n['dokument'])): ?>
                <a href="uploads/news_dokumente/<?= h($n['dokument']) ?>" target="_blank" class="btn btn-outline-primary btn-sm">📄 PDF</a>
              <?php endif; ?>
              <?php if ($isInfo): ?>
                <span class="badge text-bg-light">Wichtig</span>
              <?php endif; ?>
            </div>
          </div>
          <div class="card-footer bg-transparent d-flex justify-content-between small text-muted">
            <span><?= !empty($n['erstellt_am']) ? date("d.m.Y H:i", strtotime($n['erstellt_am'])) : '' ?></span>
            <span><?= h($n['verfasser'] ?? '') ?></span>
          </div>
        </div>
      </div>
    <?php endwhile; else: ?>
      <div class="col-12">
        <div class="alert alert-light border">Keine News vorhanden.</div>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php require_once __DIR__ . "/includes/footer.php"; ?>
<?php ob_end_flush(); ?>
