<?php
declare(strict_types=1);

/**
 * Fix paid subscription rows where development_fee > 0 but paid_amount doesn't include it.
 * Only affects the member row (person_type='member') which carries the dev fee.
 * paid_amount should = total_amount + fine_amount + development_fee when fully paid.
 */
return function (\App\Core\Database $db): void {
    $rows = $db->select(
        "SELECT id, total_amount, fine_amount, paid_amount, development_fee
         FROM subscriptions
         WHERE status = 'paid'
           AND development_fee > 0
           AND paid_amount <= (total_amount + fine_amount)"
    );

    $fixed = 0;
    foreach ($rows as $r) {
        $correctPaid = bcadd(bcadd($r['total_amount'], $r['fine_amount'], 2), $r['development_fee'], 2);
        if (bccomp($correctPaid, $r['paid_amount'], 2) !== 0) {
            $db->query(
                "UPDATE subscriptions SET paid_amount = ?, updated_at = NOW() WHERE id = ?",
                [$correctPaid, (int) $r['id']]
            );
            $fixed++;
        }
    }
};
