<?php
declare(strict_types=1);

/**
 * Separate development fee from total_amount.
 *
 * Business rule: مصاريف تنمية (35 EGP) is a single flat fee per membership per year,
 * added AFTER all subscription calculations and discounts. It must NOT be part of
 * total_amount (which represents only the subscription charge per person).
 *
 * This migration subtracts development_fee from total_amount for all rows where
 * dev fee was incorrectly embedded. Only affects unpaid rows.
 */
return function (\App\Core\Database $db): void {
    $rows = $db->select(
        "SELECT id, total_amount, development_fee
         FROM subscriptions
         WHERE development_fee > 0 AND status IN ('pending', 'overdue')"
    );

    foreach ($rows as $row) {
        $newTotal = bcsub($row['total_amount'], $row['development_fee'], 2);
        if (bccomp($newTotal, '0', 2) < 0) continue;

        $db->query(
            "UPDATE subscriptions SET total_amount = ?, updated_at = NOW() WHERE id = ?",
            [$newTotal, (int) $row['id']]
        );
    }
};
