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

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

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

$events = [];
$datum_counter = [];
$fahrzeug_events = [];

// Geräteprüfungen abrufen
$geraete_stmt = $conn->prepare("SELECT bezeichnung, lpruefung FROM ffw_geraete WHERE einheit = ?");
$geraete_stmt->bind_param("s", $einheit);
$geraete_stmt->execute();
$geraete_result = $geraete_stmt->get_result();

while ($row = $geraete_result->fetch_assoc()) {
    if (!empty($row['lpruefung']) && is_numeric($row['lpruefung'])) {
        $datum = date('Y-m-d', $row['lpruefung'] + 31536000); // +1 Jahr
        $datum_counter[$datum]['geraete'][] = $row['bezeichnung'];
    }
}

// Fahrzeugprüfungen abrufen
$fzg_stmt = $conn->prepare("SELECT fahrzeugbezeichnung, lpruefung FROM ffw_fahrzeuge WHERE einheit = ?");
$fzg_stmt->bind_param("s", $einheit);
$fzg_stmt->execute();
$fzg_result = $fzg_stmt->get_result();

while ($row = $fzg_result->fetch_assoc()) {
    if (!empty($row['lpruefung']) && is_numeric($row['lpruefung'])) {
        $datum = date('Y-m-d', $row['lpruefung'] + 31536000); // +1 Jahr
        $datum_counter[$datum]['fahrzeuge'][] = $row['fahrzeugbezeichnung'];
    }
}

// Aufgaben abrufen
$task_stmt = $conn->prepare("SELECT id, titel, faellig_am FROM aufgaben WHERE einheit = ? AND (empfaenger_id IS NULL OR empfaenger_id = ?)");
$task_stmt->bind_param("si", $einheit, $user_id);
$task_stmt->execute();
$task_result = $task_stmt->get_result();

while ($row = $task_result->fetch_assoc()) {
    if (!empty($row['faellig_am']) && $row['faellig_am'] !== '0000-00-00') {
        $events[] = [
            'title' => '📝 Aufgabe: ' . $row['titel'],
            'start' => $row['faellig_am'],
            'color' => '#0d6efd',
            'url' => 'aufgaben.php'
        ];
    }
}

// Prüfungseinträge generieren
foreach ($datum_counter as $datum => $typen) {
    $anzahl = count($typen['geraete'] ?? []) + count($typen['fahrzeuge'] ?? []);
    $titel = '🔧 Prüfung';

    if (!empty($typen['fahrzeuge'])) {
        foreach ($typen['fahrzeuge'] as $fzgname) {
            $fahrzeug_events[] = [
                'title' => '🚒 Fahrzeug: ' . $fzgname,
                'start' => $datum,
                'color' => '#dc3545'
            ];
        }
    }

    if ($anzahl > 0) {
        if ($anzahl > 10) {
            $titel .= " ($anzahl)";
        } else {
            $einträge = array_merge($typen['geraete'] ?? [], $typen['fahrzeuge'] ?? []);
            $titel .= ': ' . htmlspecialchars($einträge[0]);
        }
        $events[] = [
            'title' => $titel,
            'start' => $datum,
            'color' => '#198754'
        ];
    }
}

$events = array_merge($events, $fahrzeug_events);
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Kalenderübersicht</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.9/index.global.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.9/index.global.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h1 class="mb-4">📅 Kalender: Prüfungen & Aufgaben</h1>
    <div id="calendar"></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const calendarEl = document.getElementById('calendar');

    const calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        locale: 'de',
        events: <?= json_encode($events) ?>,
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,listWeek'
        },
        eventClick: function(info) {
            if (info.event.url) {
                window.location.href = info.event.url;
                info.jsEvent.preventDefault();
            }
        },
        height: "auto"
    });

    calendar.render();
});
</script>
</body>
</html>
