<?php
declare(strict_types=1);

/**
 * Fix 2023/2024 discount calculation: مصاريف تنمية (35 EGP) must NOT be
 * included in the discountable base. Discount applies only to base_amount,
 * then dev fee is added as a flat non-discountable surcharge.
 *
 * Correct formula: discount = base_amount × 50%, total = base_amount - discount + dev_fee
 */
return function (\App\Core\Database $db): void {
    $rows = $db->select(
        "SELECT id, base_amount, development_fee
         FROM subscriptions
         WHERE financial_year = '2023/2024' AND status IN ('pending', 'overdue')"
    );

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

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