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

if (!isset($_GET['id'])) {
    $_SESSION['error_message'] = "Keine Meeting-ID angegeben.";
    header("Location: index.php");
    exit;
}

$meeting_id = intval($_GET['id']);
$source_page = isset($_GET['source']) && $_GET['source'] === 'history' ? 'history' : 'index';
$cancel_link = $source_page === 'history' ? 'history.php' : 'index.php';

$stmt = mysqli_prepare($conn, "SELECT meeting_date, color_id, reason FROM meetings WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $meeting_id);
mysqli_stmt_execute($stmt);
$meeting = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
mysqli_stmt_close($stmt);

if (!$meeting) {
    $_SESSION['error_message'] = "Meeting nicht gefunden.";
    header("Location: " . $cancel_link);
    exit;
}

$colors = [];
$colors_result = mysqli_query($conn, "SELECT id, name FROM colors ORDER BY name");
while ($row = mysqli_fetch_assoc($colors_result)) {
    $colors[] = $row;
}

$users = [];
$users_result = mysqli_query($conn, "SELECT id, username AS name FROM users ORDER BY username");
while ($row = mysqli_fetch_assoc($users_result)) {
    $users[] = $row;
}

$existing_feedback = [];
$stmt = mysqli_prepare($conn, "SELECT user_id, attended, wore_color, paid, birthday_pay FROM meeting_teilnehmer WHERE meeting_id = ?");
mysqli_stmt_bind_param($stmt, "i", $meeting_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
    $existing_feedback[$row['user_id']] = $row;
}
mysqli_stmt_close($stmt);

$message = '';
$message_type = '';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if ($source_page === 'history') {
        $meeting_date = $_POST['meeting_date'] ?? '';
        $color_id = intval($_POST['color_id'] ?? 0);
        $reason = $_POST['reason'] ?? null;

        if (!empty($meeting_date) && $color_id > 0) {
            $stmt = mysqli_prepare($conn, "UPDATE meetings SET meeting_date = ?, color_id = ?, reason = ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "sisi", $meeting_date, $color_id, $reason, $meeting_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
        }
    }

    // Alte Teilnehmerdaten löschen
    $stmt = mysqli_prepare($conn, "DELETE FROM meeting_teilnehmer WHERE meeting_id = ?");
    mysqli_stmt_bind_param($stmt, "i", $meeting_id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    // Neue Daten speichern
    if (isset($_POST['user_id']) && is_array($_POST['user_id'])) {
        $stmt_insert = mysqli_prepare($conn, "
            INSERT INTO meeting_teilnehmer 
            (meeting_id, user_id, attended, wore_color, paid, birthday_pay) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");

        $meeting_year = (int)date('Y', strtotime($meeting['meeting_date']));
        $meeting_month = (int)date('n', strtotime($meeting['meeting_date']));
        $meeting_day = (int)date('j', strtotime($meeting['meeting_date']));

        foreach ($_POST['user_id'] as $user_id) {
            $user_id = intval($user_id);
            $attended = isset($_POST['attended'][$user_id]) ? 1 : 0;
            $wore_color = isset($_POST['wore_color'][$user_id]) ? 1 : 0;
            $paid = isset($_POST['paid'][$user_id]) ? 1 : 0;
            $birthday_pay = 0;

            if ($paid) {
                // Hole Geburtstag des Users
                $user_stmt = mysqli_prepare($conn, "SELECT birthday FROM users WHERE id = ?");
                mysqli_stmt_bind_param($user_stmt, "i", $user_id);
                mysqli_stmt_execute($user_stmt);
                $user_row = mysqli_fetch_assoc(mysqli_stmt_get_result($user_stmt));
                mysqli_stmt_close($user_stmt);

                if ($user_row && $user_row['birthday'] && $user_row['birthday'] !== '0000-00-00') {
                    $bday_month = (int)date('n', strtotime($user_row['birthday']));
                    $bday_day   = (int)date('j', strtotime($user_row['birthday']));

                    // War Geburtstag in diesem Jahr bereits?
                    $birthday_passed = ($bday_month < $meeting_month ||
                        ($bday_month == $meeting_month && $bday_day <= $meeting_day));

                    if ($birthday_passed) {
                        // Prüfen: Hat er in DIESEM JAHR schon als Geburtstagszahler gezahlt?
                        $check_stmt = mysqli_prepare($conn, "
                            SELECT 1 FROM meeting_teilnehmer mt
                            JOIN meetings m ON mt.meeting_id = m.id
                            WHERE mt.user_id = ? 
                              AND mt.birthday_pay = 1 
                              AND YEAR(m.meeting_date) = ?
                            LIMIT 1
                        ");
                        mysqli_stmt_bind_param($check_stmt, "ii", $user_id, $meeting_year);
                        mysqli_stmt_execute($check_stmt);
                        $already_birthday_paid = mysqli_num_rows(mysqli_stmt_get_result($check_stmt)) > 0;
                        mysqli_stmt_close($check_stmt);

                        if (!$already_birthday_paid) {
                            $birthday_pay = 1;
                        }
                    }
                }
            }

            mysqli_stmt_bind_param(
                $stmt_insert,
                "iiiiii",
                $meeting_id,
                $user_id,
                $attended,
                $wore_color,
                $paid,
                $birthday_pay
            );
            mysqli_stmt_execute($stmt_insert);
        }
        mysqli_stmt_close($stmt_insert);

        // Meeting abschließen (nur im Index-Modus)
        if ($source_page === 'index') {
            $stmt_complete = mysqli_prepare($conn, "UPDATE meetings SET is_completed = 1 WHERE id = ?");
            mysqli_stmt_bind_param($stmt_complete, "i", $meeting_id);
            mysqli_stmt_execute($stmt_complete);
            mysqli_stmt_close($stmt_complete);
        }

        $message = "Teilnehmerdaten erfolgreich gespeichert!";
        $message_type = 'success';
    } else {
        $message = "Keine Benutzerdaten übermittelt.";
        $message_type = 'warning';
    }

    header("Location: " . $cancel_link);
    exit;
}

require_once 'inc/header.php';
?>

<div class="container mt-5">
    <h2 class="mb-4">Teilnahme eintragen</h2>

    <?php if ($source_page === 'index'): ?>
        <p class="text-muted">
            für das Treffen am <strong><?= date('d.m.Y H:i', strtotime($meeting['meeting_date'])) ?></strong>
            in der Farbe <strong>
                <?php
                $color_name = '—';
                foreach ($colors as $c) {
                    if ($c['id'] == $meeting['color_id']) {
                        $color_name = htmlspecialchars($c['name']);
                        break;
                    }
                }
                echo $color_name;
                ?>
            </strong>.
        </p>
    <?php endif; ?>

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

    <div class="card shadow mb-4">
        <div class="card-body">
            <form action="participant.php?id=<?= $meeting_id ?>&source=<?= htmlspecialchars($source_page) ?>" method="post">
                <?php if ($source_page === 'history'): ?>
                    <h5 class="mb-3">Treffen-Details bearbeiten</h5>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="meeting_date" class="form-label">Datum des Treffens</label>
                            <input type="datetime-local" class="form-control" id="meeting_date" name="meeting_date"
                                value="<?= date('Y-m-d\TH:i', strtotime($meeting['meeting_date'])) ?>" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="color_id" class="form-label">Farbvorgabe</label>
                            <select class="form-select" id="color_id" name="color_id" required>
                                <?php foreach ($colors as $color): ?>
                                    <option value="<?= $color['id'] ?>" <?= $meeting['color_id'] == $color['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($color['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="reason" class="form-label">Grund (optional)</label>
                            <input type="text" class="form-control" id="reason" name="reason"
                                value="<?= htmlspecialchars($meeting['reason']) ?>">
                        </div>
                    </div>
                    <hr>
                    <h5 class="mb-3">Teilnehmer-Details bearbeiten</h5>
                <?php endif; ?>

                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Benutzer</th>
                            <th class="text-center">Dabei?</th>
                            <th class="text-center">Farbe getragen?</th>
                            <th class="text-center">Gezahlt?</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <tr>
                                <td><?= htmlspecialchars($user['name']) ?></td>
                                <td class="text-center">
                                    <div class="form-check d-inline-block">
                                        <input class="form-check-input" type="checkbox" name="attended[<?= $user['id'] ?>]"
                                            id="attended_<?= $user['id'] ?>" value="1"
                                            <?= isset($existing_feedback[$user['id']]) && $existing_feedback[$user['id']]['attended'] ? 'checked' : '' ?>>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <div class="form-check d-inline-block">
                                        <input class="form-check-input" type="checkbox" name="wore_color[<?= $user['id'] ?>]"
                                            id="wore_color_<?= $user['id'] ?>" value="1"
                                            <?= isset($existing_feedback[$user['id']]) && $existing_feedback[$user['id']]['wore_color'] ? 'checked' : '' ?>>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <div class="form-check d-inline-block">
                                        <input class="form-check-input" type="checkbox" name="paid[<?= $user['id'] ?>]"
                                            id="paid_<?= $user['id'] ?>" value="1"
                                            <?= isset($existing_feedback[$user['id']]) && $existing_feedback[$user['id']]['paid'] ? 'checked' : '' ?>>
                                    </div>
                                </td>
                            </tr>
                            <input type="hidden" name="user_id[]" value="<?= $user['id'] ?>">
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="d-flex justify-content-between mt-3">
                    <button type="submit" class="btn btn-outline-primary">Speichern</button>
                    <a href="<?= htmlspecialchars($cancel_link) ?>" class="btn btn-outline-secondary">Abbrechen</a>
                </div>
            </form>
        </div>
    </div>
</div>

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