This commit is contained in:
Borgal
2025-11-16 21:13:04 +01:00
parent aeb2d87cf5
commit 1b9ba22bb5
11 changed files with 1104 additions and 234 deletions

BIN
backups/DoMiLi_Backup_2025-10.pdf Executable file

Binary file not shown.

277
export.php Executable file
View File

@@ -0,0 +1,277 @@
<?php
// define('DOMILI_ALLOW_WEB', true); // Zum Testen im Browser einkommentieren
if (php_sapi_name() !== 'cli' && !defined('DOMILI_ALLOW_WEB')) {
die('Zugriff verweigert.');
}
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/inc/db.php';
use Dompdf\Dompdf;
use Dompdf\Options;
date_default_timezone_set('Europe/Berlin');
// === 1. Berichtsmonat ===
$berichtsMonatEnde = new DateTime('last day of last month');
$berichtsMonatBeginn = new DateTime('first day of last month');
// === 2. Letzter Jahresabschluss ===
$last_closing = '2020-01-01';
$res = mysqli_query($conn, "SELECT MAX(closing_date) AS last_date FROM penalty_closings");
if ($res && ($row = mysqli_fetch_assoc($res)) && !is_null($row['last_date'])) {
$last_closing = $row['last_date'];
}
// === 3. Alle Benutzer ===
$alleBenutzer = [];
$resUsers = mysqli_query($conn, "SELECT id, username FROM users ORDER BY username");
while ($row = mysqli_fetch_assoc($resUsers)) {
$alleBenutzer[$row['id']] = $row['username'];
}
$userIds = array_keys($alleBenutzer);
// === 4. Alle relevanten Daten (nur completed + attended=1) ===
$bisDatum = $berichtsMonatEnde->format('Y-m-d');
$stmt = mysqli_prepare($conn, "
SELECT m.id AS meeting_id, m.meeting_date,
mt.user_id, mt.wore_color, mt.paid
FROM meetings m
LEFT JOIN meeting_teilnehmer mt ON m.id = mt.meeting_id AND mt.attended = 1
WHERE m.meeting_date <= ? AND m.is_completed = 1
ORDER BY m.meeting_date
");
mysqli_stmt_bind_param($stmt, 's', $bisDatum);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$alleMeetingsMitTeilnehmern = [];
while ($row = mysqli_fetch_assoc($result)) {
$alleMeetingsMitTeilnehmern[] = $row;
}
mysqli_stmt_close($stmt);
// === 5. Meetings des Berichtsmonats mit Farben ===
$stmtMeta = mysqli_prepare($conn, "
SELECT id, meeting_date, reason, color_id
FROM meetings
WHERE meeting_date >= ? AND meeting_date <= ? AND is_completed = 1
ORDER BY meeting_date
");
$startDate = $berichtsMonatBeginn->format('Y-m-d');
$endDate = $berichtsMonatEnde->format('Y-m-d');
mysqli_stmt_bind_param($stmtMeta, 'ss', $startDate, $endDate);
mysqli_stmt_execute($stmtMeta);
$resultMeta = mysqli_stmt_get_result($stmtMeta);
$berichtsMeetingsMeta = [];
while ($row = mysqli_fetch_assoc($resultMeta)) {
$color_id = (int)$row['color_id'];
$colorStmt = mysqli_prepare($conn, "SELECT name FROM colors WHERE id = ?");
mysqli_stmt_bind_param($colorStmt, 'i', $color_id);
mysqli_stmt_execute($colorStmt);
$colorRes = mysqli_stmt_get_result($colorStmt);
$colorName = '';
if ($cRow = mysqli_fetch_assoc($colorRes)) {
$colorName = $cRow['name'];
}
mysqli_stmt_close($colorStmt);
$berichtsMeetingsMeta[] = [
'id' => $row['id'],
'meeting_date' => $row['meeting_date'],
'reason' => $row['reason'],
'color_name' => $colorName
];
}
mysqli_stmt_close($stmtMeta);
// === 6. Für jedes Meeting: alle Benutzer mit allen Werten ===
$gruppiert = [];
foreach ($berichtsMeetingsMeta as $meta) {
$mid = $meta['id'];
$meetingDatum = new DateTime($meta['meeting_date']);
$gruppiert[$mid] = [
'datum' => $meta['meeting_date'],
'reason' => $meta['reason'],
'color_name' => $meta['color_name'],
'teilnehmer' => []
];
foreach ($userIds as $uid) {
$username = $alleBenutzer[$uid];
$teilgenommen = false;
$wore_color = null;
$paid_this = false;
foreach ($alleMeetingsMitTeilnehmern as $mt) {
if ($mt['meeting_id'] == $mid && $mt['user_id'] == $uid) {
$teilgenommen = true;
$wore_color = !empty($mt['wore_color']);
$paid_this = !empty($mt['paid']);
break;
}
}
// Kumulierte Werte bis zu diesem Meeting
$strafenGesamt = 0;
$offeneStrafen = 0;
$teilnahmenGesamt = 0;
$rechnungenGesamt = 0;
foreach ($alleMeetingsMitTeilnehmern as $mt) {
if ($mt['user_id'] != $uid || is_null($mt['user_id'])) continue;
$mDatum = new DateTime($mt['meeting_date']);
if ($mDatum > $meetingDatum) continue;
$teilnahmenGesamt++;
if (!$mt['wore_color']) {
$strafenGesamt++;
if ($mt['meeting_date'] >= $last_closing) {
$offeneStrafen++;
}
}
if (!empty($mt['paid'])) {
$rechnungenGesamt++;
}
}
$userNameAnzeige = htmlspecialchars($username);
if ($paid_this) {
$userNameAnzeige .= ' <span class="paid-symbol">€</span>';
}
if (!$teilgenommen) {
$farbeSymbol = '';
} else {
$farbeSymbol = $wore_color ? '✓' : '✗';
}
$gruppiert[$mid]['teilnehmer'][] = [
'username' => $userNameAnzeige,
'farbe_symbol' => $farbeSymbol,
'teilgenommen' => $teilgenommen,
'offene_strafen' => $offeneStrafen,
'strafen_gesamt' => $strafenGesamt,
'teilnahmen_gesamt' => $teilnahmenGesamt,
'rechnungen_gesamt' => $rechnungenGesamt
];
}
}
// === 7. Gesamt offene Strafen ===
$gesamtOffen = 0;
foreach ($alleMeetingsMitTeilnehmern as $mt) {
if (!is_null($mt['user_id']) && !$mt['wore_color'] && $mt['meeting_date'] >= $last_closing) {
$gesamtOffen++;
}
}
// === 8. PDF-Pfad ===
@mkdir(__DIR__ . '/backups', 0755, true);
$baseName = 'DoMiLi_Backup_' . $berichtsMonatBeginn->format('Y-m');
$counter = 0;
$outputPath = __DIR__ . '/backups/' . $baseName . '.pdf';
while (file_exists($outputPath)) {
$counter++;
$outputPath = __DIR__ . '/backups/' . $baseName . '_' . $counter . '.pdf';
}
// === 9. HTML mit allen Anforderungen ===
$html = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: DejaVu Sans, Arial, sans-serif; font-size: 9pt; }
h1 { font-size: 14pt; margin-bottom: 14pt; }
h2 { font-size: 11pt; margin: 12pt 0 8pt 0; }
.strafkasse { font-weight: bold; margin: 0 0 14pt 0; padding: 6pt; background-color: #f9f9f9; border: 1px solid #ccc; }
table { width: 100%; border-collapse: collapse; margin-bottom: 12pt; }
th, td { border: 1px solid #333; padding: 4pt 6pt; text-align: left; }
th { background-color: #f0f0f0; font-weight: bold; }
.paid-symbol { color: red; font-weight: bold; }
.color-ok { color: green; }
.color-fail { color: red; }
.page-break { page-break-after: always; }
.meta { margin-top: 20pt; font-size: 8pt; color: #555; }
</style>
</head>
<body>
<h1>DoMiLi Monatliches Backup</h1>
<h2>Zeitraum: ' . $berichtsMonatBeginn->format('F Y') . '</h2>
<div class="strafkasse">Strafkasse: ' . $gesamtOffen . ' €</div>';
if (empty($berichtsMeetingsMeta)) {
$html .= '<p>Keine abgeschlossenen Meetings im Berichtsmonat.</p>';
} else {
$meetingCount = 0;
foreach ($gruppiert as $meeting) {
if ($meetingCount > 0 && $meetingCount % 3 === 0) {
$html .= '<div class="page-break"></div>';
}
$meetingCount++;
$meetingDatum = new DateTime($meeting['datum']);
$html .= '<h3>' . $meetingDatum->format('d.m.Y') . ' ' . htmlspecialchars($meeting['reason']) . ' (' . htmlspecialchars($meeting['color_name']) . ')</h3>';
$html .= '<table>
<thead>
<tr>
<th>Benutzer*</th>
<th>Farbe getragen</th>
<th>offene Strafen (in €)</th>
<th>Strafen gesamt</th>
<th>Teilnahmen gesamt</th>
<th>Rechnung gesamt</th>
</tr>
</thead>
<tbody>';
foreach ($meeting['teilnehmer'] as $t) {
if ($t['farbe_symbol'] === '✓') {
$farbeHtml = '<span class="color-ok">✓</span>';
} elseif ($t['farbe_symbol'] === '✗') {
$farbeHtml = '<span class="color-fail">✗</span>';
} else {
$farbeHtml = $t['farbe_symbol'];
}
$html .= '<tr>
<td>' . $t['username'] . '</td>
<td>' . $farbeHtml . '</td>
<td>' . $t['offene_strafen'] . '</td>
<td>' . $t['strafen_gesamt'] . '</td>
<td>' . $t['teilnahmen_gesamt'] . '</td>
<td>' . $t['rechnungen_gesamt'] . '</td>
</tr>';
}
$html .= '</tbody></table>';
}
}
$html .= '
<div class="meta">
<p>Erstellt am: ' . date('d.m.Y') . '</p>
<p><em>* = "€" hat Restaurant-Rechnung bezahlt</em></p>
</div>
</body>
</html>';
// === 10. PDF erzeugen ===
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
file_put_contents($outputPath, $dompdf->output());
echo "✅ PDF erfolgreich gespeichert: " . $outputPath . "\n";

View File

@@ -12,34 +12,42 @@
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link d-flex align-items-center" href="history.php">
<span class="material-icons md-18 me-2">calendar_month</span> History
<a class="nav-link d-flex align-items-center" href="planning.php">
<span class="material-icons md-18 me-2" style="width: 24px;">event</span> Terminplanung
</a>
</li>
<li class="nav-item">
<a class="nav-link d-flex align-items-center" href="kasse.php">
<span class="material-icons md-18 me-2">euro</span> Kasse
</a>
</li>
<li class="nav-item">
<a class="nav-link d-flex align-items-center" href="stats.php">
<li class="nav-item dropdown">
<a class="nav-link d-flex align-items-center dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<span class="material-icons md-18 me-2">bar_chart</span> Auswertung
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item d-flex align-items-center" href="history.php"><span class="material-icons text-secondary me-2">calendar_month</span>History</a></li>
<li><a class="dropdown-item d-flex align-items-center" href="kasse.php"><span class="material-icons text-secondary me-2">euro</span>Kasse</a></li>
<li><a class="dropdown-item d-flex align-items-center" href="stats.php"><span class="material-icons text-secondary me-2">bar_chart</span>Statistik</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link d-flex align-items-center" href="vacation.php">
<span class="material-icons md-18 me-2" style="width: 24px;">beach_access</span> Abwesenheiten
</a>
</li>
<li class="nav-item">
<a class="nav-link d-flex align-items-center" href="info.php">
<span class="material-icons md-18 me-2" style="width: 24px;">rule</span> Info
</a>
</li>
<li class="nav-item">
<a class="nav-link d-flex align-items-center" href="version.php">
<span class="material-icons md-18 me-2" style="width: 24px;">info</span> Release Notes
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link d-flex align-items-center dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<span class="material-icons md-18 me-2">settings</span> Settings
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item d-flex align-items-center" href="colors.php"><span class="material-icons text-secondary me-2">palette</span>Farben</a></li>
<li><a class="dropdown-item d-flex align-items-center" href="planning.php"><span class="material-icons text-secondary me-2">event</span>Terminplanung</a></li>
<li><a class="dropdown-item d-flex align-items-center" href="users.php"><span class="material-icons text-secondary me-2">group</span>Benutzer</a></li>
<li><a class="dropdown-item d-flex align-items-center" href="version.php"><span class="material-icons text-secondary me-2">info</span>Release Notes</a></li>
</ul>
</li>
</ul>

View File

@@ -179,68 +179,13 @@ if ($row) {
mysqli_stmt_close($attendees_stmt);
}
// --- ZAHLENDE PERSON BESTIMMEN (MIT GEBURTSTAGS-REGEL) ---
// --- ZAHLENDE PERSON BESTIMMEN ---
$next_payer_username = null;
if ($total_accepted > 0) {
$current_year = date('Y');
$meeting_date = $row['meeting_date'];
// Kandidaten holen
$sql_candidates = "
SELECT
u.id,
u.username,
u.birthday,
u.last_birthday_year,
(SELECT COUNT(*) FROM meeting_teilnehmer WHERE user_id = u.id AND paid = 1) AS paid_count
FROM meeting_teilnehmer mt
JOIN users u ON mt.user_id = u.id
WHERE mt.meeting_id = ? AND mt.rsvp_status = 'accepted'
ORDER BY u.username
";
$stmt_candidates = mysqli_prepare($conn, $sql_candidates);
mysqli_stmt_bind_param($stmt_candidates, "i", $meeting_id);
mysqli_stmt_execute($stmt_candidates);
$candidates = mysqli_fetch_all(mysqli_stmt_get_result($stmt_candidates), MYSQLI_ASSOC);
mysqli_stmt_close($stmt_candidates);
$birthday_payers = [];
$regular_payers = [];
foreach ($candidates as $c) {
if (empty($c['birthday'])) {
$regular_payers[] = $c;
continue;
include_once('zahler.php');
$next_payer_username = get_next_payer_username($conn, $meeting_id);
}
$birth_month = (int)date('m', strtotime($c['birthday']));
$birth_day = (int)date('d', strtotime($c['birthday']));
$birthday_this_year = "$current_year-$birth_month-$birth_day";
$already_paid_this_year = ($c['last_birthday_year'] == $current_year);
$birthday_passed = (strtotime($birthday_this_year) <= strtotime($meeting_date));
if (!$already_paid_this_year && $birthday_passed) {
$birthday_payers[] = $c;
} else {
$regular_payers[] = $c;
}
}
// Priorität: Geburtstagskinder zuerst
if (!empty($birthday_payers)) {
usort($birthday_payers, function ($a, $b) {
return $a['paid_count'] <=> $b['paid_count'];
});
$next_payer_username = $birthday_payers[0]['username'];
} elseif (!empty($regular_payers)) {
usort($regular_payers, function ($a, $b) {
return $a['paid_count'] <=> $b['paid_count'];
});
$next_payer_username = $regular_payers[0]['username'];
}
}
// --- TERMINVERSCHIEBUNG: Logik einbinden UND ausführen ---
include('verschiebung.php');
@@ -266,6 +211,34 @@ $german_weekdays = [
?>
<div class="container pt-0">
<?php
// 🔹 Hinweis für fehlende Profildaten (E-Mail oder Geburtstag)
if (isset($_SESSION['user_id'])) {
$user_profile_check = mysqli_prepare($conn, "SELECT email, birthday FROM users WHERE id = ?");
mysqli_stmt_bind_param($user_profile_check, "i", $_SESSION['user_id']);
mysqli_stmt_execute($user_profile_check);
$profile_data = mysqli_fetch_assoc(mysqli_stmt_get_result($user_profile_check));
mysqli_stmt_close($user_profile_check);
$email_missing = empty($profile_data['email']);
$birthday_missing = empty($profile_data['birthday']) || $profile_data['birthday'] === '0000-00-00';
if ($email_missing || $birthday_missing) {
echo '<div class="alert alert-info alert-dismissible fade show" role="alert">';
echo '<strong>Fast fertig!</strong> ';
if ($email_missing && $birthday_missing) {
echo 'Bitte trage deine E-Mail-Adresse und deinen Geburtstag in deinem Profil ein, um alle Funktionen nutzen zu können.';
} elseif ($email_missing) {
echo 'Bitte trage deine E-Mail-Adresse in deinem Profil ein.';
} else {
echo 'Bitte trage deinen Geburtstag in deinem Profil ein, um bei Geburtstagen berücksichtigt zu werden.';
}
echo ' <a href="profil.php" class="alert-link">Zum Profil</a>';
echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
echo '</div>';
}
}
?>
<?php if (isset($auto_declined) && $auto_declined === 'declined'): ?>
<div class="alert alert-info alert-dismissible fade show" role="alert">
Abwesenheitsmodus aktiv.

123
info.php Executable file
View File

@@ -0,0 +1,123 @@
<?php
include('inc/check_login.php');
require_once('inc/db.php');
require_once 'inc/header.php';
?>
<div class="container mt-5">
<h2 class="mb-4">Funktionen und Infos</h2>
<div class="alert alert-info d-flex align-items-start">
<i class="bi bi-info-circle me-2 mt-1"></i>
<div>
Dieses sind die aktuellen Funktionen und Regeln der DoMiLi-App.
Sie wurden zuletzt am <strong>11. November 2025</strong> aktualisiert.
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h5 class="mb-0">1. Farbwahl</h5>
</div>
<div class="card-body">
<ul class="mb-0" style="font-size: 0.95rem; line-height: 1.6;">
<li>Wer einen <b>Einteiler</b> in der gewählten Farbe trägt, bekommt einen <b>Bonus</b>.</li>
<li>Arbeitskleidung ist <b>nicht</b> zugelassen, ausgenommen Hosen.</li>
<li>Ausleihen von Kleidung ist <b>nicht</b> zugelassen.</li>
<li>Schriften, Logos etc. zählen <b>nicht</b> als Farbe (Farbanteil <b>min. 75%</b> des Oberteils)</li>
<li>Mäntel und Jacken sind <b>nicht</b> zugelassen</li>
<li>Umziehen nach 8 Uhr (Ausnahme Arbeitskleidung) nicht zugelassen</li>
<li>Die Farben werden <b>zufällig</b> gewählt, können aber nachträglich vom <b>Admin</b> geändert werden.</li>
<li>Welche <b>Farben</b> aktuell zur Auswahl stehen kann man im Menü unter <code>Settings -> Farben</code> sehen.</li>
<li>In der Übersicht ist auch die Anzahl der Farben einzusehen <i>(historische und schon geplante Treffen)</i>.</li>
<li>Es können natürlich Farben vom <b>Admin</b> hinzugefügt oder entfernt werden.</li>
<li>Die Auswahl der Farben ist zwar <b>zufällig</b>, aber schon genutzte Farben sollen <b><i>weniger wahrscheinlich</i></b> gewählt werden.</li>
<li>Es gibt Sonderfarben<span class="badge bg-info ms-1" title="Sonderfarbe nicht im Zufallsmodus">★</span> die nicht automatisch gewählt werden, diese können nur manuell gesetzt werden.</li>
</ul>
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h5 class="mb-0">2. Teilnahme</h5>
</div>
<div class="card-body">
<ul class="mb-0" style="font-size: 0.95rem; line-height: 1.6;">
<li>Eine Zu- bzw. Absage im Vorwege gibt einen guten Überblick und dient der Festlegung des Zahlers.</li>
<li>Auf der Startseite kann man in der Teilnehmerübersicht durch anklicken die Namen der Teilnehmer sehen.</li>
<li>Für eine längere Abwesenheit z.B. Urlaub kann man einen Abwesenheitsassistenten setzen, der automatisch absagt.</li>
<li>Nach dem Termin können von jedem User die Teilnehmer inkl. Farbe und Zahler eingetragen werden.</li>
</ul>
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h5 class="mb-0">3. Terminverschiebungen</h5>
</div>
<div class="card-body">
<ul class="mb-0" style="font-size: 0.95rem; line-height: 1.6;">
<li>Jeder User kann einen Änderungsvorschlag für einen Termine eintragen.</li>
<li>Die User können der Verschiebung zustimmen oder widersprechen. Die Verschiebung kann im Anschluss von einem <b>Admin</b> akzeptiert oder abgelehnt werden.</li>
<li>Die Benutzer werden bei jedem Verschiebungsvorschlag, sowie bei der Annahme/Ablehnung dessen per Mail benachrichtigt.</li>
<li>Die Vorschläge werden in der Statistik erfasst.</li>
</ul>
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h5 class="mb-0">4. Strafgeld</h5>
</div>
<div class="card-body">
<ul class="mb-0" style="font-size: 0.95rem; line-height: 1.6;">
<li>Nichtteilnahme ist straffrei.</li>
<li>Falsche Farbe getragen bedeutet eine Strafe von <b>1 €</b>.</li>
</ul>
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h5 class="mb-0">5. Zahler</h5>
</div>
<div class="card-body">
<ul class="mb-0" style="font-size: 0.95rem; line-height: 1.6;">
<li>Wer bisher am <b>seltensten gezahlt</b> hat, wird beim nächsten Treffen als <b>Zahler</b> vorgeschlagen.</li>
<li>Bei Gleichstand entscheidet die <b>alphabetische Reihenfolge</b> des Benutzernamens.</li>
<li>Hat ein User <b>Geburtstag</b> wird diese als Zahler für das nächste Treffen vorgeschlagen, dieses zählt <b>nicht</b> für die Zahler-Statistik.</li>
</ul>
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h5 class="mb-0">6. Auswertung</h5>
</div>
<div class="card-body">
<ul class="mb-0" style="font-size: 0.95rem; line-height: 1.6;">
<li>Unter der <b>Historie</b> kann man die Eintragung für <b>jedes Treffen</b> einsehen.</li>
<li>In der <b>Kasse</b> sieht man die Übersicht der <b>Strafen</b> und <b>Zahler</b></li>
<ul>
<li>Bei den offenen Strafen werden die Strafen bis zum Jahresabschluss summiert und anschließend zurückgesetzt.</li>
<li>In den Gesamtstrafen werden alle Strafen aus der Gesamthistorie seit App-Launch aufsummiert.</li>
<li>Im Ranking der Zahler ist die Auflistung der bisherigen Zahler einzusehen.</li>
</ul>
<li>In der <b>Statistik</b> befindet sich die Übersicht der</li>
<ul>
<li><b>Häufigkeit der Farben</b>.</li>
<li><b>Teilnahme-Ranking</b> mit Durchschnittlicher Teilnahme je Treffen und der Anzahl der Teilnahme je Benutzer.</li>
<li><b>Farbe getragen Ranking</b> mit Durchschnittlicher korrekten Farbe je Treffen, sowie die Anzahl der korrekten Farbe je User.</li>
<li><b>Verschiebevorschlag Ranking</b> Anzahl der Verschiebevorschlägen je Benutzer.</li>
</ul>
</ul>
</div>
</div>
<div class="text-center text-muted mt-4" style="font-size: 0.875rem;">
<i class="bi bi-clipboard-check me-1"></i>
The Regels sind the Regels.
</div>
</div>
<?php include('inc/footer.php'); ?>

420
kasse.php
View File

@@ -1,55 +1,265 @@
<?php
// PHP-Logik für die Datenabfrage
// KEIN LEERZEICHEN ODER ZEILENUMBRUCH VOR DIESEM <?php!
include('inc/check_login.php');
require_once('inc/db.php');
// --- 1. Jährliche Strafen-Statistik ---
// Passen Sie hier das Datum der Abschlussveranstaltung an.
$last_reset_date = '2024-01-01';
$is_admin = ($_SESSION['role'] === 'admin');
$penalties_data = [];
$total_penalties = 0;
$total_due = 0;
// Passen Sie hier die Höhe der Strafe in Euro an.
// --- JAHRESABSCHLUSS ---
if ($is_admin && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'close_year') {
$today = date('Y-m-d');
$user_id = $_SESSION['user_id'] ?? 0;
$last_closing_date = '2020-01-01';
$result_last = mysqli_query($conn, "SELECT MAX(closing_date) AS last_date FROM penalty_closings");
if ($result_last) {
$row = mysqli_fetch_assoc($result_last);
if ($row && !is_null($row['last_date'])) {
$last_closing_date = $row['last_date'];
}
}
$check = mysqli_prepare($conn, "SELECT 1 FROM penalty_closings WHERE closing_date = ?");
mysqli_stmt_bind_param($check, "s", $today);
mysqli_stmt_execute($check);
$exists = mysqli_stmt_get_result($check)->num_rows > 0;
mysqli_stmt_close($check);
if (!$exists) {
$insert = mysqli_prepare($conn, "INSERT INTO penalty_closings (closing_date, closed_by) VALUES (?, ?)");
mysqli_stmt_bind_param($insert, "si", $today, $user_id);
mysqli_stmt_execute($insert);
mysqli_stmt_close($insert);
$penalty_summary = [];
$stmt_email = mysqli_prepare($conn, "
SELECT u.username, COUNT(*) AS penalty_count
FROM meeting_teilnehmer mt
JOIN meetings m ON mt.meeting_id = m.id
JOIN users u ON mt.user_id = u.id
WHERE m.meeting_date >= ? AND m.meeting_date <= ?
AND mt.attended = 1 AND mt.wore_color = 0 AND m.is_completed = 1
GROUP BY u.username
");
mysqli_stmt_bind_param($stmt_email, "ss", $last_closing_date, $today);
mysqli_stmt_execute($stmt_email);
$result_email = mysqli_stmt_get_result($stmt_email);
while ($row = mysqli_fetch_assoc($result_email)) {
$penalty_summary[] = $row;
}
mysqli_stmt_close($stmt_email);
$all_users = [];
$stmt_users = mysqli_prepare($conn, "SELECT id, username, email FROM users WHERE email IS NOT NULL AND email != ''");
mysqli_stmt_execute($stmt_users);
$result_users = mysqli_stmt_get_result($stmt_users);
while ($row = mysqli_fetch_assoc($result_users)) {
$all_users[] = $row;
}
mysqli_stmt_close($stmt_users);
if (!empty($all_users) && file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
$today_formatted = date('d.m.Y', strtotime($today));
$last_closing_formatted = date('d.m.Y', strtotime($last_closing_date));
foreach ($all_users as $recipient) {
$recipient_email = $recipient['email'];
$recipient_name = $recipient['username'] ?? 'Benutzer';
try {
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->Host = SMTP_HOST;
$mail->SMTPAuth = true;
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->SMTPSecure = SMTP_ENCRYPTION;
$mail->Port = SMTP_PORT;
$mail->setFrom(MAIL_FROM_ADDRESS, MAIL_FROM_NAME);
$text_body = "Hallo $recipient_name,\n\n";
$text_body .= "Der Jahresabschluss wurde am $today_formatted durchgeführt.\n";
$text_body .= "Strafen der abgeschlossenen Periode (vom $last_closing_formatted bis $today_formatted):\n\n";
if (empty($penalty_summary)) {
$text_body .= "Keine Strafen in diesem Zeitraum.\n";
} else {
foreach ($penalty_summary as $row) {
$text_body .= "- " . $row['username'] . ": " . (int)$row['penalty_count'] . " Strafen (1 € pro Strafe)\n";
}
}
$text_body .= "\nDein DoMiLi-Admin.";
$html_table_rows = '';
if (empty($penalty_summary)) {
$html_table_rows = '<tr><td colspan="3" style="text-align:center;">Keine Strafen in diesem Zeitraum.</td></tr>';
} else {
foreach ($penalty_summary as $row) {
$html_table_rows .= sprintf(
'<tr>
<td style="padding:8px;border:1px solid #ddd;">%s</td>
<td style="padding:8px;border:1px solid #ddd;text-align:center;">%d</td>
<td style="padding:8px;border:1px solid #ddd;text-align:right;">%s</td>
</tr>',
htmlspecialchars($row['username']),
(int)$row['penalty_count'],
number_format((float)($row['penalty_count']), 2, ',', '.') . ' €'
);
}
}
$html_body = "
<p>Hallo <strong>$recipient_name</strong>,</p>
<p>der Jahresabschluss wurde am <strong>$today_formatted</strong> durchgeführt.</p>
<p><strong>Strafen der abgeschlossenen Periode</strong> (vom $last_closing_formatted bis $today_formatted):</p>
<table style=\"border-collapse:collapse;width:100%;margin:15px 0;\">
<thead>
<tr>
<th style=\"padding:8px;border:1px solid #ddd;text-align:left;background:#f2f2f2;\">Mitglied</th>
<th style=\"padding:8px;border:1px solid #ddd;text-align:center;background:#f2f2f2;\">Anzahl Strafen</th>
<th style=\"padding:8px;border:1px solid #ddd;text-align:right;background:#f2f2f2;\">Betrag</th>
</tr>
</thead>
<tbody>
$html_table_rows
</tbody>
</table>
<p><em>Dein DoMiLi-Admin.</em></p>";
$mail->isHTML(true);
$mail->Subject = "DoMiLi Jahresabschluss abgeschlossen am $today_formatted";
$mail->Body = $html_body;
$mail->AltBody = $text_body;
$mail->addAddress($recipient_email);
$mail->send();
} catch (Exception $e) {
error_log("PHPMailer Fehler: " . $mail->ErrorInfo);
}
}
}
$close_success = "Jahresabschluss erfolgreich durchgeführt!";
} else {
$close_error = "Heute wurde bereits ein Abschluss durchgeführt.";
}
}
// --- DATEN FÜR ANZEIGE ---
$last_closing_date = '2020-01-01';
$result_last = mysqli_query($conn, "SELECT MAX(closing_date) AS last_date FROM penalty_closings");
if ($result_last) {
$row = mysqli_fetch_assoc($result_last);
if ($row && !is_null($row['last_date'])) {
$last_closing_date = $row['last_date'];
}
}
$cumulative_penalties = [];
$stmt_cum = mysqli_prepare($conn, "
SELECT u.username, COUNT(*) AS total_penalty_count
FROM meeting_teilnehmer mt
JOIN meetings m ON mt.meeting_id = m.id
JOIN users u ON mt.user_id = u.id
WHERE mt.attended = 1 AND mt.wore_color = 0 AND m.is_completed = 1
GROUP BY u.username
");
mysqli_stmt_execute($stmt_cum);
$result_cum = mysqli_stmt_get_result($stmt_cum);
while ($row = mysqli_fetch_assoc($result_cum)) {
$cumulative_penalties[$row['username']] = (int)$row['total_penalty_count'];
}
mysqli_stmt_close($stmt_cum);
$open_penalties = [];
$total_open = 0;
$penalty_amount = 1;
// SQL-Abfrage, um Strafen pro Benutzer seit dem letzten Reset-Datum zu zählen
// Strafe = anwesend (attended=1) aber Farbe nicht getragen (wore_color=0)
// NEUE BEDINGUNG: Nur Meetings einbeziehen, die als abgeschlossen markiert sind.
$sql_penalties = "
SELECT
u.username,
COUNT(mt.user_id) AS penalty_count
$stmt_open = mysqli_prepare($conn, "
SELECT u.username, COUNT(*) AS open_penalty_count
FROM meeting_teilnehmer mt
JOIN meetings m ON mt.meeting_id = m.id
JOIN users u ON mt.user_id = u.id
WHERE m.meeting_date >= ? AND mt.attended = 1 AND mt.wore_color = 0 AND m.is_completed = 1
GROUP BY u.username
ORDER BY penalty_count DESC
";
$stmt = mysqli_prepare($conn, $sql_penalties);
// Überprüfen, ob das Statement erfolgreich vorbereitet wurde
if ($stmt === false) {
die("Fehler bei der SQL-Abfrage: " . mysqli_error($conn));
");
mysqli_stmt_bind_param($stmt_open, "s", $last_closing_date);
mysqli_stmt_execute($stmt_open);
$result_open = mysqli_stmt_get_result($stmt_open);
while ($row = mysqli_fetch_assoc($result_open)) {
$open_penalties[$row['username']] = (int)$row['open_penalty_count'];
$total_open += $row['open_penalty_count'];
}
mysqli_stmt_bind_param($stmt, "s", $last_reset_date);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt_open);
while ($row = mysqli_fetch_assoc($result)) {
$penalties_data[] = $row;
$total_penalties += $row['penalty_count'];
$total_due += $row['penalty_count'] * $penalty_amount;
$penalties_data = [];
$all_usernames = array_unique(array_merge(array_keys($cumulative_penalties), array_keys($open_penalties)));
foreach ($all_usernames as $username) {
$total = $cumulative_penalties[$username] ?? 0;
$open = $open_penalties[$username] ?? 0;
$penalties_data[] = [
'username' => $username,
'total_penalty_count' => $total,
'open_penalty_count' => $open
];
}
usort($penalties_data, fn($a, $b) => $b['open_penalty_count'] <=> $a['open_penalty_count']);
$total_penalties = array_sum(array_column($penalties_data, 'total_penalty_count'));
$total_due = $total_open * $penalty_amount;
$historical_table = [];
$closing_years = [];
$result_closings = mysqli_query($conn, "SELECT closing_date FROM penalty_closings ORDER BY closing_date");
while ($row = mysqli_fetch_assoc($result_closings)) {
$closing_date = new DateTime($row['closing_date']);
$year = (int)$closing_date->format('Y');
$month = (int)$closing_date->format('n');
$closed_year = ($month >= 7) ? $year : ($year - 1);
$closing_years[] = $closed_year;
}
$closing_years = array_unique($closing_years);
sort($closing_years);
if (!empty($closing_years)) {
foreach ($closing_years as $year) {
$year_start = "$year-01-01";
$year_end = "$year-12-31";
$stmt_hist = mysqli_prepare($conn, "
SELECT u.username, COUNT(*) AS penalty_count
FROM meeting_teilnehmer mt
JOIN meetings m ON mt.meeting_id = m.id
JOIN users u ON mt.user_id = u.id
WHERE m.meeting_date BETWEEN ? AND ?
AND mt.attended = 1 AND mt.wore_color = 0 AND m.is_completed = 1
GROUP BY u.username
");
mysqli_stmt_bind_param($stmt_hist, "ss", $year_start, $year_end);
mysqli_stmt_execute($stmt_hist);
$result_hist = mysqli_stmt_get_result($stmt_hist);
while ($row = mysqli_fetch_assoc($result_hist)) {
$username = $row['username'];
$count = (int)$row['penalty_count'];
if (!isset($historical_table[$username])) {
$historical_table[$username] = ['years' => [], 'total' => 0];
}
$historical_table[$username]['years'][] = $year;
$historical_table[$username]['total'] += $count;
}
mysqli_stmt_close($stmt_hist);
}
foreach ($historical_table as $username => $data) {
$historical_table[$username]['year_label'] = implode('/', $data['years']);
}
}
mysqli_stmt_close($stmt);
// Neue Statistik: Ranking nach bezahlten Strafen
// NEUE BEDINGUNG: Auch hier nur abgeschlossene Meetings einbeziehen.
$paid_stats = [];
$sql_paid = "
SELECT
u.username,
COUNT(mt.user_id) AS paid_count
SELECT u.username, COUNT(mt.user_id) AS paid_count
FROM meeting_teilnehmer mt
JOIN meetings m ON mt.meeting_id = m.id
JOIN users u ON mt.user_id = u.id
@@ -66,38 +276,58 @@ require_once 'inc/header.php';
?>
<div class="container mt-5">
<h2 class="mb-4">Kasse & Auswertung</h2>
<h2 class="mb-4">Kasse</h2>
<?php if (!empty($close_success)): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= htmlspecialchars($close_success) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (!empty($close_error)): ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= htmlspecialchars($close_error) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<div class="card shadow mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h4 class="mb-0">Strafen seit letztem Abschluss</h4>
<div class="card-header bg-primary-subtle text-secondary d-flex justify-content-between align-items-center">
<h4 class="mb-0">Strafen</h4>
<?php if ($is_admin): ?>
<form method="POST" class="d-flex align-items-center m-0" onsubmit="return confirm('Jahresabschluss durchführen?');">
<input type="hidden" name="action" value="close_year">
<button type="submit" class="btn btn-sm d-flex align-items-center justify-content-center p-0" style="height: 24px; font-size: 0.875rem;">
Jahresabschluss
<span class="material-symbols-outlined ms-1" style="font-size: 18px; line-height: 1;">add</span>
</button>
</form>
<?php endif; ?>
</div>
<div class="card-body">
<p class="fs-5 fw-bold text-center">
Gesamtzahl der Strafen: <span class="badge bg-danger"><?= $total_penalties ?></span><br>
Fälliger Gesamtbetrag: <span class="text-danger fw-bold"><?= number_format($total_due, 2, ',', '.'); ?> €</span>
Strafen gesamt: <span class="badge bg-danger"><?= $total_penalties ?></span><br>
offener Betrag: <span class="text-danger fw-bold"><?= number_format($total_due, 2, ',', '.') ?> €</span>
</p>
<?php if (empty($penalties_data)): ?>
<div class="alert alert-info text-center" role="alert">
Bisher wurden keine Strafen verzeichnet.
</div>
<div class="alert alert-info text-center">Keine Strafen erfasst.</div>
<?php else: ?>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Benutzer</th>
<th>Anzahl Strafen</th>
<th>Fälliger Betrag</th>
<th>Strafen gesamt</th>
<th>offener Betrag</th>
</tr>
</thead>
<tbody>
<?php foreach ($penalties_data as $penalty): ?>
<?php foreach ($penalties_data as $p): ?>
<tr>
<td><?= htmlspecialchars($penalty['username']); ?></td>
<td><?= htmlspecialchars($penalty['penalty_count']); ?></td>
<td><?= number_format($penalty['penalty_count'] * $penalty_amount, 2, ',', '.'); ?> €</td>
<td><?= htmlspecialchars($p['username']) ?></td>
<td><?= htmlspecialchars($p['total_penalty_count']) ?></td>
<td><?= number_format($p['open_penalty_count'] * $penalty_amount, 2, ',', '.') ?> €</td>
</tr>
<?php endforeach; ?>
</tbody>
@@ -107,40 +337,79 @@ require_once 'inc/header.php';
</div>
</div>
<div class="card shadow mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h4 class="mb-0">Historische Strafen</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Benutzer</th>
<th>Jahr(e)</th>
<th>Strafen</th>
</tr>
</thead>
<tbody>
<?php if (!empty($historical_table)): ?>
<?php foreach ($historical_table as $username => $data): ?>
<tr>
<td><?= htmlspecialchars($username) ?></td>
<td><?= htmlspecialchars($data['year_label']) ?></td>
<td><?= htmlspecialchars($data['total']) ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3" class="text-center text-muted">—</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="card shadow mb-4">
<div class="card-header bg-primary-subtle text-secondary">
<h4 class="mb-0">Rechnungen</h4>
</div>
<div class="card-body">
<h5 class="card-title text-center">Ranking - Rechnung übernommen</h5>
<h5 class="card-title text-center">Ranking Rechnung übernommen</h5>
<div style="height: 40vh;">
<canvas id="paidChart"></canvas>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Daten für "Gezahlt"-Diagramm
const paidData = {
labels: <?= json_encode(array_column($paid_stats, 'username')); ?>,
const rawLabels = <?php echo json_encode(array_column($paid_stats, 'username') ?: []); ?>;
const rawData = <?php echo json_encode(array_map('intval', array_column($paid_stats, 'paid_count') ?: [])); ?>;
const ctx = document.getElementById('paidChart').getContext('2d');
if (rawLabels.length === 0 || rawData.length === 0) {
document.getElementById('paidChart').closest('.card-body').innerHTML =
'<p class="text-muted text-center mt-3">Keine bezahlten Rechnungen erfasst.</p>';
return;
}
new Chart(ctx, {
type: 'bar',
data: {
labels: rawLabels,
datasets: [{
label: 'Gezahlte Strafen',
data: <?= json_encode(array_column($paid_stats, 'paid_count')); ?>,
backgroundColor: 'rgba(153, 102, 255, 0.8)',
borderColor: 'rgb(153, 102, 255)',
data: rawData,
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};
const paidConfig = {
type: 'bar',
data: paidData,
},
options: {
indexAxis: 'y',
responsive: true,
@@ -156,31 +425,28 @@ require_once 'inc/header.php';
},
scales: {
x: {
beginAtZero: true
beginAtZero: true,
ticks: {
stepSize: 1,
callback: function(value) {
return Number.isInteger(value) ? value : null;
}
}
},
y: {
ticks: {
font: {
size: 10
size: 12
},
callback: function(value, index, ticks) {
const username = this.getLabelForValue(value);
const maxChars = 15;
if (username.length > maxChars) {
return username.substring(0, maxChars) + '...';
}
return username;
const label = this.getLabelForValue(value);
return label.length > 15 ? label.substring(0, 15) + '…' : label;
}
}
}
}
}
};
new Chart(
document.getElementById('paidChart'),
paidConfig
);
});
});
</script>

View File

@@ -85,20 +85,38 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
}
mysqli_stmt_close($stmt_insert);
// 🔹 GEBURTSTAGS-REGEL: last_birthday_year setzen
// 🔹 GEBURTSTAGS-REGEL: last_birthday_year NUR setzen, wenn Geburtstag bereits war
$current_year = (int)date('Y');
$meeting_date_for_bday = $meeting['meeting_date'];
foreach ($_POST['user_id'] as $user_id) {
$user_id = (int)$user_id;
$paid = isset($_POST['paid'][$user_id]) ? 1 : 0;
$paid = isset($_POST['paid'][$user_id]) && $_POST['paid'][$user_id] == 1;
if ($paid) {
$stmt_bday = mysqli_prepare($conn, "
if (!$paid) continue;
$user_stmt = mysqli_prepare($conn, "SELECT birthday FROM users WHERE id = ? AND birthday IS NOT NULL");
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) continue;
$birthday = $user_row['birthday'];
$birth_month = (int)date('m', strtotime($birthday));
$birth_day = (int)date('d', strtotime($birthday));
$birthday_this_year = "$current_year-$birth_month-$birth_day";
if (strtotime($birthday_this_year) <= strtotime($meeting_date_for_bday)) {
$update_stmt = mysqli_prepare($conn, "
UPDATE users
SET last_birthday_year = YEAR(CURDATE())
WHERE id = ? AND birthday IS NOT NULL
SET last_birthday_year = ?
WHERE id = ?
");
mysqli_stmt_bind_param($stmt_bday, "i", $user_id);
mysqli_stmt_execute($stmt_bday);
mysqli_stmt_close($stmt_bday);
mysqli_stmt_bind_param($update_stmt, "ii", $current_year, $user_id);
mysqli_stmt_execute($update_stmt);
mysqli_stmt_close($update_stmt);
}
}

View File

@@ -5,10 +5,10 @@ require_once 'inc/db.php';
$message = '';
$message_type = '';
$user_id = (int)$_SESSION['user_id']; // Sicherheitshalber als Integer
$user_id = (int)$_SESSION['user_id'];
// Aktuelle Benutzerdaten laden
$stmt_fetch = mysqli_prepare($conn, "SELECT username, email, role, birthday FROM users WHERE id = ?");
$stmt_fetch = mysqli_prepare($conn, "SELECT username, email, role, birthday, last_birthday_year FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt_fetch, "i", $user_id);
mysqli_stmt_execute($stmt_fetch);
$result = mysqli_stmt_get_result($stmt_fetch);
@@ -20,9 +20,10 @@ if (!$user_data) {
}
$current_username = $user_data['username'];
$current_email = $user_data['email'];
$current_email = $user_data['email'] ?? '';
$current_role = $user_data['role'];
$current_birthday = $user_data['birthday'] ?? '';
$current_last_bday_year = $user_data['last_birthday_year'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$new_username = trim($_POST['username'] ?? '');
@@ -37,35 +38,85 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = "Ungültige E-Mail-Adresse.";
$message_type = 'danger';
} else {
$stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, email = ?, birthday = ? WHERE id = ?");
if ($stmt) {
// Standardwerte
$db_email = (!empty($new_email)) ? $new_email : null;
$db_birthday = (!empty($new_birthday)) ? $new_birthday : null;
// 🔹 GEBURTSTAGSLOGIK: Nur wenn Geburtstag neu/aktualisiert wird
$update_last_bday_year = false;
$new_last_bday_year = null;
if ($db_birthday !== null) {
$today = date('Y-m-d');
$current_year = (int)date('Y');
$birth_month = (int)date('m', strtotime($db_birthday));
$birth_day = (int)date('d', strtotime($db_birthday));
$birthday_this_year = "$current_year-$birth_month-$birth_day";
if (strtotime($birthday_this_year) < strtotime($today)) {
$new_last_bday_year = $current_year;
$update_last_bday_year = true;
}
}
// 🔹 Update in DB
mysqli_autocommit($conn, false);
$success = true;
// 1. Benutzerdaten aktualisieren
$stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, email = ?, birthday = ? WHERE id = ?");
if ($stmt) {
mysqli_stmt_bind_param($stmt, "sssi", $new_username, $db_email, $db_birthday, $user_id);
if (mysqli_stmt_execute($stmt)) {
if (!mysqli_stmt_execute($stmt)) {
$success = false;
}
mysqli_stmt_close($stmt);
} else {
$success = false;
}
// 2. Optional: last_birthday_year aktualisieren
if ($success && $update_last_bday_year) {
$stmt2 = mysqli_prepare($conn, "UPDATE users SET last_birthday_year = ? WHERE id = ?");
if ($stmt2) {
mysqli_stmt_bind_param($stmt2, "ii", $new_last_bday_year, $user_id);
if (!mysqli_stmt_execute($stmt2)) {
$success = false;
}
mysqli_stmt_close($stmt2);
} else {
$success = false;
}
}
if ($success) {
mysqli_commit($conn);
$_SESSION['username'] = $new_username;
$_SESSION['email'] = $new_email;
$result_reload = mysqli_query($conn, "SELECT username, email, role, birthday FROM users WHERE id = " . (int)$user_id);
if ($result_reload) {
$user_data = mysqli_fetch_assoc($result_reload);
// Neu laden
$stmt_reload = mysqli_prepare($conn, "SELECT username, email, role, birthday, last_birthday_year FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt_reload, "i", $user_id);
mysqli_stmt_execute($stmt_reload);
$user_data = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt_reload));
mysqli_stmt_close($stmt_reload);
$current_username = $user_data['username'];
$current_email = $user_data['email'];
$current_email = $user_data['email'] ?? '';
$current_role = $user_data['role'];
$current_birthday = $user_data['birthday'] ?? '';
}
$current_last_bday_year = $user_data['last_birthday_year'];
$message = "Profil erfolgreich aktualisiert!";
$message_type = 'success';
} else {
mysqli_rollback($conn);
$message = "Fehler beim Speichern der Daten.";
$message_type = 'danger';
}
mysqli_stmt_close($stmt);
} else {
$message = "Datenbankfehler: Statement konnte nicht vorbereitet werden.";
$message_type = 'danger';
}
mysqli_autocommit($conn, true);
}
}
}
@@ -96,12 +147,20 @@ require_once 'inc/header.php';
</div>
<div class="mb-3">
<label for="email" class="form-label fw-bold">E-Mail-Adresse</label>
<input type="email" class="form-control" id="email" name="email" value="<?= htmlspecialchars($current_email) ?>">
<input type="email" class="form-control" id="email" name="email" value="<?= htmlspecialchars($current_email ?? '') ?>">
</div>
<div class="mb-3">
<label for="birthday" class="form-label fw-bold">Geburtstag</label>
<input type="date" class="form-control" id="birthday" name="birthday" value="<?= htmlspecialchars($current_birthday) ?>">
<small class="form-text text-muted">Für automatische Sonderzahlung.</small>
<input type="date" class="form-control" id="birthday" name="birthday" value="<?= htmlspecialchars($current_birthday ?? '') ?>">
<small class="form-text text-muted">
<?php if (!empty($current_birthday) && $current_last_bday_year == date('Y')): ?>
<span class="text-success">✓ In diesem Jahr bereits als Geburtstagszahler markiert.</span>
<?php elseif (!empty($current_birthday)): ?>
Geburtstag steht noch an du kannst als Sonderzahler vorgeschlagen werden.
<?php else: ?>
Für automatische Sonderzahlung.
<?php endif; ?>
</small>
</div>
<div class="mb-3">
<label for="role" class="form-label fw-bold">Rolle</label>

View File

@@ -9,6 +9,28 @@ $message_type = '';
$edit_mode = false;
$edit_user = null;
// Hilfsfunktion: DE-Format zu DB-Format
function deDateToDb($deDate)
{
if (empty($deDate)) return null;
$parts = explode('.', $deDate);
if (count($parts) !== 3) return null;
$day = str_pad($parts[0], 2, '0', STR_PAD_LEFT);
$month = str_pad($parts[1], 2, '0', STR_PAD_LEFT);
$year = $parts[2];
if (checkdate((int)$month, (int)$day, (int)$year)) {
return "$year-$month-$day";
}
return null;
}
// Hilfsfunktion: DB-Format zu DE-Format
function dbDateToDe($dbDate)
{
if (empty($dbDate) || $dbDate === '0000-00-00') return '';
return date('d.m.Y', strtotime($dbDate));
}
// --- Nur Admins: Löschen ---
if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
$id = (int)$_GET['id'];
@@ -34,7 +56,7 @@ if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'delete' && isset(
// --- Nur Admins: Bearbeiten ---
if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id'])) {
$id = (int)$_GET['id'];
$stmt = mysqli_prepare($conn, "SELECT id, username, email, role FROM users WHERE id = ?");
$stmt = mysqli_prepare($conn, "SELECT id, username, email, role, birthday FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
@@ -45,6 +67,9 @@ if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_
if (!$edit_user) {
$message = "Benutzer nicht gefunden.";
$message_type = 'warning';
} else {
// Konvertiere DB-Datum zu DE-Format für das Formular
$edit_user['birthday_de'] = dbDateToDe($edit_user['birthday']);
}
}
@@ -53,10 +78,12 @@ if ($is_admin && $_SERVER["REQUEST_METHOD"] == "POST") {
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
$email_raw = trim($_POST['email'] ?? '');
$birthday_de = trim($_POST['birthday'] ?? '');
$role = ($_POST['role'] ?? 'member') === 'admin' ? 'admin' : 'member';
$id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
$email = !empty($email_raw) ? $email_raw : null;
$birthday_db = deDateToDb($birthday_de); // null bei ungültig/leer
if (empty($username)) {
$message = "Benutzername ist erforderlich.";
@@ -65,11 +92,11 @@ if ($is_admin && $_SERVER["REQUEST_METHOD"] == "POST") {
if ($id) {
if (!empty($password)) {
$password_hashed = password_hash($password, PASSWORD_DEFAULT);
$stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, password = ?, email = ?, role = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "ssssi", $username, $password_hashed, $email, $role, $id);
$stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, password = ?, email = ?, birthday = ?, role = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "sssssi", $username, $password_hashed, $email, $birthday_db, $role, $id);
} else {
$stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, email = ?, role = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "sssi", $username, $email, $role, $id);
$stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, email = ?, birthday = ?, role = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "ssssi", $username, $email, $birthday_db, $role, $id);
}
} else {
if (empty($password)) {
@@ -77,8 +104,8 @@ if ($is_admin && $_SERVER["REQUEST_METHOD"] == "POST") {
$message_type = 'danger';
} else {
$password_hashed = password_hash($password, PASSWORD_DEFAULT);
$stmt = mysqli_prepare($conn, "INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssss", $username, $password_hashed, $email, $role);
$stmt = mysqli_prepare($conn, "INSERT INTO users (username, password, email, birthday, role) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "sssss", $username, $password_hashed, $email, $birthday_db, $role);
}
}
@@ -99,7 +126,7 @@ if ($is_admin && $_SERVER["REQUEST_METHOD"] == "POST") {
// --- Mitgliederliste für alle ---
$users = [];
$result = mysqli_query($conn, "SELECT id, username, role FROM users ORDER BY id ASC");
$result = mysqli_query($conn, "SELECT id, username, role, email, birthday FROM users ORDER BY id ASC");
while ($row = mysqli_fetch_assoc($result)) {
$users[] = $row;
}
@@ -140,6 +167,11 @@ require_once 'inc/header.php';
<label class="form-label">E-Mail (optional)</label>
<input type="email" class="form-control" name="email" value="<?= htmlspecialchars($edit_user['email'] ?? ''); ?>">
</div>
<div class="col-md-3">
<label class="form-label">Geburtsdatum (optional, TT.MM.JJJJ)</label>
<input type="text" class="form-control" name="birthday" placeholder="z.B. 15.08.1990" value="<?= htmlspecialchars($edit_user['birthday_de'] ?? ''); ?>">
<div class="form-text">Leer lassen, um kein Geburtsdatum zu speichern.</div>
</div>
<div class="col-md-3">
<label class="form-label">Passwort</label>
<input type="password" class="form-control" name="password" placeholder="<?= $edit_mode ? 'Leer lassen = unverändert' : 'Erforderlich' ?>">
@@ -182,10 +214,11 @@ require_once 'inc/header.php';
<thead>
<tr>
<th>ID</th>
<th>Benutzername</th>
<th>User</th>
<th class="text-center" style="width: 56px;">Daten</th>
<th>Rolle</th>
<?php if ($is_admin): ?>
<th>Aktionen</th>
<th class="text-end"></th>
<?php endif; ?>
</tr>
</thead>
@@ -194,6 +227,20 @@ require_once 'inc/header.php';
<tr>
<td><?= htmlspecialchars($user['id']) ?></td>
<td><?= htmlspecialchars($user['username']) ?></td>
<td class="text-center align-middle">
<div class="d-flex" style="justify-content: center; height: 1.4rem; gap: 0.25rem;">
<div class="d-flex align-items-center justify-content-center" style="width: 1.3em;">
<?php if (!empty($user['email'])): ?>
<span class="material-symbols-outlined text-success" style="font-size:0.8em; line-height:1;" title="E-Mail vorhanden">mail</span>
<?php endif; ?>
</div>
<div class="d-flex align-items-center justify-content-center" style="width: 1.3em;">
<?php if (!empty($user['birthday']) && $user['birthday'] !== '0000-00-00'): ?>
<span class="material-symbols-outlined text-info" style="font-size:0.8em; line-height:1;" title="Geburtstag vorhanden">cake</span>
<?php endif; ?>
</div>
</div>
</td>
<td>
<span class="badge rounded-pill bg-<?= $user['role'] === 'admin' ? 'info' : 'secondary' ?>">
<?= htmlspecialchars($user['role']) ?>

View File

@@ -1,6 +1,9 @@
<?php
define('APP_URL', 'https://domili.borgal.de');
// 🔒 Testmodus: true = nur User-ID 1, false = alle Benutzer
$test_mode = false;
function load_reschedule_data($conn, $meeting_id, $user_id)
{
$stmt = mysqli_prepare($conn, "
@@ -67,6 +70,8 @@ function load_reschedule_data($conn, $meeting_id, $user_id)
function handle_reschedule_actions($conn, $meeting_id, $user_id)
{
global $test_mode;
// Vorschlag einreichen
if (isset($_POST['propose_reschedule']) && isset($_POST['new_date']) && isset($_POST['reason'])) {
$new_date = $_POST['new_date'];
@@ -100,7 +105,6 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
require_once __DIR__ . '/vendor/autoload.php';
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isHTML(false);
$orig_date = null;
$orig_stmt = mysqli_prepare($conn, "SELECT meeting_date FROM meetings WHERE id = ?");
@@ -122,15 +126,43 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
$proposer = $_SESSION['username'] ?? 'Ein Benutzer';
$new_fmt = date('d.m.Y H:i', strtotime($new_date));
$subject = "DoMiLi: Neuer Terminvorschlag für den ursprünglichen Termin vom $orig_str";
$body = "Hallo %s,\n\n%s hat einen neuen Vorschlag zur Verschiebung des Termins eingereicht.\nNeuer vorgeschlagener Termin: %s\nGrund: %s\n\nBitte stimme erneut ab, ob du teilnehmen möchtest.\n\nZur Abstimmung: DoMiLi-APP\n%s\n\nDein DoMiLi-Team";
// 🔒 Empfängerliste Testmodus?
if ($test_mode) {
$users_stmt = mysqli_query($conn, "SELECT username, email FROM users WHERE id = 1 AND email IS NOT NULL AND email != ''");
} else {
$users_stmt = mysqli_query($conn, "SELECT username, email FROM users WHERE email IS NOT NULL AND email != ''");
}
while ($u = mysqli_fetch_assoc($users_stmt)) {
// Überspringe den eigenen Vorschlag aber im Testmodus ggf. auskommentieren
if (isset($_SESSION['email']) && $u['email'] === $_SESSION['email']) continue;
$mail_body_html = '
<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif; line-height: 1.6; color: #333; max-width: 700px; margin: 0 auto; padding: 20px; background: #f8f9fa;">
<div style="background: white; padding: 24px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.08);">
<h3 style="color: #0d6efd; margin-top: 0;">Neuer Terminvorschlag</h3>
<p>Hallo <strong>' . htmlspecialchars($u['username']) . '</strong>,</p>
<div style="background: #f0f7ff; border-left: 4px solid #0d6efd; padding: 16px; margin: 16px 0; border-radius: 0 4px 4px 0;">
<p><strong>' . htmlspecialchars($proposer) . '</strong> hat einen neuen Vorschlag zur Verschiebung des Termins eingereicht.</p>
<p><strong>Neuer vorgeschlagener Termin:</strong><br>
' . htmlspecialchars($new_fmt) . '</p>
<p><strong>Grund:</strong><br>
' . htmlspecialchars($reason) . '</p>
</div>
<p>Bitte stimme erneut ab, ob du teilnehmen möchtest.</p>
<p><a href="' . APP_URL . '/index.php" style="display: inline-block; background: #0d6efd; color: white; text-decoration: none; padding: 8px 16px; border-radius: 4px; font-weight: 500;">Zur Abstimmung</a></p>
<p style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #eee; color: #6c757d; font-size: 0.875rem;">
Dein DoMiLi-Team
</p>
</div>
</div>';
$mail->isHTML(true);
$mail->addAddress($u['email']);
$mail->Subject = $subject;
$mail->Body = sprintf($body, $u['username'], $proposer, $new_fmt, $reason, APP_URL . '/index.php');
$mail->Subject = "DoMiLi: Neuer Terminvorschlag für den ursprünglichen Termin vom $orig_str";
$mail->Body = $mail_body_html;
$mail->AltBody = "Hallo " . $u['username'] . ",\n\n" . $proposer . " hat einen neuen Vorschlag zur Verschiebung eingereicht.\nNeuer Termin: " . $new_fmt . "\nGrund: " . $reason . "\n\nZur Abstimmung: " . APP_URL . "/index.php\n\nDein DoMiLi-Team";
$mail->send();
$mail->clearAddresses();
}
@@ -229,13 +261,13 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
$meeting_id = $proposal['meeting_id'];
$original_date = $proposal['original_date'];
// Meeting aktualisieren
// Meeting aktualisieren ACHTUNG: nur meeting_date, kein reason hier
$update_meeting = mysqli_prepare($conn, "
UPDATE meetings
SET meeting_date = ?
WHERE id = ?
");
mysqli_stmt_bind_param($update_meeting, "ssi", $new_date, $new_reason, $meeting_id);
mysqli_stmt_bind_param($update_meeting, "si", $new_date, $meeting_id);
mysqli_stmt_execute($update_meeting);
mysqli_stmt_close($update_meeting);
@@ -264,7 +296,6 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
require_once __DIR__ . '/vendor/autoload.php';
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isHTML(false);
try {
$mail->isSMTP();
@@ -278,14 +309,41 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
$orig_fmt = date('d.m.Y H:i', strtotime($original_date));
$new_fmt = date('d.m.Y H:i', strtotime($new_date));
$subject = "DoMiLi: Termin wurde verschoben!";
$body = "Hallo %s,\n\nDer Termin wurde vom Admin verschoben.\n\nUrsprünglicher Termin: %s\nNeuer Termin: %s\nGrund: %s\n\nBitte stimme erneut ab, ob du teilnehmen möchtest.\n\nZur Abstimmung: DoMiLi-APP\n%s\n\nDein DoMiLi-Team";
if ($test_mode) {
$users_stmt = mysqli_query($conn, "SELECT username, email FROM users WHERE id = 1 AND email IS NOT NULL AND email != ''");
} else {
$users_stmt = mysqli_query($conn, "SELECT username, email FROM users WHERE email IS NOT NULL AND email != ''");
}
while ($u = mysqli_fetch_assoc($users_stmt)) {
$mail_body_html = '
<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif; line-height: 1.6; color: #333; max-width: 700px; margin: 0 auto; padding: 20px; background: #f8f9fa;">
<div style="background: white; padding: 24px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.08);">
<h3 style="color: #0d6efd; margin-top: 0;">Termin wurde verschoben!</h3>
<p>Hallo <strong>' . htmlspecialchars($u['username']) . '</strong>,</p>
<div style="background: #f0f7ff; border-left: 4px solid #0d6efd; padding: 16px; margin: 16px 0; border-radius: 0 4px 4px 0;">
<p>Der Termin wurde vom Admin verschoben.</p>
<p><strong>Ursprünglicher Termin:</strong><br>
' . htmlspecialchars($orig_fmt) . '</p>
<p><strong>Neuer Termin:</strong><br>
' . htmlspecialchars($new_fmt) . '</p>
<p><strong>Grund:</strong><br>
' . htmlspecialchars($new_reason) . '</p>
</div>
<p>Bitte stimme erneut ab, ob du teilnehmen möchtest.</p>
<p><a href="' . APP_URL . '/index.php" style="display: inline-block; background: #0d6efd; color: white; text-decoration: none; padding: 8px 16px; border-radius: 4px; font-weight: 500;">Zur Abstimmung</a></p>
<p style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #eee; color: #6c757d; font-size: 0.875rem;">
Dein DoMiLi-Team
</p>
</div>
</div>';
$mail->isHTML(true);
$mail->addAddress($u['email']);
$mail->Subject = $subject;
$mail->Body = sprintf($body, $u['username'], $orig_fmt, $new_fmt, $new_reason, APP_URL . '/index.php');
$mail->Subject = "DoMiLi: Termin wurde verschoben!";
$mail->Body = $mail_body_html;
$mail->AltBody = "Hallo " . $u['username'] . ",\n\nDer Termin wurde verschoben.\nUrsprünglich: " . $orig_fmt . "\nNeu: " . $new_fmt . "\nGrund: " . $new_reason . "\n\nZur Abstimmung: " . APP_URL . "/index.php\n\nDein DoMiLi-Team";
$mail->send();
$mail->clearAddresses();
}
@@ -303,7 +361,6 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
if (isset($_POST['reject_proposal']) && isset($_POST['proposal_id'])) {
$proposal_id = intval($_POST['proposal_id']);
// Vorschlagdaten laden
$proposal_stmt = mysqli_prepare($conn, "
SELECT p.proposed_by_user_id, u.username AS proposer_name,
m.meeting_date AS original_date
@@ -317,7 +374,6 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
$proposal = mysqli_fetch_assoc(mysqli_stmt_get_result($proposal_stmt));
mysqli_stmt_close($proposal_stmt);
// Vorschlag ablehnen
$reject_stmt = mysqli_prepare($conn, "
UPDATE meeting_reschedule_proposals
SET status = 'rejected'
@@ -332,7 +388,6 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
require_once __DIR__ . '/vendor/autoload.php';
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isHTML(false);
try {
$mail->isSMTP();
@@ -346,14 +401,34 @@ function handle_reschedule_actions($conn, $meeting_id, $user_id)
$proposer = $proposal['proposer_name'];
$original_fmt = date('d.m.Y H:i', strtotime($proposal['original_date']));
$subject = "DoMiLi: Verschiebungsvorschlag abgelehnt";
$body = "Hallo %s,\n\nDer Verschiebungsvorschlag von {$proposer} wurde vom Admin abgelehnt.\nDer Termin bleibt daher unverändert beim ursprünglichen Termin am {$original_fmt}.\n\nDein DoMiLi-Team";
if ($test_mode) {
$users_stmt = mysqli_query($conn, "SELECT username, email FROM users WHERE id = 1 AND email IS NOT NULL AND email != ''");
} else {
$users_stmt = mysqli_query($conn, "SELECT username, email FROM users WHERE email IS NOT NULL AND email != ''");
}
while ($u = mysqli_fetch_assoc($users_stmt)) {
$mail_body_html = '
<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif; line-height: 1.6; color: #333; max-width: 700px; margin: 0 auto; padding: 20px; background: #f8f9fa;">
<div style="background: white; padding: 24px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.08);">
<h3 style="color: #dc3545; margin-top: 0;">Verschiebungsvorschlag abgelehnt</h3>
<p>Hallo <strong>' . htmlspecialchars($u['username']) . '</strong>,</p>
<div style="background: #fff5f5; border-left: 4px solid #dc3545; padding: 16px; margin: 16px 0; border-radius: 0 4px 4px 0;">
<p>Der Verschiebungsvorschlag von <strong>' . htmlspecialchars($proposer) . '</strong> wurde vom Admin abgelehnt.</p>
<p>Der Termin bleibt daher unverändert beim ursprünglichen Termin am <strong>' . htmlspecialchars($original_fmt) . '</strong>.</p>
</div>
<p style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #eee; color: #6c757d; font-size: 0.875rem;">
Dein DoMiLi-Team
</p>
</div>
</div>';
$mail->isHTML(true);
$mail->addAddress($u['email']);
$mail->Subject = $subject;
$mail->Body = sprintf($body, $u['username']);
$mail->Subject = "DoMiLi: Verschiebungsvorschlag abgelehnt";
$mail->Body = $mail_body_html;
$mail->AltBody = "Hallo " . $u['username'] . ",\n\nDer Verschiebungsvorschlag von " . $proposer . " wurde abgelehnt.\nDer Termin bleibt beim ursprünglichen Termin am " . $original_fmt . ".\n\nDein DoMiLi-Team";
$mail->send();
$mail->clearAddresses();
}

View File

@@ -1,35 +1,59 @@
<?php
function get_next_payer_username($conn, $meeting_id)
{
$current_year = (int)date('Y');
// Alle zugesagten Nutzer mit paid_count
$sql = "
SELECT
u.id,
u.username,
u.birthday,
u.last_birthday_year,
(SELECT COUNT(*) FROM meeting_teilnehmer WHERE user_id = u.id AND paid = 1) AS paid_count
FROM meeting_teilnehmer mt
JOIN users u ON mt.user_id = u.id
WHERE mt.meeting_id = ? AND mt.rsvp_status = 'accepted'
ORDER BY paid_count ASC
ORDER BY u.username
";
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) return null;
mysqli_stmt_bind_param($stmt, "i", $meeting_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$candidates = [];
$min_count = -1;
while ($row = mysqli_fetch_assoc($result)) {
if ($min_count == -1 || $row['paid_count'] < $min_count) {
$min_count = $row['paid_count'];
$candidates = [$row['username']];
} elseif ($row['paid_count'] == $min_count) {
$candidates[] = $row['username'];
}
}
$candidates = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
mysqli_stmt_close($stmt);
if (empty($candidates)) return null;
sort($candidates);
return $candidates[0];
// Finde minimale paid_count
$min_paid = min(array_column($candidates, 'paid_count'));
$eligible = array_filter($candidates, fn($c) => $c['paid_count'] == $min_paid);
$birthday_eligible = [];
$others = [];
foreach ($eligible as $c) {
$is_birthday_payer_eligible = (
!empty($c['birthday'])
&& $c['birthday'] !== '0000-00-00'
&& $c['last_birthday_year'] != $current_year
);
if ($is_birthday_payer_eligible) {
$birthday_eligible[] = $c;
} else {
$others[] = $c;
}
}
// Sortiere alphabetisch
$sort = fn($a, $b) => strcmp($a['username'], $b['username']);
if (!empty($birthday_eligible)) {
usort($birthday_eligible, $sort);
return $birthday_eligible[0]['username'];
}
$all = array_merge($birthday_eligible, $others);
usort($all, $sort);
return $all[0]['username'];
}