<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('mathchapters')) {
            return;
        }

        Schema::table('mathchapters', function (Blueprint $table) {
            if (! Schema::hasColumn('mathchapters', 'subjectid')) {
                $table->unsignedBigInteger('subjectid')->nullable()->after('classgroupname');
            }

            if (! Schema::hasColumn('mathchapters', 'subjectname')) {
                $table->string('subjectname', 250)->nullable()->after('subjectid');
            }
        });

        DB::table('mathchapters')
            ->whereNull('subjectid')
            ->update([
                'subjectid' => 5,
                'subjectname' => 'Maths',
            ]);
    }

    public function down(): void
    {
        if (! Schema::hasTable('mathchapters')) {
            return;
        }

        Schema::table('mathchapters', function (Blueprint $table) {
            if (Schema::hasColumn('mathchapters', 'subjectname')) {
                $table->dropColumn('subjectname');
            }

            if (Schema::hasColumn('mathchapters', 'subjectid')) {
                $table->dropColumn('subjectid');
            }
        });
    }
};
