<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('companies', function (Blueprint $table) {
            // Add missing columns
            if (!Schema::hasColumn('companies', 'slug')) {
                $table->string('slug')->unique()->after('name_en');
            }

            if (!Schema::hasColumn('companies', 'domain')) {
                $table->string('domain')->nullable()->unique()->after('slug');
            }

            if (!Schema::hasColumn('companies', 'database_prefix')) {
                $table->string('database_prefix', 50)->unique()->after('domain');
            }

            if (!Schema::hasColumn('companies', 'tax_number')) {
                $table->string('tax_number')->nullable()->after('postal_code');
            }

            if (!Schema::hasColumn('companies', 'tax_rate')) {
                $table->decimal('tax_rate', 5, 2)->default(15.00)->after('currency');
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('companies', function (Blueprint $table) {
            // Drop columns if they exist
            $columns = [
                'slug',
                'domain',
                'database_prefix',
                'tax_number',
                'tax_rate'
            ];

            foreach ($columns as $column) {
                if (Schema::hasColumn('companies', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
