<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Add payment gateway column to transactions table
        if (Schema::hasTable('transactions')) {
            Schema::table('transactions', function (Blueprint $table) {
                if (!Schema::hasColumn('transactions', 'payment_gateway')) {
                    $table->string('payment_gateway', 50)->nullable()->after('type')->comment('Payment gateway used: paystack, flutterwave, offline, etc');
                }
                if (!Schema::hasColumn('transactions', 'gateway_reference')) {
                    $table->string('gateway_reference', 255)->nullable()->after('payment_gateway')->comment('Payment gateway transaction reference');
                }
                if (!Schema::hasColumn('transactions', 'gateway_status')) {
                    $table->string('gateway_status', 50)->default('pending')->after('gateway_reference')->comment('Payment status: pending, success, failed, cancelled');
                }
                if (!Schema::hasColumn('transactions', 'gateway_response')) {
                    $table->text('gateway_response')->nullable()->after('gateway_status')->comment('Full response from payment gateway');
                }
                if (!Schema::hasColumn('transactions', 'proof_of_payment')) {
                    $table->string('proof_of_payment', 255)->nullable()->after('gateway_response')->comment('File path for proof of payment upload');
                }
            });
        }

        // Create payment gateway settings table
        if (!Schema::hasTable('payment_gateways')) {
            Schema::create('payment_gateways', function (Blueprint $table) {
                $table->id();
                $table->string('name', 50)->unique()->comment('Gateway identifier: paystack, flutterwave, offline');
                $table->string('display_name', 100)->comment('Display name for frontend');
                $table->boolean('is_active')->default(false)->comment('Enable/disable gateway');
                $table->text('public_key')->nullable()->comment('Public/Publishable key');
                $table->text('secret_key')->nullable()->comment('Secret key (encrypted)');
                $table->string('webhook_url')->nullable()->comment('Webhook URL for this gateway');
                $table->text('settings')->nullable()->comment('JSON settings for additional configurations');
                $table->integer('sort_order')->default(0)->comment('Display order');
                $table->timestamp('created_at')->useCurrent();
                $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
                
                $table->index('is_active');
                $table->index('sort_order');
            });

            // Insert default payment gateways
            DB::table('payment_gateways')->insert([
                [
                    'name' => 'paystack',
                    'display_name' => 'Paystack',
                    'is_active' => false,
                    'public_key' => '',
                    'secret_key' => '',
                    'webhook_url' => url('/api/webhook/paystack'),
                    'settings' => json_encode([
                        'test_mode' => true,
                        'supported_currencies' => ['NGN', 'USD', 'GHS', 'ZAR', 'KES'],
                        'logo' => 'paystack-logo.png'
                    ]),
                    'sort_order' => 1,
                    'created_at' => now(),
                    'updated_at' => now()
                ],
                [
                    'name' => 'flutterwave',
                    'display_name' => 'Flutterwave',
                    'is_active' => false,
                    'public_key' => '',
                    'secret_key' => '',
                    'webhook_url' => url('/api/webhook/flutterwave'),
                    'settings' => json_encode([
                        'test_mode' => true,
                        'supported_currencies' => ['NGN', 'USD', 'GHS', 'ZAR', 'KES', 'UGX', 'TZS'],
                        'logo' => 'flutterwave-logo.png'
                    ]),
                    'sort_order' => 2,
                    'created_at' => now(),
                    'updated_at' => now()
                ],
                [
                    'name' => 'offline',
                    'display_name' => 'Offline Payment',
                    'is_active' => true,
                    'public_key' => null,
                    'secret_key' => null,
                    'webhook_url' => null,
                    'settings' => json_encode([
                        'instructions' => 'Please contact admin for payment instructions',
                        'bank_details' => 'Bank: [Your Bank]\nAccount: [Your Account]\nAccount Name: [Your Name]',
                        'requires_approval' => true,
                        'logo' => 'offline-payment.png'
                    ]),
                    'sort_order' => 3,
                    'created_at' => now(),
                    'updated_at' => now()
                ]
            ]);
        }

        // Create payment logs table for debugging
        if (!Schema::hasTable('payment_logs')) {
            Schema::create('payment_logs', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('transaction_id')->nullable();
                $table->string('gateway', 50);
                $table->string('event_type', 50)->comment('webhook, api_call, error, etc');
                $table->text('request_data')->nullable();
                $table->text('response_data')->nullable();
                $table->string('status', 50);
                $table->string('ip_address', 45)->nullable();
                $table->timestamp('created_at')->useCurrent();
                
                $table->index('transaction_id');
                $table->index('gateway');
                $table->index('event_type');
                $table->index('created_at');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Remove columns from transactions table
        if (Schema::hasTable('transactions')) {
            Schema::table('transactions', function (Blueprint $table) {
                $table->dropColumn(['payment_gateway', 'gateway_reference', 'gateway_status', 'gateway_response']);
            });
        }

        // Drop tables
        Schema::dropIfExists('payment_logs');
        Schema::dropIfExists('payment_gateways');
    }
};
