<?php

/**
 * Gibt den Vorschlag für den nächsten Rechnungszahler zurück.
 * Liefert ein Array: ['username' => ..., 'is_birthday_payer' => true/false]
 */
function get_next_payer_info($conn, $meeting_id)
{
    // Meeting-Datum holen
    $stmt = mysqli_prepare($conn, "SELECT meeting_date 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) {
        return null;
    }

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

    // Alle ZUSAGENDEN Teilnehmer
    $sql = "
        SELECT 
            u.id,
            u.username,
            u.birthday
        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 = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "i", $meeting_id);
    mysqli_stmt_execute($stmt);
    $candidates = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
    mysqli_stmt_close($stmt);

    if (empty($candidates)) {
        return null;
    }

    // 🔹 Geburtstagskandidaten: Geburtstag war + noch nicht in diesem Jahr als Geburtstagszahler gezahlt
    $birthday_candidates = array_filter($candidates, function ($c) use ($conn, $meeting_year, $meeting_month, $meeting_day) {
        if (!$c['birthday'] || $c['birthday'] === '0000-00-00') {
            return false;
        }

        $bday_month = (int)date('n', strtotime($c['birthday']));
        $bday_day   = (int)date('j', strtotime($c['birthday']));

        // War Geburtstag in diesem Jahr bereits?
        if (!($bday_month < $meeting_month ||
            ($bday_month == $meeting_month && $bday_day <= $meeting_day))) {
            return false;
        }

        // 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", $c['id'], $meeting_year);
        mysqli_stmt_execute($check_stmt);
        $already_paid = mysqli_num_rows(mysqli_stmt_get_result($check_stmt)) > 0;
        mysqli_stmt_close($check_stmt);

        return !$already_paid;
    });

    if (!empty($birthday_candidates)) {
        usort($birthday_candidates, fn($a, $b) => strcmp($a['username'], $b['username']));
        $first = $birthday_candidates[0];
        return [
            'username' => $first['username'],
            'is_birthday_payer' => true
        ];
    }

    // 🔹 Normale Rotation: Zähle paid=1 UND birthday_pay=0
    $user_paid_counts = [];
    foreach ($candidates as $c) {
        $count_stmt = mysqli_prepare($conn, "
            SELECT COUNT(*) 
            FROM meeting_teilnehmer 
            WHERE user_id = ? AND paid = 1 AND birthday_pay = 0
        ");
        mysqli_stmt_bind_param($count_stmt, "i", $c['id']);
        mysqli_stmt_execute($count_stmt);
        $count = (int)mysqli_fetch_row(mysqli_stmt_get_result($count_stmt))[0];
        mysqli_stmt_close($count_stmt);
        $user_paid_counts[$c['id']] = $count;
    }

    $min_paid = min($user_paid_counts);
    $regular_candidates = array_filter($candidates, function ($c) use ($user_paid_counts, $min_paid) {
        return $user_paid_counts[$c['id']] === $min_paid;
    });

    usort($regular_candidates, fn($a, $b) => strcmp($a['username'], $b['username']));
    $first = reset($regular_candidates);
    return [
        'username' => $first['username'],
        'is_birthday_payer' => false
    ];
}
