<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use MtcPharmacy\Subscriptions\Classes\Subscription;

class AddSubscriptionIdFields extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('order', function (Blueprint $table) {
            // First ensure the subscription_id column exists and matches the referenced column type
            if (!Schema::hasColumn('order', 'subscription_id')) {
                $table->unsignedInteger('subscription_id')->nullable()->after('basket_id');

                $table->foreign('subscription_id', 'order__subscription_id')
                    ->references('id')
                    ->on('subscriptions')
                    ->constrained()
                    ->onDelete('set null')
                    ->onUpdate('cascade')
                ;
            }
        });


        Schema::table('basket', function (Blueprint $table) {
            if (!Schema::hasColumn('basket', 'subscription_id')) {
                $table->unsignedInteger('subscription_id')->nullable()->after('id');

                $table->foreign('subscription_id', 'basket__subscription_id')
                    ->references('id')
                    ->on('subscriptions')
                    ->constrained()
                    ->onDelete('set null')
                    ->onUpdate('cascade');
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('basket', function(Blueprint $table) {
            $table->dropForeign('basket__subscription_id');
            $table->dropColumn('subscription_id');
        });

        Schema::table('order', function(Blueprint $table) {
            $table->dropForeign('order__subscription_id');
            $table->dropColumn('subscription_id');
        });
    }
}
