<?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::create('employee_ledgers', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('employee_id')->constrained()->onDelete('cascade');

            $table->dateTime('entry_date');

            $table->enum('type', [
                'opening',
                'advance',
                'advance_return',
                'salary_generated',
                'salary_paid',
                'bonus_generated',
                'bonus_paid',
                'bonus',
                'deduction',
                'adjustment'
            ]);

            $table->string('reference_type')->nullable(); // employee_advance, payroll_item, payroll_payment, employee_bonus
            $table->unsignedBigInteger('reference_id')->nullable();

            $table->string('reference_no')->nullable();
            $table->text('description')->nullable();

            // credit = company owes employee
            // debit  = company paid employee / advance / deduction / adjustment
            $table->decimal('debit', 14, 2)->default(0);
            $table->decimal('credit', 14, 2)->default(0);

            $table->decimal('balance', 14, 2)->default(0);

            $table->timestamps();

            $table->index(['user_id', 'employee_id']);
            $table->index(['user_id', 'entry_date']);
            $table->index(['employee_id', 'type']);
            $table->index(['reference_type', 'reference_id']);
        });
    }

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