<?php
ob_start();

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

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

// Session-Werte
$user_id = $_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$barcode_car = $_GET['c'] ?? '';
$fehler = $_SESSION['geraet_fehler'] ?? null;
$success = $_SESSION['geraet_success'] ?? null;
$formdata = $_SESSION['geraet_formdata'] ?? [];
unset($_SESSION['geraet_fehler'], $_SESSION['geraet_success'], $_SESSION['geraet_formdata']);

// Daten vorbereiten
$einheiten = $conn->query("SELECT DISTINCT einheit, gemeinde_id FROM users WHERE einheit != ''")->fetch_all(MYSQLI_ASSOC);

$stmtFzg = $conn->prepare("SELECT barcode_fzg, fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE einheit = ? ORDER BY fahrzeugbezeichnung ASC");
$stmtFzg->bind_param("s", $user_einheit);
$stmtFzg->execute();
$fahrzeuge_result = $stmtFzg->get_result();

$fahrzeugname = '';
if (!empty($barcode_car)) {
    $stmtName = $conn->prepare("SELECT fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE barcode_fzg = ? AND einheit = ?");
    $stmtName->bind_param("ss", $barcode_car, $user_einheit);
    $stmtName->execute();
    $resultName = $stmtName->get_result();
    if ($row = $resultName->fetch_assoc()) {
        $fahrzeugname = $row["fahrzeugbezeichnung"];
    }
}

if (!empty($barcode_car)) {
    $stmt = $conn->prepare("SELECT * FROM ffw_geraete WHERE fahrzeug = ? AND einheit = ? ORDER BY gr, bezeichnung");
    $stmt->bind_param("ss", $barcode_car, $user_einheit);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = false;
}

$kategorien = $conn->query("SELECT DISTINCT kat FROM ffw_geraete WHERE kat != '' ORDER BY kat ASC");
$geraeteraeume = $conn->query("SELECT DISTINCT gr FROM ffw_geraete WHERE gr != '' ORDER BY gr ASC");
$statuswerte = $conn->query("SELECT DISTINCT status FROM ffw_geraete WHERE status != '' ORDER BY status ASC");
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Geräteübersicht</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
    <h1 class="mb-4">Geräteübersicht</h1>

    <?php if ($fehler): ?>
        <div class="alert alert-danger"><?= $fehler ?></div>
    <?php endif; ?>
    <?php if ($success): ?>
        <div class="alert alert-success">Gerät erfolgreich hinzugefügt.</div>
    <?php endif; ?>

    <form method="get" class="mb-4">
        <label for="c" class="form-label">Fahrzeug wählen:</label>
        <select name="c" id="c" onchange="this.form.submit()" class="form-select w-auto d-inline-block ms-2">
            <option value="">-- Fahrzeug auswählen --</option>
            <?php while ($fzg = $fahrzeuge_result->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($fzg['barcode_fzg']) ?>" <?= ($fzg['barcode_fzg'] == $barcode_car ? 'selected' : '') ?>>
                    <?= htmlspecialchars($fzg['fahrzeugbezeichnung']) ?>
                </option>
            <?php endwhile; ?>
        </select>
    </form>

    <button class="btn btn-primary mb-4" data-bs-toggle="modal" data-bs-target="#geraeteModal">➕ Gerät hinzufügen</button>

    <?php if ($fahrzeugname): ?>
        <h5 class="mb-3">Fahrzeug: <strong><?= htmlspecialchars($fahrzeugname) ?></strong></h5>
    <?php endif; ?>

    <?php if ($result && $result->num_rows > 0): ?>
        <div class="table-responsive">
            <table class="table table-bordered table-sm align-middle text-center">
                <thead class="table-light">
                    <tr>
                        <th>Bezeichnung</th>
                        <th>Barcode</th>
                        <th>Kategorie</th>
                        <th>Baujahr</th>
                        <th>Geräteraum</th>
                        <th>Status</th>
                        <th>Letzte Prüfung</th>
                        <th>Nächste Prüfung</th>
                        <th>Aktion</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <?php
                        $nächste = strtotime('+1 year', $row['lpruefung']);
                        $tage_diff = floor(($nächste - time()) / 86400);
                        $bg = 'table-success';
                        if ($tage_diff < 7) $bg = 'table-danger';
                        elseif ($tage_diff < 30) $bg = 'table-warning';

                        // Favorit prüfen
                        $is_fav = false;
                        $stmt_fav = $conn->prepare("SELECT 1 FROM ffw_favoriten WHERE user_id = ? AND geraet_id = ?");
                        $stmt_fav->bind_param("ii", $user_id, $row['id']);
                        $stmt_fav->execute();
                        $stmt_fav->store_result();
                        if ($stmt_fav->num_rows > 0) $is_fav = true;
                        $stmt_fav->close();
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['bezeichnung']) ?></td>
                        <td><?= htmlspecialchars($row['barcode']) ?></td>
                        <td><?= htmlspecialchars($row['kat']) ?></td>
                        <td><?= htmlspecialchars($row['baujahr']) ?></td>
                        <td><?= htmlspecialchars($row['gr']) ?></td>
                        <td><?= htmlspecialchars($row['status']) ?></td>
                        <td><?= date("d.m.Y", $row['lpruefung']) ?></td>
                        <td class="<?= $bg ?>"><?= date("d.m.Y", $nächste) ?></td>
                        <td>
                            <form method="post" action="geraet_edit.php" class="d-inline">
                                <input type="hidden" name="barcode" value="<?= htmlspecialchars($row['barcode']) ?>">
                                <button type="submit" class="btn btn-sm btn-outline-primary">Bearbeiten</button>
                            </form>
                            <form method="post" action="favorit_toggle.php" class="d-inline">
                                <input type="hidden" name="geraet_id" value="<?= $row['id'] ?>">
                                <button class="btn btn-sm <?= $is_fav ? 'btn-warning' : 'btn-outline-secondary' ?>" name="toggle_fav">
                                    <?= $is_fav ? '★ Entfernen' : '☆ Merken' ?>
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    <?php elseif ($barcode_car): ?>
        <div class="alert alert-warning">Keine Geräte für dieses Fahrzeug gefunden.</div>
    <?php endif; ?>
