<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $programs = $db->select(
        "SELECT p.id FROM sa_programs p
         WHERE EXISTS (SELECT 1 FROM sa_groups g WHERE g.program_id = p.id AND g.is_archived = 0)",
        []
    );

    foreach ($programs as $program) {
        $bestGroup = $db->selectOne(
            "SELECT monthly_fee_member, monthly_fee_nonmember, max_capacity, min_capacity
             FROM sa_groups
             WHERE program_id = ? AND is_archived = 0
             ORDER BY current_count DESC, id DESC
             LIMIT 1",
            [(int) $program['id']]
        );

        if (!$bestGroup) {
            continue;
        }

        $db->update('sa_programs', [
            'monthly_fee_member'    => $bestGroup['monthly_fee_member'] ?? '0.00',
            'monthly_fee_nonmember' => $bestGroup['monthly_fee_nonmember'] ?? '0.00',
            'max_capacity'          => (int) ($bestGroup['max_capacity'] ?? 20),
            'min_capacity'          => (int) ($bestGroup['min_capacity'] ?? 1),
        ], 'id = ?', [(int) $program['id']]);
    }

    // Programs without any groups get sensible defaults
    $db->query(
        "UPDATE sa_programs SET monthly_fee_member = 0.00, monthly_fee_nonmember = 0.00, max_capacity = 20, min_capacity = 1
         WHERE monthly_fee_member IS NULL",
        []
    );
};
