<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * Account Types (Standard Chart of Accounts):
     * - asset: Assets (Cash, Bank, Receivables, Inventory, Fixed Assets)
     * - liability: Liabilities (Payables, Loans, Accrued Expenses)
     * - equity: Equity (Capital, Retained Earnings, Drawings)
     * - income: Income/Revenue (Sales, Service Income, Other Income)
     * - expense: Expenses (Purchases, Salaries, Rent, Utilities)
     */
    public function up(): void
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->id();
            $table->string('code', 20)->unique();
            $table->string('name', 100);
            $table->enum('type', ['asset', 'liability', 'equity', 'income', 'expense']);
            $table->enum('sub_type', [
                // Assets
                'cash', 'bank', 'receivable', 'inventory', 'fixed_asset', 'other_asset',
                // Liabilities
                'payable', 'loan', 'accrued', 'other_liability',
                // Equity
                'capital', 'retained_earnings', 'drawing',
                // Income
                'sales', 'service_income', 'other_income',
                // Expense
                'purchase', 'salary', 'rent', 'utility', 'transport', 'office', 'other_expense'
            ])->nullable();
            $table->foreignId('parent_id')->nullable()->constrained('accounts')->onDelete('set null');
            $table->decimal('opening_balance', 15, 2)->default(0);
            $table->enum('opening_type', ['debit', 'credit'])->default('debit');
            $table->decimal('current_balance', 15, 2)->default(0);
            $table->string('description')->nullable();
            $table->boolean('is_system')->default(false); // System accounts cannot be deleted
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->softDeletes();
            
            $table->index(['type', 'sub_type']);
            $table->index('is_active');
        });
    }

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