</div>

<!-- MODAL -->
<div class="modal fade <?= $fehler ? 'show d-block' : '' ?>" id="geraeteModal" tabindex="-1" aria-labelledby="geraeteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <form method="post" action="geraet_add_handler.php" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Neues Gerät hinzufügen</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">Einheit</label>
                        <select name="einheit" id="einheit" class="form-select" required onchange="setGemeinde(this.value)">
                            <option value="">Bitte wählen</option>
                            <?php foreach ($einheiten as $e): ?>
                                <option value="<?= $e['einheit'] ?>" <?= ($formdata['einheit'] ?? '') === $e['einheit'] ? 'selected' : '' ?>><?= $e['einheit'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Gemeinde-ID</label>
                        <input type="text" name="gemeinde" id="gemeinde" class="form-control" readonly value="<?= htmlspecialchars($formdata['gemeinde'] ?? '') ?>">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Fahrzeug</label>
                    <select name="fahrzeug" class="form-select" required>
                        <option value="">Bitte wählen</option>
                        <?php
                        $stmtFzg->execute();
                        $fahrzeuge_neu = $stmtFzg->get_result();
                        while ($f = $fahrzeuge_neu->fetch_assoc()): ?>
                            <option value="<?= $f['barcode_fzg'] ?>" <?= ($formdata['fahrzeug'] ?? '') === $f['barcode_fzg'] ? 'selected' : '' ?>><?= $f['fahrzeugbezeichnung'] ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">Bezeichnung</label>
                        <input type="text" name="bezeichnung" class="form-control" required value="<?= htmlspecialchars($formdata['bezeichnung'] ?? '') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Barcode</label>
                        <input type="text" name="barcode" id="barcode" class="form-control" required value="<?= htmlspecialchars($formdata['barcode'] ?? '') ?>">
                        <div id="barcode-feedback" class="small mt-1"></div>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-4">
                        <label class="form-label">Kategorie</label>
                        <select name="kat" class="form-select">
                            <option value="">Bitte wählen</option>
                            <?php while ($k = $kategorien->fetch_assoc()): ?>
                                <option value="<?= $k['kat'] ?>" <?= ($formdata['kat'] ?? '') === $k['kat'] ? 'selected' : '' ?>><?= $k['kat'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Geräteraum</label>
                        <select name="gr" class="form-select">
                            <option value="">Bitte wählen</option>
                            <?php while ($g = $geraeteraeume->fetch_assoc()): ?>
                                <option value="<?= $g['gr'] ?>" <?= ($formdata['gr'] ?? '') === $g['gr'] ? 'selected' : '' ?>><?= $g['gr'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">Bitte wählen</option>
                            <?php while ($s = $statuswerte->fetch_assoc()): ?>
                                <option value="<?= $s['status'] ?>" <?= ($formdata['status'] ?? '') === $s['status'] ? 'selected' : '' ?>><?= $s['status'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">Letzte Prüfung</label>
                        <input type="date" name="lpruefung" class="form-control" value="<?= htmlspecialchars($formdata['lpruefung'] ?? '') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Baujahr</label>
                        <input type="number" name="baujahr" class="form-control" min="1900" max="<?= date('Y') ?>" value="<?= htmlspecialchars($formdata['baujahr'] ?? '') ?>">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-success" id="submitBtn">💾 Speichern</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const einheitZuGemeinde = <?= json_encode(array_column($einheiten, 'gemeinde_id', 'einheit')) ?>;
function setGemeinde(einheit) {
    document.getElementById('gemeinde').value = einheitZuGemeinde[einheit] ?? '';
}

document.addEventListener("DOMContentLoaded", function () {
    const barcodeInput = document.getElementById('barcode');
    const einheitSelect = document.getElementById('einheit');
    const feedback = document.getElementById('barcode-feedback');
    const submitBtn = document.getElementById('submitBtn');

    async function checkBarcode() {
        const barcode = barcodeInput.value.trim();
        const einheit = einheitSelect.value;

        if (!barcode || !einheit) {
            feedback.textContent = '';
            feedback.className = 'small mt-1';
            submitBtn.disabled = false;
            return;
        }

        try {
            const res = await fetch(`ajax_check_barcode.php?barcode=${encodeURIComponent(barcode)}&einheit=${encodeURIComponent(einheit)}`);
            const data = await res.json();

            if (data.exists) {
                feedback.textContent = '❌ Dieser Barcode ist in dieser Einheit bereits vergeben.';
                feedback.className = 'text-danger small mt-1';
                submitBtn.disabled = true;
            } else {
                feedback.textContent = '✅ Barcode ist verfügbar.';
                feedback.className = 'text-success small mt-1';
                submitBtn.disabled = false;
            }
        } catch (err) {
            feedback.textContent = '';
            submitBtn.disabled = false;
        }
    }

    barcodeInput.addEventListener('input', checkBarcode);
    einheitSelect.addEventListener('change', checkBarcode);
});
</script>
</body>
</html>
