<?php

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

return new class extends Migration {
    public function up(): void
    {
        // Make ration_card_id nullable without relying on Doctrine DBAL (raw SQL)
        if (Schema::hasColumn('voters', 'ration_card_id')) {
            // MySQL syntax; adjust if using different DB engine
            DB::statement('ALTER TABLE voters MODIFY ration_card_id BIGINT UNSIGNED NULL');
        }

        Schema::table('voters', function (Blueprint $table) {
            if (!Schema::hasColumn('voters','serial_number')) {
                $table->unsignedInteger('serial_number')->nullable()->after('id');
            }
            if (!Schema::hasColumn('voters','relation_type')) {
                $table->string('relation_type')->nullable()->after('name'); // father|husband|mother|guardian etc
            }
            if (!Schema::hasColumn('voters','relation_name')) {
                $table->string('relation_name')->nullable()->after('relation_type');
            }
            if (!Schema::hasColumn('voters','house_number')) {
                $table->string('house_number')->nullable()->after('relation_name');
            }
            if (!Schema::hasColumn('voters','age')) {
                $table->unsignedSmallInteger('age')->nullable()->after('year_of_birth');
            }
        });
    }

    public function down(): void
    {
        Schema::table('voters', function (Blueprint $table) {
            if (Schema::hasColumn('voters','serial_number')) { $table->dropColumn('serial_number'); }
            if (Schema::hasColumn('voters','relation_type')) { $table->dropColumn('relation_type'); }
            if (Schema::hasColumn('voters','relation_name')) { $table->dropColumn('relation_name'); }
            if (Schema::hasColumn('voters','house_number')) { $table->dropColumn('house_number'); }
            if (Schema::hasColumn('voters','age')) { $table->dropColumn('age'); }
            // Not reverting ration_card_id to not nullable automatically.
        });
    }
};
