<?php
include('inc/check_login.php');
include('inc/db.php');
include('inc/helpers.php');

// PHP-Logik für die Löschfunktion
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);

    // 🔥 Zuerst abhängige Tabellen bereinigen – in der richtigen Reihenfolge!
    // 1. Abstimmungen zu Vorschlägen löschen
    $stmt1 = mysqli_prepare($conn, "DELETE FROM meeting_reschedule_votes WHERE proposal_id IN (SELECT id FROM meeting_reschedule_proposals WHERE meeting_id = ?)");
    if ($stmt1) {
        mysqli_stmt_bind_param($stmt1, "i", $id);
        mysqli_stmt_execute($stmt1);
        mysqli_stmt_close($stmt1);
    }

    // 2. Verschiebungsvorschläge löschen
    $stmt2 = mysqli_prepare($conn, "DELETE FROM meeting_reschedule_proposals WHERE meeting_id = ?");
    if ($stmt2) {
        mysqli_stmt_bind_param($stmt2, "i", $id);
        mysqli_stmt_execute($stmt2);
        mysqli_stmt_close($stmt2);
    }

    // 3. Teilnehmerdaten löschen
    $stmt3 = mysqli_prepare($conn, "DELETE FROM meeting_teilnehmer WHERE meeting_id = ?");
    if ($stmt3) {
        mysqli_stmt_bind_param($stmt3, "i", $id);
        mysqli_stmt_execute($stmt3);
        mysqli_stmt_close($stmt3);
    }

    // 4. Jetzt den Termin selbst löschen
    $stmt4 = mysqli_prepare($conn, "DELETE FROM meetings WHERE id = ?");
    mysqli_stmt_bind_param($stmt4, "i", $id);
    if (mysqli_stmt_execute($stmt4)) {
        header("Location: history.php?status=deleted");
        exit;
    } else {
        $error_message = "Fehler beim Löschen des Termins.";
    }
    mysqli_stmt_close($stmt4);
}

// Funktion zum Abrufen aller Meeting-Details
function get_all_meeting_details($conn)
{
    $sql = "
        SELECT 
            m.id AS meeting_id, 
            m.meeting_date, 
            m.reason, 
            c.name AS color_name, 
            c.hex_code,
            u.username,
            mt.attended,
            mt.wore_color,
            mt.paid,
            mt.birthday_pay
        FROM meetings m
        JOIN colors c ON m.color_id = c.id
        LEFT JOIN meeting_teilnehmer mt ON m.id = mt.meeting_id
        LEFT JOIN users u ON mt.user_id = u.id
        WHERE is_completed = 1
        ORDER BY m.meeting_date DESC, u.username ASC
    ";

    $result = mysqli_query($conn, $sql);

    if (!$result) {
        die("Fehler in der SQL-Abfrage: " . mysqli_error($conn));
    }

    $meetings = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $meeting_id = $row['meeting_id'];

        if (!isset($meetings[$meeting_id])) {
            $meetings[$meeting_id] = [
                'date' => $row['meeting_date'],
                'reason' => $row['reason'],
                'color_name' => $row['color_name'],
                'hex_code' => $row['hex_code'],
                'participants' => []
            ];
        }

        if ($row['username']) {
            $meetings[$meeting_id]['participants'][] = [
                'username' => $row['username'],
                'attended' => $row['attended'],
                'wore_color' => $row['wore_color'],
                'paid' => $row['paid'],
                'birthday_pay' => $row['birthday_pay']
            ];
        }
    }

    return $meetings;
}

// PHP-Logik zur Verarbeitung des Formulars
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_meeting'])) {
    $meeting_date = $_POST['meeting_date'];
    $reason = $_POST['reason'];
    $color_id = $_POST['color_id'];

    if (!empty($meeting_date) && !empty($color_id)) {
        $stmt = mysqli_prepare($conn, "INSERT INTO meetings (meeting_date, reason, color_id) VALUES (?, ?, ?)");
        mysqli_stmt_bind_param($stmt, "ssi", $meeting_date, $reason, $color_id);

        if (mysqli_stmt_execute($stmt)) {
            header("Location: history.php?status=success");
            exit;
        } else {
            $error_message = "Fehler beim Hinzufügen des Treffens: " . mysqli_error($conn);
        }
        mysqli_stmt_close($stmt);
    } else {
        $error_message = "Datum und Farbe sind Pflichtfelder.";
    }
}

