<?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('multiple_tables', function (Blueprint $table) {
            $tables = ['answers', 'assessments', 'companies', 'products', 'questions', 'question_groups'];
            foreach ($tables as $table) {
                Schema::table($table, function (Blueprint $tableBlueprint) use ($table) {
                    if (Schema::hasColumn($table, 'created_at')) {
                        $tableBlueprint->renameColumn('created_at', 'DtmIns');
                    }
                    if (Schema::hasColumn($table, 'updated_at')) {
                        $tableBlueprint->renameColumn('updated_at', 'DtmUpd');
                    }
                });
                // Adjust timestamp behavior via raw SQL
                DB::statement("ALTER TABLE {$table} MODIFY DtmIns TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
                DB::statement("ALTER TABLE {$table} MODIFY DtmUpd TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $tables = ['answers', 'assessments', 'companies', 'products', 'questions', 'question_groups'];

        foreach ($tables as $table) {
            Schema::table($table, function (Blueprint $tableBlueprint) use ($table) {
                if (Schema::hasColumn($table, 'DtmIns')) {
                    $tableBlueprint->renameColumn('DtmIns', 'created_at');
                }
                if (Schema::hasColumn($table, 'DtmUpd')) {
                    $tableBlueprint->renameColumn('DtmUpd', 'updated_at');
                }
            });

            DB::statement("ALTER TABLE {$table} MODIFY created_at TIMESTAMP NULL DEFAULT NULL");
            DB::statement("ALTER TABLE {$table} MODIFY updated_at TIMESTAMP NULL DEFAULT NULL");
        }
    }
};
