<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * Add RON (Romanian Leu) to the supported_currencies list of every
 * gateway that does business in Europe.
 *
 * Why this migration exists: the seeded supported_currencies arrays
 * shipped with hard-coded "popular" currencies and RON was left out.
 * Customers in Romania (and any reseller targeting RO) saw their
 * plans priced in RON disappear from the checkout — the JS filter
 * hid Stripe/PayPal because RON wasn't in the array.
 *
 * We add RON to the EU-relevant gateways only (Stripe, PayPal,
 * Mollie, Braintree, Square, Authorize.Net) — gateways that are
 * region-locked away from Europe (Razorpay-IN, Paystack-NG,
 * Flutterwave-AF) are untouched because they actually don't
 * support RON.
 *
 * Idempotent: re-running this migration is a no-op once RON is
 * already in the array.
 */
return new class extends Migration {
    /** Gateways that legitimately accept RON. */
    private const EU_GATEWAYS = [
        'stripe', 'paypal', 'mollie', 'braintree', 'square',
        'authorize_net', 'paddle', 'iyzico', 'fondy',
    ];

    public function up(): void
    {
        foreach (self::EU_GATEWAYS as $slug) {
            $row = DB::table('payment_gateways')->where('slug', $slug)->first();
            if (!$row) continue;

            $list = json_decode((string) $row->supported_currencies, true);
            if (!is_array($list)) $list = [];

            if (!in_array('RON', $list, true)) {
                $list[] = 'RON';
                DB::table('payment_gateways')
                    ->where('id', $row->id)
                    ->update(['supported_currencies' => json_encode($list)]);
            }
        }
    }

    public function down(): void
    {
        foreach (self::EU_GATEWAYS as $slug) {
            $row = DB::table('payment_gateways')->where('slug', $slug)->first();
            if (!$row) continue;

            $list = json_decode((string) $row->supported_currencies, true);
            if (!is_array($list)) continue;

            $filtered = array_values(array_filter($list, fn ($c) => $c !== 'RON'));
            DB::table('payment_gateways')
                ->where('id', $row->id)
                ->update(['supported_currencies' => json_encode($filtered)]);
        }
    }
};
