<?php

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

class CreateSubscriptionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // First, ensure the orders table exists and has necessary columns
        if (!Schema::hasTable('orders')) {
            Schema::create('orders', function (Blueprint $table) {
                $table->id();
                $table->string('order_id')->nullable();
                $table->string('name')->nullable();
                $table->string('email')->nullable();
                $table->string('plan_name')->nullable();
                $table->boolean('is_recurring')->default(false)->nullable();
                $table->unsignedBigInteger('plan_id')->nullable();
                $table->integer('price')->nullable();
                $table->string('price_curency')->nullable();
                $table->string('payment_type')->nullable();
                $table->unsignedBigInteger('txn_id')->nullable();
                $table->integer('payment_status')->nullable();
                $table->string('receipt')->nullable();
                $table->unsignedBigInteger('user_id')->nullable();
                $table->unsignedBigInteger('workspace')->nullable();
                $table->integer('is_refund')->nullable();
                $table->timestamps();
            });
        }
        
        // Add missing columns to orders table if it exists
        Schema::table('orders', function (Blueprint $table) {
            if (!Schema::hasColumn('orders', 'stripe_subscription_id')) {
                $table->string('stripe_subscription_id')->nullable()->after('txn_id');
            }
            if (!Schema::hasColumn('orders', 'stripe_customer_id')) {
                $table->string('stripe_customer_id')->nullable()->after('stripe_subscription_id');
            }
            if (!Schema::hasColumn('orders', 'stripe_price_id')) {
                $table->string('stripe_price_id')->nullable()->after('stripe_customer_id');
            }
            if (!Schema::hasColumn('orders', 'is_recurring') && !Schema::hasColumn('orders', 'plan_id')) {
                $table->boolean('is_recurring')->default(false)->after('plan_id');
            }
            if (!Schema::hasColumn('orders', 'original_price')) {
                $table->decimal('original_price', 10, 2)->nullable()->after('price');
            }
        });

        // Now create the subscriptions table
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->index();
            $table->unsignedBigInteger('order_id')->nullable()->index();
            $table->unsignedBigInteger('plan_id')->index();
            $table->string('name');
            $table->string('stripe_id')->unique();
            $table->string('stripe_status');
            $table->string('stripe_price')->nullable();
            $table->string('stripe_product')->nullable();
            $table->string('stripe_customer')->nullable();
            $table->integer('quantity')->default(1);
            $table->timestamp('trial_ends_at')->nullable();
            $table->timestamp('current_period_start')->nullable();
            $table->timestamp('current_period_end')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->string('interval')->default('month');
            $table->decimal('amount', 10, 2)->default(0);
            $table->string('currency', 3)->default('AUD');
            $table->boolean('is_recurring')->default(true);
            $table->text('metadata')->nullable();
            $table->timestamps();

            // Add foreign keys only if the referenced tables exist
            if (Schema::hasTable('users')) {
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            }
            
            if (Schema::hasTable('plans')) {
                $table->foreign('plan_id')->references('id')->on('plans')->onDelete('cascade');
            }
            
            // Check if orders table has an id column before creating foreign key
            if (Schema::hasTable('orders') && Schema::hasColumn('orders', 'id')) {
                $table->foreign('order_id')->references('id')->on('orders')->onDelete('set null');
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Drop the subscriptions table first
        Schema::dropIfExists('subscriptions');

        // Remove added columns from orders table if it exists
        if (Schema::hasTable('orders')) {
            Schema::table('orders', function (Blueprint $table) {
                $columns = [
                    'stripe_subscription_id',
                    'stripe_customer_id',
                    'stripe_price_id',
                    'original_price'
                ];
                
                foreach ($columns as $column) {
                    if (Schema::hasColumn('orders', $column)) {
                        $table->dropColumn($column);
                    }
                }
            });
        }
    }
}
