<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Check if gateways already exist before inserting
        $existingGateways = DB::table('payment_gateways')
            ->whereIn('name', ['paypal', 'stripe'])
            ->pluck('name')
            ->toArray();

        $gateways = [];

        // Add PayPal if it doesn't exist
        if (!in_array('paypal', $existingGateways)) {
            $gateways[] = [
                'name' => 'paypal',
                'display_name' => 'PayPal',
                'is_active' => false,
                'public_key' => '',
                'secret_key' => '',
                'webhook_url' => url('/api/webhook/paypal'),
                'settings' => json_encode([
                    'mode' => 'sandbox', // sandbox or live
                    'client_id' => '',
                    'client_secret' => '',
                    'supported_currencies' => ['USD', 'EUR', 'GBP', 'CAD', 'AUD', 'JPY', 'INR', 'NGN'],
                    'logo' => 'paypal-logo.png',
                    'description' => 'Pay securely with PayPal - Credit card, Debit card, or PayPal balance'
                ]),
                'sort_order' => 4,
                'created_at' => now(),
                'updated_at' => now()
            ];
        }

        // Add Stripe if it doesn't exist
        if (!in_array('stripe', $existingGateways)) {
            $gateways[] = [
                'name' => 'stripe',
                'display_name' => 'Stripe',
                'is_active' => false,
                'public_key' => '',
                'secret_key' => '',
                'webhook_url' => url('/api/webhook/stripe'),
                'settings' => json_encode([
                    'test_mode' => true,
                    'publishable_key' => '',
                    'secret_key' => '',
                    'webhook_secret' => '',
                    'supported_currencies' => ['USD', 'EUR', 'GBP', 'CAD', 'AUD', 'JPY', 'INR', 'NGN', 'ZAR', 'KES'],
                    'logo' => 'stripe-logo.png',
                    'description' => 'Pay securely with Stripe - All major credit and debit cards accepted'
                ]),
                'sort_order' => 5,
                'created_at' => now(),
                'updated_at' => now()
            ];
        }

        // Insert new gateways if any
        if (!empty($gateways)) {
            DB::table('payment_gateways')->insert($gateways);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::table('payment_gateways')
            ->whereIn('name', ['paypal', 'stripe'])
            ->delete();
    }
};
