<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('person_id')->constrained('people');
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('employee_number', 20);
            $table->string('department', 30)->nullable();
            $table->string('position', 50)->nullable();
            $table->string('employment_type', 20);
            $table->date('start_date');
            $table->date('end_date')->nullable();
            $table->bigInteger('salary_amount')->nullable();
            $table->string('salary_frequency', 20)->nullable();
            $table->decimal('working_hours_per_week', 4, 1)->nullable();
            $table->foreignId('branch_id')->nullable()->constrained('branches')->nullOnDelete();
            $table->unsignedBigInteger('manager_id')->nullable();
            $table->string('status', 20)->default('active');
            $table->text('termination_reason')->nullable();
            $table->text('notes')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->foreignId('created_by')->constrained('users');
            $table->foreignId('updated_by')->nullable()->constrained('users');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('manager_id')->references('id')->on('employees')->nullOnDelete();
            $table->unique(['academy_id', 'person_id']);
            $table->unique(['academy_id', 'employee_number']);
            $table->index(['academy_id', 'status']);
            $table->index('branch_id');
        });

        DB::statement("ALTER TABLE employees ADD CONSTRAINT employees_employment_type_check CHECK (employment_type IN ('full_time', 'part_time', 'contract', 'intern', 'volunteer'))");
        DB::statement("ALTER TABLE employees ADD CONSTRAINT employees_salary_frequency_check CHECK (salary_frequency IS NULL OR salary_frequency IN ('monthly', 'biweekly', 'weekly', 'daily', 'hourly'))");
        DB::statement("ALTER TABLE employees ADD CONSTRAINT employees_status_check CHECK (status IN ('active', 'on_leave', 'suspended', 'terminated', 'resigned'))");
    }

    public function down(): void
    {
        Schema::dropIfExists('employees');
    }
};
