<?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('intercompany_loans', function (Blueprint $table) {
            $table->id();
            $table->string('loan_number')->unique();
            $table->foreignId('lender_company_id')->constrained('companies')->onDelete('restrict');
            $table->foreignId('borrower_company_id')->constrained('companies')->onDelete('restrict');
            $table->decimal('principal_amount', 15, 2);
            $table->decimal('outstanding_balance', 15, 2);
            $table->decimal('interest_rate', 5, 2);
            $table->enum('interest_type', ['simple', 'compound'])->default('simple');
            $table->date('disbursement_date');
            $table->date('maturity_date');
            $table->integer('term_months');
            $table->enum('payment_frequency', ['monthly', 'quarterly', 'annual', 'bullet'])->default('monthly');
            $table->enum('status', ['pending', 'approved', 'active', 'paid_off', 'defaulted', 'cancelled'])->default('pending');
            $table->text('purpose')->nullable();
            $table->text('terms_conditions')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users');
            $table->timestamp('approved_at')->nullable();
            $table->timestamps();
            $table->softDeletes();
            
            $table->index(['lender_company_id', 'status']);
            $table->index(['borrower_company_id', 'status']);
        });

        Schema::create('loan_repayments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('loan_id')->constrained('intercompany_loans')->onDelete('cascade');
            $table->string('payment_number');
            $table->date('payment_date');
            $table->date('due_date');
            $table->decimal('principal_amount', 15, 2);
            $table->decimal('interest_amount', 15, 2);
            $table->decimal('total_amount', 15, 2);
            $table->enum('status', ['scheduled', 'paid', 'overdue', 'waived'])->default('scheduled');
            $table->foreignId('processed_by')->nullable()->constrained('users');
            $table->timestamp('processed_at')->nullable();
            $table->timestamps();
            
            $table->index(['loan_id', 'status']);
        });
    }

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