<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (!Schema::hasTable('payment_gateways')) {
            Schema::create('payment_gateways', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('slug')->unique();
                $table->string('api_key')->nullable();
                $table->string('api_secret')->nullable();
                $table->string('webhook_secret')->nullable();
                $table->boolean('is_active')->default(false);
                $table->boolean('is_test_mode')->default(true);
                $table->json('supported_currencies')->nullable();
                $table->json('supported_methods')->nullable();
                $table->decimal('transaction_fee_percent', 5, 2)->default(0);
                $table->decimal('transaction_fee_fixed', 8, 2)->default(0);
                $table->text('description')->nullable();
                $table->integer('sort_order')->default(0);
                $table->timestamps();
                $table->softDeletes();
            });
        }

        // Create payment methods table
        if (!Schema::hasTable('payment_methods')) {
            Schema::create('payment_methods', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('slug')->unique();
                $table->string('gateway_slug');
                $table->string('icon')->nullable();
                $table->boolean('is_active')->default(true);
                $table->integer('sort_order')->default(0);
                $table->timestamps();
                
                $table->foreign('gateway_slug')
                    ->references('slug')
                    ->on('payment_gateways')
                    ->onDelete('cascade');
            });
        }

        // Create transactions table
        if (!Schema::hasTable('transactions')) {
            Schema::create('transactions', function (Blueprint $table) {
                $table->id();
                $table->string('transaction_id')->unique();
                $table->string('order_id')->unique();
                $table->string('gateway_transaction_id')->nullable();
                $table->string('gateway_order_id')->nullable();
                $table->string('gateway_payment_id')->nullable();
                $table->string('gateway_signature')->nullable();
                
                $table->unsignedBigInteger('user_id');
                $table->string('entity_type'); // subscription, ad_package, etc.
                $table->unsignedBigInteger('entity_id');
                
                $table->string('gateway_slug');
                $table->string('payment_method_slug')->nullable();
                
                $table->decimal('amount', 10, 2);
                $table->decimal('currency', 5, 2)->default(0); // Changed default slightly or keep it
                $table->decimal('gateway_fee', 8, 2)->default(0);
                $table->decimal('platform_fee', 8, 2)->default(0);
                
                $table->string('status'); // pending, success, failed, cancelled, refunded
                $table->string('payment_status')->default('pending'); // pending, authorized, captured, failed
                $table->string('refund_status')->default('none'); // none, requested, partial, full
                
                $table->json('gateway_response')->nullable();
                $table->json('metadata')->nullable();
                
                $table->timestamp('paid_at')->nullable();
                $table->timestamp('captured_at')->nullable();
                $table->timestamp('refunded_at')->nullable();
                
                $table->timestamps();
                $table->softDeletes();
                
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->foreign('gateway_slug')->references('slug')->on('payment_gateways')->onDelete('cascade');
                $table->foreign('payment_method_slug')->references('slug')->on('payment_methods')->onDelete('set null');
            });
        }

        // Create subscriptions table
        if (!Schema::hasTable('subscriptions')) {
            Schema::create('subscriptions', function (Blueprint $table) {
                $table->id();
                $table->string('subscription_id')->unique();
                $table->unsignedBigInteger('user_id');
                $table->unsignedBigInteger('plan_id');
                $table->string('gateway_subscription_id')->nullable();
                $table->string('gateway_customer_id')->nullable();
                
                $table->string('gateway_slug');
                $table->string('status'); // active, cancelled, expired, pending
                $table->string('payment_status')->default('pending');
                
                $table->timestamp('start_date');
                $table->timestamp('end_date');
                $table->timestamp('next_billing_date')->nullable();
                $table->timestamp('cancelled_at')->nullable();
                
                $table->integer('billing_cycle_count')->default(0);
                $table->integer('max_billing_cycles')->default(0);
                
                $table->decimal('amount', 10, 2);
                $table->string('currency')->default('INR');
                $table->string('billing_interval'); // day, week, month, year
                $table->integer('billing_frequency')->default(1);
                
                $table->boolean('auto_renew')->default(true);
                $table->boolean('is_trial')->default(false);
                $table->timestamp('trial_ends_at')->nullable();
                
                $table->json('metadata')->nullable();
                $table->timestamps();
                $table->softDeletes();
                
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->foreign('plan_id')->references('id')->on('user_plans')->onDelete('cascade');
                $table->foreign('gateway_slug')->references('slug')->on('payment_gateways')->onDelete('cascade');
            });
        }

        // Create ad packages table
        if (!Schema::hasTable('ad_packages')) {
            Schema::create('ad_packages', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('slug')->unique();
                $table->text('description')->nullable();
                $table->decimal('price', 10, 2);
                $table->string('currency')->default('INR');
                $table->integer('duration_days');
                $table->boolean('free_trial_available')->default(false);
                $table->integer('free_trial_days')->default(0);
                $table->json('features')->nullable();
                $table->boolean('is_active')->default(true);
                $table->integer('sort_order')->default(0);
                $table->timestamps();
                $table->softDeletes();
            });
        }

        // Create ad package purchases table
        Schema::create('ad_package_purchases', function (Blueprint $table) {
            $table->id();
            $table->string('purchase_id')->unique();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('ad_package_id');
            $table->unsignedBigInteger('ad_id');
            $table->string('transaction_id');
            
            $table->string('gateway_purchase_id')->nullable();
            $table->string('gateway_order_id')->nullable();
            
            $table->string('gateway_slug');
            $table->string('status'); // pending, active, expired, cancelled
            
            $table->decimal('amount', 10, 2);
            $table->string('currency')->default('INR');
            $table->decimal('gateway_fee', 8, 2)->default(0);
            
            $table->timestamp('start_date');
            $table->timestamp('end_date');
            
            $table->json('features_applied')->nullable();
            $table->json('metadata')->nullable();
            
            $table->timestamps();
            $table->softDeletes();
            
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('ad_package_id')->references('id')->on('ad_packages')->onDelete('cascade');
            $table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');
            $table->foreign('transaction_id')->references('transaction_id')->on('transactions')->onDelete('cascade');
            $table->foreign('gateway_slug')->references('slug')->on('payment_gateways')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('ad_package_purchases');
        Schema::dropIfExists('subscriptions');
        Schema::dropIfExists('transactions');
        Schema::dropIfExists('payment_methods');
        Schema::dropIfExists('payment_gateways');
        Schema::dropIfExists('ad_packages');
    }
};
