<?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
    {
        Schema::table('leave_types', function (Blueprint $table): void {
            $table->boolean('allow_half_day')->default(false)->after('requires_approval');
            $table->boolean('allow_negative_balance')->default(false)->after('allow_half_day');
            $table->boolean('requires_attachment')->default(false)->after('allow_negative_balance');
        });

        Schema::table('leave_requests', function (Blueprint $table): void {
            $table->boolean('is_half_day')->default(false)->after('total_days');
        });

        Schema::create('leave_balances', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->foreignId('employee_id')->constrained()->cascadeOnDelete();
            $table->foreignId('leave_type_id')->constrained()->cascadeOnDelete();
            $table->unsignedSmallInteger('year');
            $table->decimal('entitled_days', 8, 2)->default(0);
            $table->decimal('used_days', 8, 2)->default(0);
            $table->timestamps();

            $table->unique(['employee_id', 'leave_type_id', 'year'], 'leave_balances_employee_type_year_uq');
        });
    }

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

        Schema::table('leave_requests', function (Blueprint $table): void {
            $table->dropColumn('is_half_day');
        });

        Schema::table('leave_types', function (Blueprint $table): void {
            $table->dropColumn(['allow_half_day', 'allow_negative_balance', 'requires_attachment']);
        });
    }
};
