<?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_type_rules', function (Blueprint $table) {
            $table->string('accrual_mode', 20)->default('yearly')->after('carry_forward_limit');
            $table->boolean('pro_rata_on_joining')->default(true)->after('accrual_mode');
        });

        Schema::create('leave_balances', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('company_id')->nullable()->index();
            $table->unsignedBigInteger('user_id')->index();
            $table->unsignedBigInteger('leave_type_id')->index();
            $table->unsignedSmallInteger('year')->index();
            $table->decimal('opening_balance', 8, 2)->default(0);
            $table->decimal('allocated', 8, 2)->default(0);
            $table->decimal('accrued', 8, 2)->default(0);
            $table->decimal('carried_forward', 8, 2)->default(0);
            $table->decimal('used', 8, 2)->default(0);
            $table->decimal('pending', 8, 2)->default(0);
            $table->decimal('encashed', 8, 2)->default(0);
            $table->timestamps();

            $table->unique(['company_id', 'user_id', 'leave_type_id', 'year'], 'leave_balances_unique');
        });

        Schema::create('leave_transactions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('company_id')->nullable()->index();
            $table->unsignedBigInteger('user_id')->index();
            $table->unsignedBigInteger('leave_type_id')->index();
            $table->unsignedBigInteger('leave_balance_id')->nullable()->index();
            $table->unsignedBigInteger('leave_id')->nullable()->index();
            $table->string('transaction_type', 30);
            $table->decimal('amount', 8, 2);
            $table->decimal('balance_before', 8, 2)->default(0);
            $table->decimal('balance_after', 8, 2)->default(0);
            $table->unsignedSmallInteger('year');
            $table->date('effective_date');
            $table->text('remarks')->nullable();
            $table->unsignedBigInteger('created_by')->nullable();
            $table->string('reference_key', 120)->nullable()->unique();
            $table->json('meta_json')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('leave_transactions');
        Schema::dropIfExists('leave_balances');

        Schema::table('leave_type_rules', function (Blueprint $table) {
            $table->dropColumn(['accrual_mode', 'pro_rata_on_joining']);
        });
    }
};
