<?php
// index.php – Startseite (Modern Dashboard Redesign)
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
$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);

$aufgaben_anzahl = $kpi_aufgaben;
?>

<style>
  body { background-color: #f8f9fa; }

  /* Hero Section */
  .hero-card {
    background: linear-gradient(135deg, #0d6efd 0%, #0a58ca 100%);
    color: white;
    border: none;
    border-radius: 1rem;
    position: relative;
    overflow: hidden;
  }
  .hero-card::after {
    content: "";
    position: absolute;
    top: -50px; right: -50px;
    width: 200px; height: 200px;
    background: rgba(255,255,255,0.1);
    border-radius: 50%;
  }

  /* KPI Kacheln */
  .stat-card {
    border: none;
    border-radius: 0.75rem;
    transition: transform 0.2s;
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.02);
    height: 100%;
  }
  .stat-card:hover { transform: translateY(-3px); box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
  .stat-icon {
    width: 48px; height: 48px;
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.5rem;
  }

  /* Quick Links (App Grid) */
  .app-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
  .app-btn {
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    padding: 1rem;
    background: white; border: 1px solid #dee2e6;
    border-radius: 0.75rem;
    text-decoration: none; color: #495057;
    transition: all 0.2s;
  }
  .app-btn:hover { background: #e9ecef; color: #0d6efd; border-color: #cce8ff; }
  .app-btn i { font-size: 1.75rem; margin-bottom: 0.5rem; color: #0d6efd; }

  /* News Cards - Ecken jetzt eckig (border-radius: 0) */
  .news-card {
    border: none;
    border-radius: 0; /* Keine runden Ecken */
    background: white;
    box-shadow: 0 2px 8px rgba(0,0,0,0.03);
    overflow: hidden;
    margin-bottom: 1.5rem;
  }
  .news-img-col { min-height: 200px; background-size: cover; background-position: center; }
  .badge-info { background-color: #dc3545; color: white; }
</style>

<div class="container my-4">

  <div class="card hero-card shadow mb-4">
    <div class="card-body p-4">
      <div class="row align-items-center">
        <div class="col-lg-7 mb-3 mb-lg-0">
          <h2 class="fw-bold mb-1">Moin, <?= h($vorname) ?>! 👋</h2>
          <p class="mb-0 opacity-75">
            Willkommen im Dashboard der Einheit <strong><?= h($einheit) ?></strong>.
            <?php if ($aufgaben_anzahl > 0): ?>
               Du hast <strong class="text-warning"><?= $aufgaben_anzahl ?> offene Aufgaben</strong>.
            <?php else: ?>
               Alles sieht ruhig aus.
            <?php endif; ?>
          </p>
        </div>
        <div class="col-lg-5">
          <form method="post" action="geraet_edit.php" class="d-flex shadow-sm rounded-pill bg-white p-1">
            <input type="text" name="barcode" class="form-control border-0 rounded-pill ps-3" placeholder="🔍 Geräte-Barcode scannen..." required style="box-shadow: none;">
            <button type="submit" class="btn btn-primary rounded-pill px-4">Go</button>
          </form>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-3 mb-4">

    <div class="col-6 col-lg-3">
      <a href="aufgaben.php" class="text-decoration-none">
        <div class="card stat-card p-3">
          <div class="d-flex align-items-center">
            <div class="stat-icon bg-danger-subtle text-danger me-3"><i class="bi bi-list-check"></i></div>
            <div>
              <h3 class="mb-0 fw-bold text-dark"><?= $kpi_aufgaben ?></h3>
              <small class="text-muted">Meine Aufgaben</small>
            </div>
          </div>
        </div>
      </a>
    </div>

    <div class="col-6 col-lg-3">
      <a href="tickets.php" class="text-decoration-none">
        <div class="card stat-card p-3">
          <div class="d-flex align-items-center">
            <div class="stat-icon bg-warning-subtle text-warning-emphasis me-3"><i class="bi bi-ticket-perforated"></i></div>
            <div>
              <h3 class="mb-0 fw-bold text-dark"><?= $kpi_tickets ?></h3>
              <small class="text-muted">Offene Tickets</small>
            </div>
          </div>
        </div>
      </a>
    </div>

    <div class="col-6 col-lg-3">
      <a href="geraete_stats.php" class="text-decoration-none">
        <div class="card stat-card p-3">
          <div class="d-flex align-items-center">
            <div class="stat-icon bg-info-subtle text-info-emphasis me-3"><i class="bi bi-stopwatch"></i></div>
            <div>
              <h3 class="mb-0 fw-bold text-dark"><?= $kpi_pruefungen ?></h3>
              <small class="text-muted">Prüfungen (30T)</small>
            </div>
          </div>
        </div>
      </a>
    </div>

    <div class="col-6 col-lg-3">
      <a href="#news" class="text-decoration-none">
        <div class="card stat-card p-3">
          <div class="d-flex align-items-center">
            <div class="stat-icon bg-success-subtle text-success me-3"><i class="bi bi-newspaper"></i></div>
            <div>
              <h3 class="mb-0 fw-bold text-dark"><?= $kpi_news ?></h3>
              <small class="text-muted">Aktuelle News</small>
            </div>
          </div>
        </div>
      </a>
    </div>
  </div>

  <div class="row g-4">

    <div class="col-lg-4 order-lg-last">

      <div class="mb-4">
        <h6 class="text-uppercase text-muted small fw-bold mb-3">Schnellzugriff</h6>
        <div class="app-grid">
          <a href="geraete.php" class="app-btn">
            <i class="bi bi-tools"></i>
            <span class="fw-medium">Geräte</span>
          </a>
          <a href="lager.php" class="app-btn">
            <i class="bi bi-box-seam"></i>
            <span class="fw-medium">Lager</span>
          </a>
          <a href="cart.php" class="app-btn position-relative">
            <span class="position-absolute top-0 end-0 badge rounded-pill bg-danger m-2" style="font-size:0.6rem">Neu</span>
            <i class="bi bi-cart"></i>
            <span class="fw-medium">Bestellung</span>
          </a>
          <a href="dokumente.php" class="app-btn">
            <i class="bi bi-folder2-open"></i>
            <span class="fw-medium">Dokumente</span>
          </a>
        </div>
      </div>

      <div class="card border-0 bg-primary-subtle mb-4">
        <div class="card-body">
          <h6 class="card-title fw-bold text-primary mb-2"><i class="bi bi-info-circle me-1"></i> System Info</h6>
          <p class="small mb-2">Das Modul <strong>Bestellwesen</strong> befindet sich in der Beta-Phase.</p>
          <a href="cart.php" class="btn btn-sm btn-primary w-100">Zum Modul</a>
        </div>
      </div>

    </div>

    <div class="col-lg-8" id="news">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0 fw-bold">Neuigkeiten</h5>
        <a href="#" class="small text-decoration-none">Alle anzeigen</a>
      </div>

      <?php
        if ($newsRes && $newsRes->num_rows > 0):
          while ($n = $newsRes->fetch_assoc()):
            $isInfo = ($n['kategorie'] ?? '') === 'Info';
            $nid = (int)$n['id'];
            $img = !empty($n['bild']) ? 'uploads/news_bilder/' . h($n['bild']) : null;
      ?>

        <div class="news-card">
          <div class="row g-0">
            <?php if($img): ?>
              <div class="col-md-4 news-img-col" style="background-image: url('<?= $img ?>');"></div>
              <div class="col-md-8">
            <?php else: ?>
              <div class="col-12">
            <?php endif; ?>

              <div class="card-body d-flex flex-column h-100">
                <div class="d-flex justify-content-between align-items-start mb-2">
                   <div>
                     <h5 class="card-title fw-bold mb-1"><?= h($n['titel']) ?></h5>
                     <div class="text-muted small">
                       <?= date("d.m.Y", strtotime($n['erstellt_am'])) ?> • <?= h($n['verfasser']) ?>
                     </div>
                   </div>
                   <?php if($isInfo): ?>
                     <span class="badge badge-info">Wichtig</span>
                   <?php endif; ?>
                </div>

                <div class="card-text text-secondary mb-3">
                  <?= nl2br(h($n['inhalt'])) ?>
                </div>

                <div class="mt-auto d-flex gap-2">
                  <?php if (!empty($n['dokument'])): ?>
                    <a href="uploads/news_dokumente/<?= h($n['dokument']) ?>" target="_blank" class="btn btn-sm btn-outline-primary"><i class="bi bi-file-earmark-pdf"></i> PDF</a>
                  <?php endif; ?>
                </div>

              </div>
            </div>
          </div>
        </div>

      <?php endwhile; else: ?>
        <div class="text-center py-5 text-muted bg-white shadow-sm border" style="border-radius:0;">
          <i class="bi bi-newspaper display-4 mb-3 d-block opacity-25"></i>
          <p>Aktuell keine Neuigkeiten.</p>
        </div>
      <?php endif; ?>

    </div>
  </div>

</div>

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