<?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('goods_receipts', function (Blueprint $table) {
            $table->id();
            $table->string('code')->index(); // GR 單號
            $table->foreignId('warehouse_id')->constrained()->onDelete('restrict');
            $table->foreignId('purchase_order_id')->nullable()->constrained()->onDelete('set null');
            $table->foreignId('vendor_id')->constrained()->onDelete('restrict'); // 關聯到 Inventory 模組內的 Vendor 邏輯或跨模組 ID (此處僅 FK 約束通常指向同一 DB 的 vendors 表)
            $table->date('received_date');
            $table->enum('status', ['draft', 'completed', 'cancelled'])->default('draft');
            $table->text('remarks')->nullable();
            $table->foreignId('user_id')->constrained()->onDelete('restrict'); // 經辦人
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('goods_receipt_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('goods_receipt_id')->constrained()->onDelete('cascade');
            $table->foreignId('product_id')->constrained()->onDelete('restrict');
            $table->foreignId('purchase_order_item_id')->nullable()->constrained()->onDelete('set null'); // 用於回寫 PO Item
            $table->decimal('quantity_received', 10, 2);
            $table->decimal('unit_price', 10, 2); // 暫定價格 (來自 PO)
            $table->decimal('total_amount', 12, 2); // 小計
            $table->string('batch_number')->nullable();
            $table->date('expiry_date')->nullable();
            $table->timestamps();
        });
    }

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