<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Accounts (Bank, Mobile Money, Cash)
        Schema::create('accounts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
            $table->string('name');
            $table->string('type')->default('Bank'); // Bank, Mobile, Cash
            $table->decimal('balance', 15, 2)->default(0);
            $table->string('currency')->default('TZS');
            $table->timestamps();
        });

        // 2. Transaction Categories
        Schema::create('transaction_categories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->nullable()->constrained('organizations')->cascadeOnDelete(); // Nullable for global categories
            $table->string('name');
            $table->string('type'); // Income, Expense
            $table->timestamps();
        });

        // 3. Transactions
        Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
            $table->foreignId('account_id')->constrained('accounts')->cascadeOnDelete();
            $table->foreignId('category_id')->constrained('transaction_categories');
            
            $table->decimal('amount', 15, 2);
            $table->string('type'); // Credit (Income), Debit (Expense)
            $table->string('reference')->nullable();
            $table->text('description')->nullable();
            $table->date('date');
            
            $table->foreignId('recorded_by')->constrained('users');
            
            $table->timestamps();
        });
    }

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