<?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
    {
        Schema::create('petty_cash_transactions', function (Blueprint $table) {
            $table->id();
            $table->string('transaction_number')->unique();
            $table->date('transaction_date');
            $table->enum('type', ['disbursement', 'return', 'top_up'])->default('disbursement');
            $table->decimal('amount', 15, 2);
            $table->string('given_to')->nullable(); // Person who received the cash
            $table->text('description');
            $table->text('notes')->nullable();
            $table->enum('status', ['pending', 'approved', 'returned', 'cancelled'])->default('pending');
            $table->unsignedBigInteger('returned_from_id')->nullable(); // For returns, link to original transaction
            $table->decimal('returned_amount', 15, 2)->nullable(); // Amount returned
            $table->foreignId('bank_account_id')->nullable()->constrained('bank_accounts')->onDelete('set null'); // For top-ups
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('approved_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index('transaction_date');
            $table->index('type');
            $table->index('status');
        });

        // Add foreign key for self-referencing after table is created
        Schema::table('petty_cash_transactions', function (Blueprint $table) {
            $table->foreign('returned_from_id')->references('id')->on('petty_cash_transactions')->onDelete('set null');
        });
    }

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