<?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('supplier_transactions', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('supplier_id')->constrained()->onDelete('cascade');

            // ✅ Transaction number
            $table->string('trx_no',50)->nullable();

            $table->enum('type', ['purchase','payment','adjust']);

            $table->decimal('debit',12,2)->default(0);
            $table->decimal('credit',12,2)->default(0);

            $table->text('note')->nullable();

            $table->string('memo_no')->nullable();
            $table->string('memo_photo')->nullable();
            $table->string('payment_proof_photo')->nullable();

            $table->foreignId('user_account_id')->nullable()
                  ->constrained('user_accounts')->nullOnDelete();

            $table->dateTime('posted_at')->nullable();

            $table->timestamps();

            // indexes
            $table->unique(['user_id','trx_no']); // ✅ user-wise unique
            $table->index(['user_id','supplier_id']);
            $table->index('type');
            $table->index('posted_at');
        });
    }

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