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

$einheit = $_SESSION['einheit'] ?? '';

// STATISTIK-KACHELN (ohne "Ausgesondert")
$anzahl_geraete = $conn->query("SELECT COUNT(*) FROM ffw_geraete WHERE einheit = '$einheit' AND status != 'Ausgesondert'")->fetch_row()[0];
$anzahl_favoriten = $conn->query("SELECT COUNT(*) FROM ffw_geraete WHERE einheit = '$einheit' AND fav = 'x' AND status != 'Ausgesondert'")->fetch_row()[0];
$anzahl_fahrzeuge = $conn->query("SELECT COUNT(*) FROM ffw_fahrzeuge WHERE einheit = '$einheit'")->fetch_row()[0];
$anzahl_faellig = $conn->query("SELECT COUNT(*) FROM ffw_geraete WHERE einheit = '$einheit' AND lpruefung < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 11 MONTH)) AND status != 'Ausgesondert'")->fetch_row()[0];

// STATUS-CHART
$labels_status = [];
$values_status = [];
$result = $conn->query("SELECT status, COUNT(*) AS anzahl FROM ffw_geraete WHERE einheit = '$einheit' AND status != 'Ausgesondert' GROUP BY status");
while ($row = $result->fetch_assoc()) {
    $labels_status[] = $row['status'];
    $values_status[] = $row['anzahl'];
}

// KATEGORIE-CHART
$labels_kat = [];
$values_kat = [];
$result = $conn->query("SELECT kat, COUNT(*) AS anzahl FROM ffw_geraete WHERE einheit = '$einheit' AND status != 'Ausgesondert' GROUP BY kat");
while ($row = $result->fetch_assoc()) {
    $labels_kat[] = $row['kat'];
    $values_kat[] = $row['anzahl'];
}

// GERÄTERAUM-CHART
$labels_gr = [];
$values_gr = [];
$result = $conn->query("SELECT gr, COUNT(*) AS anzahl FROM ffw_geraete WHERE einheit = '$einheit' AND status != 'Ausgesondert' GROUP BY gr");
while ($row = $result->fetch_assoc()) {
    $labels_gr[] = $row['gr'];
    $values_gr[] = $row['anzahl'];
}

