<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->string('header_bg_color')->nullable()->after('success_color');
            $table->string('footer_bg_color')->nullable()->after('header_bg_color');
        });

        // Copy existing values
        DB::table('tenants')->update([
            'header_bg_color' => DB::raw('header_footer_bg_color'),
            'footer_bg_color' => DB::raw('header_footer_bg_color'),
        ]);

        // Make columns required and drop old column
        Schema::table('tenants', function (Blueprint $table) {
            $table->string('header_bg_color')->nullable(false)->change();
            $table->string('footer_bg_color')->nullable(false)->change();
            $table->dropColumn('header_footer_bg_color');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->string('header_footer_bg_color')->nullable()->after('success_color');
        });

        // Copy back one of the values (fallback to default color if null)
        DB::table('tenants')->update([
            'header_footer_bg_color' => DB::raw("COALESCE(header_bg_color, footer_bg_color, '#313131')"),
        ]);

        Schema::table('tenants', function (Blueprint $table) {
            $table->string('header_footer_bg_color')->nullable(false)->change();
            $table->dropColumn(['header_bg_color', 'footer_bg_color']);
        });
    }
};
