<?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('bills', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('bill_number')->unique(); // Vendor Invoice Number
            $table->uuid('supplier_id');
            $table->uuid('purchase_order_id')->nullable();
            $table->date('issue_date');
            $table->date('due_date');
            $table->decimal('total_amount', 15, 2)->default(0);
            $table->string('status')->default('DRAFT'); // DRAFT, POSTED, PARTIAL_PAID, PAID, VOID
            $table->text('notes')->nullable();
            $table->uuid('created_by');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('supplier_id')->references('id')->on('suppliers');
            $table->foreign('purchase_order_id')->references('id')->on('purchase_orders');
            $table->foreign('created_by')->references('id')->on('users');
        });

        Schema::create('bill_items', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('bill_id');
            $table->string('description');
            $table->uuid('product_id')->nullable();
            $table->uuid('expense_account_id')->nullable(); // For direct expenses
            $table->integer('quantity')->default(1);
            $table->decimal('unit_price', 15, 2)->default(0);
            $table->decimal('total_price', 15, 2)->default(0);
            $table->timestamps();

            $table->foreign('bill_id')->references('id')->on('bills')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products');
            // expense_account_id FK to chart_of_accounts if we want strictness, usually yes.
             $table->foreign('expense_account_id')->references('id')->on('chart_of_accounts');
        });
    }

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