<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Schema optimization - remove deprecated columns
     */
    public function up(): void
    {
        if (Schema::hasTable('activity_records')) {
            try {
                DB::statement('ALTER TABLE `activity_records` DROP INDEX `activity_records_is_backdate_index`');
            } catch (\Exception $e) {
                // Index may not exist
            }

            Schema::table('activity_records', function (Blueprint $table) {
                if (Schema::hasColumn('activity_records', 'is_backdate')) {
                    $table->dropColumn('is_backdate');
                }
                if (Schema::hasColumn('activity_records', 'backdate_days')) {
                    $table->dropColumn('backdate_days');
                }
            });
        }

        if (Schema::hasTable('audit_logs')) {
            try {
                DB::statement('ALTER TABLE `audit_logs` DROP INDEX `audit_logs_is_backdate_index`');
            } catch (\Exception $e) {
                // Index may not exist
            }

            Schema::table('audit_logs', function (Blueprint $table) {
                if (Schema::hasColumn('audit_logs', 'is_backdate')) {
                    $table->dropColumn('is_backdate');
                }
                if (Schema::hasColumn('audit_logs', 'backdate_days')) {
                    $table->dropColumn('backdate_days');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (Schema::hasTable('activity_records')) {
            Schema::table('activity_records', function (Blueprint $table) {
                if (!Schema::hasColumn('activity_records', 'is_backdate')) {
                    $table->boolean('is_backdate')->default(false);
                }
                if (!Schema::hasColumn('activity_records', 'backdate_days')) {
                    $table->integer('backdate_days')->nullable();
                }
            });

            Schema::table('activity_records', function (Blueprint $table) {
                $table->index('is_backdate');
            });
        }

        if (Schema::hasTable('audit_logs')) {
            Schema::table('audit_logs', function (Blueprint $table) {
                if (!Schema::hasColumn('audit_logs', 'is_backdate')) {
                    $table->boolean('is_backdate')->default(false);
                }
                if (!Schema::hasColumn('audit_logs', 'backdate_days')) {
                    $table->integer('backdate_days')->nullable();
                }
            });

            Schema::table('audit_logs', function (Blueprint $table) {
                $table->index('is_backdate');
            });
        }
    }
};
