<?php
declare(strict_types=1);

/**
 * Apply the mandated 50% discount to all 2023/2024 subscriptions.
 * Business rule: SUBSCRIPTION_YEAR_ADJUSTMENT_2023 = 50% discount on total (base + dev fee).
 * The rule was created after subscriptions were already generated, so existing records
 * were never updated. This migration retroactively applies the discount.
 *
 * Only updates UNPAID records. Paid records are left as-is (already settled).
 */
return function (\App\Core\Database $db): void {
    $rows = $db->select(
        "SELECT id, base_amount, development_fee, total_amount, discount_amount
         FROM subscriptions
         WHERE financial_year = '2023/2024' AND status IN ('pending', 'overdue')"
    );

    foreach ($rows as $row) {
        $gross = bcadd($row['base_amount'], $row['development_fee'], 2);
        $discount = bcdiv($gross, '2', 2); // 50%
        $newTotal = bcsub($gross, $discount, 2);

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