<?php

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

return new class extends Migration
{
    public function up(): void
    {
        foreach (['hr_allowance_types', 'hr_deduction_types'] as $name) {
            Schema::create($name, function (Blueprint $table): void {
                $table->id();
                $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
                $table->string('code', 50);
                $table->string('name');
                $table->enum('calculation_type', ['fixed', 'percentage'])->default('fixed');
                $table->decimal('default_amount', 14, 2)->default(0);
                $table->boolean('is_recurring')->default(true);
                $table->boolean('is_taxable')->default(false);
                $table->boolean('is_active')->default(true);
                $table->timestamps();
                $table->unique(['tenant_id', 'code']);
            });
        }

        Schema::create('hr_employee_compensation_items', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('employee_id')->constrained('employees')->cascadeOnDelete();
            $table->enum('item_type', ['allowance', 'deduction']);
            $table->unsignedBigInteger('type_id');
            $table->decimal('amount', 14, 2)->nullable();
            $table->decimal('percentage', 7, 4)->nullable();
            $table->date('effective_from');
            $table->date('effective_to')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->index(['tenant_id', 'employee_id', 'item_type', 'is_active'], 'hr_comp_items_active_idx');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('hr_employee_compensation_items');
        Schema::dropIfExists('hr_deduction_types');
        Schema::dropIfExists('hr_allowance_types');
    }
};
