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

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

// Alle Geräte abrufen
$geraete = $conn->query("SELECT id, geraetename, seriennummer, naechste_pruefung FROM atemschutzgeraete");

// Zähler vorbereiten
$gesamt = 0;
$bald_faellig = 0;
$ueberfaellig = 0;
$heute = strtotime(date('Y-m-d'));

$geraete_liste = [];

while ($g = $geraete->fetch_assoc()) {
    $gesamt++;
    $naechste = strtotime($g['naechste_pruefung']);
    $tage_diff = floor(($naechste - $heute) / (60 * 60 * 24));

    if ($tage_diff < 0) {
        $ueberfaellig++;
    } elseif ($tage_diff <= 7) {
        $bald_faellig++;
    }

    $geraete_liste[] = [
        'id' => $g['id'],
        'geraetename' => $g['geraetename'],
        'seriennummer' => $g['seriennummer'],
        'naechste_pruefung' => $g['naechste_pruefung'],
        'tage_diff' => $tage_diff
    ];
}

// Für Liste sortieren
usort($geraete_liste, fn($a, $b) => strtotime($a['naechste_pruefung']) <=> strtotime($b['naechste_pruefung']));

// Werte für Diagramm
$ok = $gesamt - ($bald_faellig + $ueberfaellig);
?>

<div class="container my-5">
  <h2 class="mb-4">Atemschutz Dashboard</h2>

  <div class="row g-4 mb-5">
    <div class="col-md-4">
      <div class="card bg-primary text-white text-center p-4 shadow">
        <h4><?= $gesamt ?></h4>
        <p>Gesamt Geräte</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card bg-warning text-dark text-center p-4 shadow">
        <h4><?= $bald_faellig ?></h4>
        <p>Bald fällig (&lt; 7 Tage)</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card bg-danger text-white text-center p-4 shadow">
        <h4><?= $ueberfaellig ?></h4>
        <p>Überfällig</p>
      </div>
    </div>
  </div>

  <div class="card p-4 mb-5 shadow">
    <h5>Gerätestatus Übersicht</h5>
    <canvas id="statusChart" height="40"></canvas>
  </div>

  <div class="d-flex gap-3 mb-5">
    <a href="atemschutz.php" class="btn btn-primary">Zur Geräteverwaltung</a>
    <a href="atemschutz.php#daten" class="btn btn-success">Neue Prüfung durchführen</a>
    <a href="export_atemschutz_excel.php" class="btn btn-outline-primary">🔽 Excel Export</a>
  </div>

  <div class="card p-4 mb-5 shadow">
    <h5>Nächste 5 fällige Prüfungen</h5>
    <div class="table-responsive mt-3">
      <table class="table table-bordered table-hover">
        <thead class="table-light">
          <tr>
            <th>Gerätename</th>
            <th>Seriennummer</th>
            <th>Nächste Prüfung</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach (array_slice($geraete_liste, 0, 5) as $g): ?>
            <?php
              if ($g['tage_diff'] < 0) {
                  $status = '<span class="badge bg-danger">Überfällig</span>';
              } elseif ($g['tage_diff'] <= 7) {
                  $status = '<span class="badge bg-warning text-dark">Bald fällig</span>';
              } else {
                  $status = '<span class="badge bg-success">OK</span>';
              }
            ?>
            <tr>
              <td><?= htmlspecialchars($g['geraetename']) ?></td>
              <td><?= htmlspecialchars($g['seriennummer']) ?></td>
              <td><?= date('d.m.Y', strtotime($g['naechste_pruefung'])) ?></td>
              <td><?= $status ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('statusChart').getContext('2d');
new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['OK', 'Bald prüfen', 'Überfällig'],
        datasets: [{
            data: [<?= $ok ?>, <?= $bald_faellig ?>, <?= $ueberfaellig ?>],
            backgroundColor: ['#198754', '#ffc107', '#dc3545'],
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            legend: {
                position: 'bottom'
            }
        }
    }
});
</script>

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