<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * This is the General Ledger / Transaction table
     * Every financial transaction creates entries here
     */
    public function up(): void
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->date('date');
            $table->foreignId('account_id')->constrained('accounts')->onDelete('restrict');
            $table->foreignId('party_id')->nullable()->constrained('parties')->onDelete('set null');
            
            // Source document reference (polymorphic)
            $table->string('transactionable_type')->nullable(); // Purchase, Sale, Voucher
            $table->unsignedBigInteger('transactionable_id')->nullable();
            
            $table->string('voucher_type', 20); // PUR, SAL, CR, DR, JV, OB (Opening Balance)
            $table->string('voucher_no', 50);
            $table->string('description')->nullable();
            $table->decimal('debit', 15, 2)->default(0);
            $table->decimal('credit', 15, 2)->default(0);
            $table->decimal('balance', 15, 2)->default(0); // Running balance for the account
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            
            $table->index('date');
            $table->index('account_id');
            $table->index('party_id');
            $table->index(['transactionable_type', 'transactionable_id']);
            $table->index('voucher_type');
            $table->index('voucher_no');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('transactions');
    }
};
