<?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
    {
        // Enhance plans table
        Schema::table('plans', function (Blueprint $table) {
            $table->string('slug')->unique()->after('name');
            $table->text('description')->nullable()->after('slug');
            $table->string('type')->default('paid')->after('description'); // free, paid
            $table->boolean('is_active')->default(true)->after('type');
            $table->integer('trial_days')->default(0)->after('is_active');
            $table->string('currency')->default('INR')->after('price');
            
            // Feature limits
            $table->integer('max_social_accounts')->default(1)->after('features');
            $table->integer('max_campaigns')->default(0)->after('max_social_accounts');
            $table->integer('max_proposals')->default(1)->after('max_campaigns');
            $table->integer('max_content_ideas_per_month')->default(5)->after('max_proposals');
            $table->integer('max_reels_per_month')->default(0)->after('max_content_ideas_per_month');
            $table->integer('max_ad_variants')->default(0)->after('max_reels_per_month');
            $table->boolean('has_ads_manager')->default(false)->after('max_ad_variants');
            $table->boolean('has_analytics')->default(false)->after('has_ads_manager');
            $table->boolean('has_competitor_insights')->default(false)->after('has_analytics');
            $table->boolean('has_localization')->default(false)->after('has_competitor_insights');
            $table->boolean('has_messaging')->default(false)->after('has_localization');
            $table->boolean('has_api_access')->default(false)->after('has_messaging');
            $table->boolean('has_white_label')->default(false)->after('has_api_access');
            $table->boolean('has_priority_support')->default(false)->after('has_white_label');
            
            $table->integer('sort_order')->default(0)->after('has_priority_support');
        });

        // Enhance subscriptions table
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->unsignedBigInteger('plan_id')->nullable()->after('tenant_id');
            $table->string('razorpay_subscription_id')->nullable()->after('plan_id');
            $table->string('razorpay_customer_id')->nullable()->after('razorpay_subscription_id');
            $table->timestamp('trial_ends_at')->nullable()->after('status');
            $table->timestamp('current_period_start')->nullable()->after('trial_ends_at');
            $table->timestamp('current_period_end')->nullable()->after('current_period_start');
            $table->timestamp('cancelled_at')->nullable()->after('current_period_end');
            $table->timestamp('ends_at')->nullable()->after('cancelled_at');
            $table->json('metadata')->nullable()->after('ends_at');
            
            $table->foreign('plan_id')->references('id')->on('plans')->onDelete('set null');
        });

        // Create transactions table for payment tracking
        Schema::create('subscription_transactions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('subscription_id');
            $table->unsignedBigInteger('user_id');
            $table->string('razorpay_payment_id')->nullable();
            $table->string('razorpay_order_id')->nullable();
            $table->string('razorpay_signature')->nullable();
            $table->string('type'); // payment, refund, upgrade, downgrade
            $table->decimal('amount', 10, 2);
            $table->string('currency', 3)->default('INR');
            $table->string('status'); // pending, success, failed, refunded
            $table->text('description')->nullable();
            $table->json('metadata')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->timestamps();
            
            $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->index(['razorpay_payment_id', 'razorpay_order_id']);
        });

        // Create invoices table
        Schema::create('subscription_invoices', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('subscription_id');
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('transaction_id')->nullable();
            $table->string('invoice_number')->unique();
            $table->decimal('subtotal', 10, 2);
            $table->decimal('tax', 10, 2)->default(0);
            $table->decimal('total', 10, 2);
            $table->string('currency', 3)->default('INR');
            $table->string('status'); // draft, paid, void, refunded
            $table->timestamp('issued_at')->nullable();
            $table->timestamp('due_at')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->json('line_items')->nullable();
            $table->timestamps();
            
            $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('transaction_id')->references('id')->on('subscription_transactions')->onDelete('set null');
        });

        // Create feature usage tracking table
        Schema::create('subscription_feature_usage', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('subscription_id');
            $table->unsignedBigInteger('user_id');
            $table->string('feature'); // social_accounts, campaigns, proposals, content_ideas, reels
            $table->integer('used')->default(0);
            $table->integer('limit')->default(0);
            $table->date('period_start');
            $table->date('period_end');
            $table->timestamps();
            
            $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unique(['subscription_id', 'feature', 'period_start']);
        });

        // Create razorpay settings table for Super Admin
        Schema::create('razorpay_settings', function (Blueprint $table) {
            $table->id();
            $table->text('key_id')->nullable(); // encrypted
            $table->text('key_secret')->nullable(); // encrypted
            $table->string('webhook_secret')->nullable();
            $table->boolean('test_mode')->default(true);
            $table->string('currency')->default('INR');
            $table->boolean('is_active')->default(false);
            $table->json('metadata')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('razorpay_settings');
        Schema::dropIfExists('subscription_feature_usage');
        Schema::dropIfExists('subscription_invoices');
        Schema::dropIfExists('subscription_transactions');
        
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropForeign(['plan_id']);
            $table->dropColumn([
                'plan_id',
                'razorpay_subscription_id',
                'razorpay_customer_id',
                'trial_ends_at',
                'current_period_start',
                'current_period_end',
                'cancelled_at',
                'ends_at',
                'metadata'
            ]);
        });
        
        Schema::table('plans', function (Blueprint $table) {
            $table->dropColumn([
                'slug',
                'description',
                'type',
                'is_active',
                'trial_days',
                'currency',
                'max_social_accounts',
                'max_campaigns',
                'max_proposals',
                'max_content_ideas_per_month',
                'max_reels_per_month',
                'max_ad_variants',
                'has_ads_manager',
                'has_analytics',
                'has_competitor_insights',
                'has_localization',
                'has_messaging',
                'has_api_access',
                'has_white_label',
                'has_priority_support',
                'sort_order'
            ]);
        });
    }
};