<?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('invoices', function (Blueprint $table) {
            $table->id();
            $table->string('number', 50)->nullable()->unique();
            $table->foreignId('project_id')->nullable()->constrained('projects')->nullOnDelete();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); // issuer or main recipient
            $table->string('type', 30); // income, expense
            $table->string('status', 30)->default('draft'); // draft, pending, paid, unpaid, approved, rejected, needs_edit
            $table->decimal('total', 19, 0)->default(0);
            $table->date('issued_at')->nullable();
            $table->date('due_at')->nullable();
            $table->text('description')->nullable();
            $table->json('meta')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        Schema::create('invoice_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('invoice_id')->constrained('invoices')->cascadeOnDelete();
            $table->string('name');
            $table->string('category', 100)->nullable();
            $table->string('subcategory', 100)->nullable();
            $table->decimal('quantity', 15, 3)->default(1);
            $table->string('unit', 50)->nullable();
            $table->decimal('unit_price', 19, 0)->default(0);
            $table->decimal('total', 19, 0)->default(0);
            $table->text('description')->nullable();
            $table->json('attachments')->nullable();
            $table->timestamps();
        });

        Schema::table('wallet_transactions', function (Blueprint $table) {
            $table->foreignId('invoice_id')->nullable()->after('project_id')->constrained('invoices')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('wallet_transactions', function (Blueprint $table) {
            $table->dropForeign(['invoice_id']);
        });
        Schema::dropIfExists('invoice_items');
        Schema::dropIfExists('invoices');
    }
};