// Farben für das Formular abrufen
$colors_result = mysqli_query($conn, "SELECT id, name, hex_code FROM colors ORDER BY name");
$colors = mysqli_fetch_all($colors_result, MYSQLI_ASSOC);

// Hier wird die Funktion aufgerufen, nachdem sie definiert wurde
$all_meetings = get_all_meeting_details($conn);

include('inc/header.php');
?>

<div class="container mt-5">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Termin-History</h2>
    </div>

    <?php if (isset($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($error_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (empty($all_meetings)): ?>
        <div class="alert alert-info text-center" role="alert">
            Bisher wurden keine Treffen erfasst.
        </div>
    <?php else: ?>
        <?php foreach ($all_meetings as $meeting_id => $meeting): ?>
            <div class="card shadow mb-4">
                <?php
                // Wochentag abkürzen (Mo., Di., Mi., ...)
                $weekday_short = date('D', strtotime($meeting['date']));
                $german_weekdays = [
                    'Mon' => 'Mo.',
                    'Tue' => 'Di.',
                    'Wed' => 'Mi.',
                    'Thu' => 'Do.',
                    'Fri' => 'Fr.',
                    'Sat' => 'Sa.',
                    'Sun' => 'So.'
                ];
                $weekday = $german_weekdays[$weekday_short] ?? '';
                $formatted_date = date('d.m.y', strtotime($meeting['date']));
                $formatted_time = date('H:i', strtotime($meeting['date']));
                ?>

                <div class="card-header bg-primary-subtle text-secondary d-flex justify-content-between align-items-center">
                    <div class="mb-0 fs-6 fs-md-5 fw-bold">
                        Treffen am <?= $weekday ?> <?= $formatted_date ?> um <?= $formatted_time ?> Uhr
                    </div>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                        <div class="dropdown">
                            <a href="#" class="text-secondary" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <span class="material-icons">more_vert</span>
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li>
                                    <a class="dropdown-item d-flex align-items-center" href="participant.php?id=<?= $meeting_id ?>&source=history">
                                        <span class="material-icons me-2">edit_calendar</span> Bearbeiten
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center text-danger" href="history.php?action=delete&id=<?= $meeting_id ?>" onclick="return confirm('Möchtest du diesen Termin wirklich löschen?');">
                                        <span class="material-icons me-2">delete_outline</span> Löschen
                                    </a>
                                </li>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <div class="d-flex flex-column text-muted fst-italic mb-2">
                        <div class="d-flex align-items-center mb-1">
                            <span>Farbe:</span>
                            <div class="ms-2" style="background-color: <?= htmlspecialchars($meeting['hex_code']); ?>; width: 20px; height: 20px; border: 1px solid #ccc; border-radius: 2px;"></div>
                            <span class="fw-bold ms-2"><?= htmlspecialchars($meeting['color_name']) ?></span>
                        </div>
                        <span>Grund: <?= htmlspecialchars($meeting['reason']) ?></span>
                    </div>
                    <h6 class="mb-2">Teilnehmer:</h6>
                    <?php if (empty($meeting['participants'])): ?>
                        <p class="text-muted">Noch keine Teilnehmer erfasst.</p>
                    <?php else: ?>
                        <ul class="list-unstyled">
                            <?php foreach ($meeting['participants'] as $participant): ?>
                                <li>
                                    <?php
                                    $status_icon = '❌';
                                    $status_text = 'Nicht dabei';
                                    if ($participant['attended']) {
                                        $status_icon = $participant['wore_color'] ? '✅' : '🔴';
                                        $status_text = $participant['wore_color'] ? 'Farbe getragen' : 'Falsche Farbe';
                                    }
                                    $paid_icon = '';
                                    if ($participant['paid']) {
                                        $paid_icon = '💰';
                                        if ($participant['birthday_pay']) {
                                            $paid_icon .= ' 🎂';
                                        }
                                    }
                                    ?>
                                    <?= $status_icon ?>
                                    <span class="fw-bold"><?= htmlspecialchars($participant['username']) ?></span>
                                    <?= $paid_icon ?>
                                    <small class="text-muted ms-2"><?= $status_text ?></small>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php include('inc/footer.php'); ?>