<?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('hr_loans', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('employee_id')->constrained('employees')->cascadeOnDelete();
            $table->enum('type', ['loan', 'advance']);
            $table->decimal('amount', 14, 2);
            $table->decimal('interest_rate', 7, 4)->default(0);
            $table->unsignedInteger('installment_count');
            $table->decimal('installment_amount', 14, 2);
            $table->date('start_date');
            $table->enum('status', ['draft', 'submitted', 'approved', 'active', 'partially_paid', 'settled', 'rejected', 'cancelled'])->default('draft');
            $table->decimal('remaining_balance', 14, 2);
            $table->text('reason')->nullable();
            $table->text('notes')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('approved_at')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->index(['tenant_id', 'employee_id', 'status']);
        });

        Schema::create('hr_loan_installments', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('loan_id')->constrained('hr_loans')->cascadeOnDelete();
            $table->date('due_date');
            $table->decimal('amount', 14, 2);
            $table->decimal('paid_amount', 14, 2)->default(0);
            $table->enum('status', ['pending', 'paid', 'skipped'])->default('pending');
            $table->foreignId('payroll_period_id')->nullable()->constrained('payroll_periods')->nullOnDelete();
            $table->timestamps();
            $table->unique(['loan_id', 'due_date']);
        });
    }

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