<?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'];
    $current_year = (int)date('Y', strtotime($meeting_date));

    // Alle ZUSAGENDEN Teilnehmer dieses Meetings
    $sql = "
        SELECT 
            u.id,
            u.username,
            u.birthday,
            u.birthday_payer_pending,
            u.regular_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 = 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;
    }

    // 🔹 PRIORITÄT 1: Geburtstags-Zahler (birthday_payer_pending = 1)
    $birthday_candidates = array_filter($candidates, fn($c) => $c['birthday_payer_pending'] == 1);
    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
        ];
    }

    // 🔹 PRIORITÄT 2: Normale Rotation (nach regular_paid_count)
    $min_paid = min(array_column($candidates, 'regular_paid_count'));
    $regular_candidates = array_filter($candidates, fn($c) => $c['regular_paid_count'] == $min_paid);
    usort($regular_candidates, fn($a, $b) => strcmp($a['username'], $b['username']));
    $first = $regular_candidates[0];
    return [
        'username' => $first['username'],
        'is_birthday_payer' => false
    ];
}

function get_next_payer_username($conn, $meeting_id)
{
    $info = get_next_payer_info($conn, $meeting_id);
    return $info ? $info['username'] : null;
}
