<?php
session_start();

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("Location: login.php");
    exit;
}

$firstname = $_SESSION["firstname"] ?? "";
$userID = $_SESSION["user_id"] ?? 0;

$dbFile = '/volume1/web/WW_Aktivenzeltlager/Akivenzeltager_Database/database.db';

$meldung = "";

function h($wert) {
    return htmlspecialchars((string)$wert, ENT_QUOTES, "UTF-8");
}

function zahlBegrenzen($wert, $min, $max) {
    $zahl = (int)$wert;

    if ($zahl < $min) {
        return $min;
    }

    if ($zahl > $max) {
        return $max;
    }

    return $zahl;
}

try {
    $pdo = new PDO("sqlite:" . $dbFile);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Fehler bei der Datenbankverbindung: " . h($e->getMessage()));
}

// Aktuellen User laden
$stmt = $pdo->prepare('SELECT active FROM "user" WHERE UserID = :UserID');
$stmt->execute([":UserID" => $userID]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

$active = (int)($userData["active"] ?? 0);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $antwort = $_POST["antwort"] ?? "";

    $personen  = zahlBegrenzen($_POST["Personen"] ?? 0, 0, 5);
    $zeltKlein = zahlBegrenzen($_POST["ZeltKlein"] ?? 0, 0, 1);
    $zeltGross = zahlBegrenzen($_POST["ZeltGross"] ?? 0, 0, 1);
    $camper    = zahlBegrenzen($_POST["Camper"] ?? 0, 0, 1);
    $auto      = zahlBegrenzen($_POST["Auto"] ?? 0, 0, 1);
    $haenger   = zahlBegrenzen($_POST["Haenger"] ?? 0, 0, 1);
    $hund      = zahlBegrenzen($_POST["Hund"] ?? 0, 0, 3);

    $gold      = isset($_POST["Gold"]) ? 1 : 0;
    $silber    = isset($_POST["Silber"]) ? 1 : 0;
    $goldoTN   = isset($_POST["GoldoTN"]) ? 1 : 0;
    $silberoTN = isset($_POST["SilberoTN"]) ? 1 : 0;
    $wbsNein   = isset($_POST["WBSnein"]) ? 1 : 0;

    $notesText = trim($_POST["notes"] ?? "");

    if (mb_strlen($notesText, "UTF-8") > 250) {
        $notesText = mb_substr($notesText, 0, 250, "UTF-8");
    }

    // Teilnahme speichern
    $active = ($antwort === "ja") ? 1 : 0;

    $stmt = $pdo->prepare('
        UPDATE "user"
        SET active = :active,
        changedate = datetime("now", "localtime")
        WHERE UserID = :UserID
    ');

    $stmt->execute([
        ":active" => $active,
        ":UserID" => $userID
    ]);

    // Notes speichern: erst prüfen, ob es schon einen Datensatz gibt
    $stmt = $pdo->prepare('
        SELECT COUNT(*)
        FROM notes
        WHERE UserID = :UserID
    ');
    $stmt->execute([":UserID" => $userID]);
    $notesExists = (int)$stmt->fetchColumn();

    if ($notesExists > 0) {
        $stmt = $pdo->prepare('
            UPDATE notes
            SET Notes = :Notes
            WHERE UserID = :UserID
        ');
    } else {
        $stmt = $pdo->prepare('
            INSERT INTO notes
                (UserID, Notes)
            VALUES
                (:UserID, :Notes)
        ');
    }

    $stmt->execute([
        ":UserID" => $userID,
        ":Notes" => $notesText
    ]);

    if ($antwort === "ja") {
        $stmt = $pdo->prepare("
            INSERT INTO camping
                (UserID, Personen, ZeltKlein, ZeltGross, Camper, Auto, Haenger, Hund)
            VALUES
                (:UserID, :Personen, :ZeltKlein, :ZeltGross, :Camper, :Auto, :Haenger, :Hund)
            ON CONFLICT(UserID) DO UPDATE SET
                Personen = excluded.Personen,
                ZeltKlein = excluded.ZeltKlein,
                ZeltGross = excluded.ZeltGross,
                Camper = excluded.Camper,
                Auto = excluded.Auto,
                Haenger = excluded.Haenger,
                Hund = excluded.Hund
        ");

        $stmt->execute([
            ":UserID" => $userID,
            ":Personen" => $personen,
            ":ZeltKlein" => $zeltKlein,
            ":ZeltGross" => $zeltGross,
            ":Camper" => $camper,
            ":Auto" => $auto,
            ":Haenger" => $haenger,
            ":Hund" => $hund
        ]);

        $stmt = $pdo->prepare("
            INSERT INTO WBS
                (UserID, Gold, Silber, GoldoTN, SilberoTN, WBSnein)
            VALUES
                (:UserID, :Gold, :Silber, :GoldoTN, :SilberoTN, :WBSnein)
            ON CONFLICT(UserID) DO UPDATE SET
                Gold = excluded.Gold,
                Silber = excluded.Silber,
                GoldoTN = excluded.GoldoTN,
                SilberoTN = excluded.SilberoTN,
                WBSnein = excluded.WBSnein
        ");

        $stmt->execute([
            ":UserID" => $userID,
            ":Gold" => $gold,
            ":Silber" => $silber,
            ":GoldoTN" => $goldoTN,
            ":SilberoTN" => $silberoTN,
            ":WBSnein" => $wbsNein
        ]);

        $meldung = "Deine Angaben wurden gespeichert.";
    } elseif ($antwort === "nein") {
        $stmt = $pdo->prepare("DELETE FROM camping WHERE UserID = :UserID");
        $stmt->execute([":UserID" => $userID]);

        $stmt = $pdo->prepare("DELETE FROM WBS WHERE UserID = :UserID");
        $stmt->execute([":UserID" => $userID]);

        $meldung = "Du hast angegeben, dass du nicht mitkommst.";
    } else {
        $meldung = "Bitte wähle aus, ob du mitkommst oder nicht.";
    }
}

// Vorhandene Camping-Daten laden
$stmt = $pdo->prepare("SELECT * FROM camping WHERE UserID = :UserID");
$stmt->execute([":UserID" => $userID]);
$camping = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$camping) {
    $camping = [
        "Personen" => 1,
        "ZeltKlein" => 0,
        "ZeltGross" => 0,
        "Camper" => 0,
        "Auto" => 0,
        "Haenger" => 0,
        "Hund" => 0
    ];
}

// Vorhandene WBS-Daten laden
$stmt = $pdo->prepare("SELECT * FROM WBS WHERE UserID = :UserID");
$stmt->execute([":UserID" => $userID]);
$wbs = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$wbs) {
    $wbs = [
        "Gold" => 0,
        "Silber" => 0,
        "GoldoTN" => 0,
        "SilberoTN" => 0,
        "WBSnein" => 0
    ];
}

// Vorhandene Notes laden
$stmt = $pdo->prepare('
    SELECT Notes
    FROM notes
    WHERE UserID = :UserID
');
$stmt->execute([":UserID" => $userID]);
$notes = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$notes) {
    $notes = [
        "Notes" => ""
    ];
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aktivenzeltlager</title>
    <meta property="og:title" content="Aktiveneltlager 2026">
    <meta property="og:url" content="hhttps://aktivenzeltlager.ov-kraus.de/">
    <meta property="og:type" content="website">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Abfrage für das Aktivenzeltlager</h1>

    <div class="top-row">
        <div class="welcome-text">Hallo <?php echo h($firstname); ?>,</div>

        <form action="logout.php" method="POST" class="logout-form">
            <button type="submit">Logout</button>
        </form>
    </div>
    
    <?php if ($meldung !== ""): ?>
        <div class="summary-box">
            <h3>Zusammenfassung</h3>
            <p><?php echo h($meldung); ?></p>
        </div>
    <?php endif; ?>

    <form method="POST" id="anmeldeForm">
        <h3>Teilnahme:</h3>
        <div>
            <input type="radio" name="antwort" id="kommeja" value="ja" <?php echo $active === 1 ? "checked" : ""; ?>>
            <label for="kommeja">Ich komme mit</label>

            <br>

            <input type="radio" name="antwort" id="kommenein" value="nein" <?php echo $active === 0 ? "checked" : ""; ?>>
            <label for="kommenein">Ich komme doch nicht mit</label>
        </div>

        <div id="campingplatz" style="display: none;">
            <h3>Campingplatz</h3>

            <table>
                <tr>
                    <td>Personen über 16 Jahre:</td>
                    <td>
                        <input type="number" name="Personen" min="0" max="5" value="<?php echo h($camping["Personen"]); ?>">
                    </td>
                </tr>
                <tr>
                    <td>Zelt (max 3x3m):</td>
                    <td>
                        <input type="number" name="ZeltKlein" min="0" max="1" value="<?php echo h($camping["ZeltKlein"]); ?>">
                    </td>
                </tr>
                <tr>
                    <td>Zelt (max 5x6m):</td>
                    <td>
                        <input type="number" name="ZeltGross" min="0" max="1" value="<?php echo h($camping["ZeltGross"]); ?>">
                    </td>
                </tr>
                <tr>
                    <td>Camper/Wohnwagen/Auto m. Übernachtung:</td>
                    <td>
                        <input type="number" name="Camper" min="0" max="1" value="<?php echo h($camping["Camper"]); ?>">
                    </td>
                </tr>
                <tr>
                    <td>Auto o. Übernachtung:</td>
                    <td>
                        <input type="number" name="Auto" min="0" max="1" value="<?php echo h($camping["Auto"]); ?>">
                    </td>
                </tr>
                <tr>
                    <td>Hänger:</td>
                    <td>
                        <input type="number" name="Haenger" min="0" max="1" value="<?php echo h($camping["Haenger"]); ?>">
                    </td>
                </tr>
                <tr>
                    <td>Hund:</td>
                    <td>
                        <input type="number" name="Hund" min="0" max="3" value="<?php echo h($camping["Hund"]); ?>">
                    </td>
                </tr>
            </table>
        </div>

        <div id="WBS" style="display: none;">
            <h3>WBS Triathlon</h3>
            <div>Der <strong>WBS Triathlon</strong> besteht aus drei Disziplinen:
<strong>Wandern, Bauernbiertrinken und Schäuferlaessen</strong>.
Das Bier wird in drei Etappen getrunken: ein Drittel vor dem Wandern,
ein Drittel während der Wanderung und das letzte Drittel beim Schäuferlaessen.
Wahlweise gibt es <strong>auch alkoholfreie Getränke</strong>. 
<br>Alternativ kann auch ohne
Teilnahme am Triathlon gemeinschaftlich mitgewandert werden.

<br><br>

<strong>Gold:</strong> 20 km Wandern, 3 Liter Bier, Schäuferla mit Kloß + Urkunde<br>
<strong>Silber:</strong> 12,5 km Wandern, 2 Liter Bier, Schäuferla mit Kloß + Urkunde
<br><br>
<strong>Bitte wählt aus, wobei ihr dabei wärt. Basierend auf der Mehrheit kann ich anschließend die Buchung vornehmen. Mehrfachauswahl ist möglich.</strong> </div>
            <table>
                <tr>
                    <td>WBS Triathlon Gold (20km):</td>
                    <td>
                        <input type="checkbox" name="Gold" class="wbsCheck" <?php echo !empty($wbs["Gold"]) ? "checked" : ""; ?>>
                    </td>
                </tr>
                <tr>
                    <td>WBS Triathlon Silber (12km):</td>
                    <td>
                        <input type="checkbox" name="Silber" class="wbsCheck" <?php echo !empty($wbs["Silber"]) ? "checked" : ""; ?>>
                    </td>
                </tr>
                <tr>
                    <td>Gold-Strecke mitwandern ohne bei Triathlon mitzumachen:</td>
                    <td>
                        <input type="checkbox" name="GoldoTN" class="wbsCheck" <?php echo !empty($wbs["GoldoTN"]) ? "checked" : ""; ?>>
                    </td>
                </tr>
                <tr>
                    <td>Silber-Strecke mitwandern ohne bei Triathlon mitzumachen:</td>
                    <td>
                        <input type="checkbox" name="SilberoTN" class="wbsCheck" <?php echo !empty($wbs["SilberoTN"]) ? "checked" : ""; ?>>
                    </td>
                </tr>
                <tr>
                    <td>Keine Lust auf Wandern:</td>
                    <td>
                        <input type="checkbox" name="WBSnein" class="wbsCheck" <?php echo !empty($wbs["WBSnein"]) ? "checked" : ""; ?>>
                    </td>
                </tr>
            </table>
        </div>

        <div>
            <h3>Hinweise</h3>

            <textarea
                name="notes"
                id="notes"
                maxlength="250"
                rows="2"
            ><?php echo h($notes["Notes"] ?? ""); ?></textarea>

            <br>
            <small>(Optional. Maximal 250 Zeichen.)</small>
        </div>

        <br>

        <button type="submit">Speichern</button>
    </form>


    <script>
        const kommeJa = document.getElementById("kommeja");
        const kommeNein = document.getElementById("kommenein");
        const campingplatz = document.getElementById("campingplatz");
        const WBS = document.getElementById("WBS");

        function formularErweitern() {
            if (kommeJa.checked) {
                campingplatz.style.display = "block";
                WBS.style.display = "block";
            } else {
                campingplatz.style.display = "none";
                WBS.style.display = "none";
            }
        }

        kommeJa.addEventListener("change", formularErweitern);
        kommeNein.addEventListener("change", formularErweitern);

        formularErweitern();
    </script>

    <script>
        const form = document.getElementById("anmeldeForm");

        form.addEventListener("submit", function(event) {
            if (kommeJa.checked) {
                const wbsChecks = document.querySelectorAll(".wbsCheck");
                let mindestensEins = false;

                wbsChecks.forEach(function(check) {
                    if (check.checked) {
                        mindestensEins = true;
                    }
                });

                if (!mindestensEins) {
                    event.preventDefault();
                    alert("Bitte wähle mindestens eine Option beim WBS Triathlon aus.");
                }
            }
        });
    </script>
</body>
</html>
