<?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()
    {
        Schema::table('users', function (Blueprint $table) {
            // Add regular columns first
            $table->string('phone')->nullable()->after('email');
            $table->string('employee_id')->unique()->nullable()->after('phone');
            $table->unsignedBigInteger('supervisor_id')->nullable()->after('employee_id');
            $table->unsignedBigInteger('department_id')->nullable()->after('supervisor_id');
            $table->enum('status', ['active', 'inactive'])->default('active')->after('department_id');
            $table->text('address')->nullable()->after('status');
            $table->date('hire_date')->nullable()->after('address');
            $table->softDeletes();
        });

        // Add foreign key constraints separately
        // This ensures the tables exist before creating constraints
        Schema::table('users', function (Blueprint $table) {
            // Check if users table has the supervisor_id column before adding foreign key
            if (Schema::hasColumn('users', 'supervisor_id')) {
                $table->foreign('supervisor_id')
                    ->references('id')
                    ->on('users')
                    ->onDelete('set null');
            }
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            // Drop foreign keys first
            $table->dropForeign(['supervisor_id']);
            $table->dropForeign(['department_id']);
            
            // Then drop columns
            $table->dropColumn([
                'phone', 
                'employee_id', 
                'supervisor_id', 
                'department_id', 
                'status', 
                'address', 
                'hire_date'
            ]);
            
            $table->dropSoftDeletes();
        });
    }
};