// FAHRZEUG-CHART
$labels_fzg = [];
$values_fzg = [];
$result = $conn->query("
    SELECT f.fahrzeugbezeichnung, COUNT(g.id) AS anzahl
    FROM ffw_fahrzeuge f
    LEFT JOIN ffw_geraete g ON f.barcode_fzg = g.fahrzeug AND g.status != 'Ausgesondert'
    WHERE f.einheit = '$einheit'
    GROUP BY f.fahrzeugbezeichnung
");
while ($row = $result->fetch_assoc()) {
    $labels_fzg[] = $row['fahrzeugbezeichnung'];
    $values_fzg[] = $row['anzahl'];
}

// PRÜFUNGEN PRO MONAT (ZEITVERLAUF)
$labels_monat = [];
$values_monat = [];
$result = $conn->query("
    SELECT DATE_FORMAT(FROM_UNIXTIME(lpruefung), '%b %Y') AS monat, COUNT(*) AS anzahl
    FROM ffw_geraete
    WHERE einheit = '$einheit' AND status != 'Ausgesondert'
    GROUP BY monat ORDER BY monat DESC LIMIT 6
");
foreach (array_reverse($result->fetch_all(MYSQLI_ASSOC)) as $row) {
    $labels_monat[] = $row['monat'];
    $values_monat[] = $row['anzahl'];
}

// NEUESTE GERÄTE
$neueste = $conn->query("
    SELECT bezeichnung, barcode, FROM_UNIXTIME(lpruefung, '%d.%m.%Y') AS lpruefung
    FROM ffw_geraete
    WHERE einheit = '$einheit' AND status != 'Ausgesondert'
    ORDER BY id DESC LIMIT 5
");

// FÄLLIGE PRÜFUNGEN
$faellig = $conn->query("
    SELECT bezeichnung, barcode, FROM_UNIXTIME(lpruefung, '%d.%m.%Y') AS lpruefung
    FROM ffw_geraete
    WHERE einheit = '$einheit' AND status != 'Ausgesondert' AND lpruefung < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 11 MONTH))
    ORDER BY lpruefung ASC LIMIT 5
");
?>

<div class="container mt-5">
    <h1 class="mb-4">📊 Dashboard</h1>

    <!-- Statistikkacheln -->
    <div class="row g-4 mb-4">
        <div class="col-md-3"><div class="bg-primary text-white p-4 rounded shadow-sm text-center"><h4><?= $anzahl_geraete ?></h4><p>Geräte</p></div></div>
        <div class="col-md-3"><div class="bg-success text-white p-4 rounded shadow-sm text-center"><h4><?= $anzahl_favoriten ?></h4><p>Favoriten</p></div></div>
        <div class="col-md-3"><div class="bg-info text-white p-4 rounded shadow-sm text-center"><h4><?= $anzahl_fahrzeuge ?></h4><p>Fahrzeuge</p></div></div>
        <div class="col-md-3"><div class="bg-danger text-white p-4 rounded shadow-sm text-center"><h4><?= $anzahl_faellig ?></h4><p>Bald fällige Prüfungen</p></div></div>
    </div>

    <!-- Diagramm-Fläche -->
    <div class="row">
        <div class="col-md-6 mb-4"><canvas id="statusChart"></canvas></div>
        <div class="col-md-6 mb-4"><canvas id="katChart"></canvas></div>
        <div class="col-md-6 mb-4"><canvas id="grChart"></canvas></div>
        <div class="col-md-6 mb-4"><canvas id="fzgChart"></canvas></div>
        <div class="col-md-12 mb-5"><canvas id="lineChart"></canvas></div>
    </div>

    <!-- Neueste Geräte & Prüfhinweise -->
    <div class="row">
        <div class="col-md-6">
            <h5>🆕 Neueste Geräte</h5>
            <table class="table table-sm">
                <thead><tr><th>Bezeichnung</th><th>Barcode</th><th>Letzte Prüfung</th></tr></thead>
                <tbody>
                    <?php while ($row = $neueste->fetch_assoc()): ?>
                        <tr><td><?= $row['bezeichnung'] ?></td><td><?= $row['barcode'] ?></td><td><?= $row['lpruefung'] ?></td></tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <div class="col-md-6">
            <h5>🔔 Bald fällige Prüfungen</h5>
            <ul class="list-group">
                <?php while ($row = $faellig->fetch_assoc()): ?>
                    <li class="list-group-item d-flex justify-content-between">
                        <span><?= $row['bezeichnung'] ?> (<?= $row['barcode'] ?>)</span>
                        <span class="text-danger fw-bold"><?= $row['lpruefung'] ?></span>
                    </li>
                <?php endwhile; ?>
            </ul>
        </div>
    </div>
</div>
<!-- Direktlinks zu Detailseiten -->
<div class="row mt-4">
    <div class="col-md-6">
        <a href="geraete_faellig.php" class="btn btn-outline-danger w-100">
            🔎 Alle bald fälligen Prüfungen anzeigen
        </a>
    </div>
    <div class="col-md-6">
        <a href="geraete_neu.php" class="btn btn-outline-primary w-100">
            🆕 Alle neuen Geräte anzeigen
        </a>
    </div>
</div>
<!-- Chart.js laden -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
// Daten aus PHP einfügen
const statusLabels = <?= json_encode($labels_status) ?>;
const statusData = <?= json_encode($values_status) ?>;

const katLabels = <?= json_encode($labels_kat) ?>;
const katData = <?= json_encode($values_kat) ?>;

const grLabels = <?= json_encode($labels_gr) ?>;
const grData = <?= json_encode($values_gr) ?>;

const fzgLabels = <?= json_encode($labels_fzg) ?>;
const fzgData = <?= json_encode($values_fzg) ?>;

const lineLabels = <?= json_encode($labels_monat) ?>;
const lineData = <?= json_encode($values_monat) ?>;

// Balkendiagramm: Geräte nach Status
new Chart(document.getElementById('statusChart'), {
    type: 'bar',
    data: {
        labels: statusLabels,
        datasets: [{
            label: 'Anzahl',
            data: statusData,
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: { display: true, text: 'Geräte nach Status (ohne Ausgesondert)' }
        }
    }
});

// Kategorie
new Chart(document.getElementById('katChart'), {
    type: 'bar',
    data: {
        labels: katLabels,
        datasets: [{
            label: 'Anzahl',
            data: katData,
            backgroundColor: 'rgba(75, 192, 192, 0.6)',
            borderColor: 'rgba(75, 192, 192, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: { display: true, text: 'Geräte nach Kategorie' }
        }
    }
});

// Geräteraum
new Chart(document.getElementById('grChart'), {
    type: 'bar',
    data: {
        labels: grLabels,
        datasets: [{
            label: 'Anzahl',
            data: grData,
            backgroundColor: 'rgba(255, 206, 86, 0.6)',
            borderColor: 'rgba(255, 206, 86, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: { display: true, text: 'Geräte nach Geräteraum' }
        }
    }
});

// Geräte pro Fahrzeug
new Chart(document.getElementById('fzgChart'), {
    type: 'bar',
    data: {
        labels: fzgLabels,
        datasets: [{
            label: 'Anzahl',
            data: fzgData,
            backgroundColor: 'rgba(153, 102, 255, 0.6)',
            borderColor: 'rgba(153, 102, 255, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: { display: true, text: 'Geräte pro Fahrzeug' }
        }
    }
});

// Liniendiagramm: Prüfungen pro Monat
new Chart(document.getElementById('lineChart'), {
    type: 'line',
    data: {
        labels: lineLabels,
        datasets: [{
            label: 'Prüfungen',
            data: lineData,
            borderColor: 'rgba(255, 99, 132, 1)',
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            fill: true,
            tension: 0.3
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: { display: true, text: '📈 Prüfungen pro Monat' }
        }
    }
});
</script>

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