<?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('shipping_orders', function (Blueprint $table) {
            $table->id();
            $table->string('doc_no')->unique()->comment('出貨單號');
            $table->string('customer_name')->nullable()->comment('客戶名稱');
            $table->unsignedBigInteger('warehouse_id')->comment('來源倉庫');
            $table->string('status')->default('draft')->comment('狀態: draft, completed, cancelled');
            $table->date('shipping_date')->comment('出貨日期');
            
            $table->decimal('total_amount', 15, 2)->default(0)->comment('總金額 (不含稅)');
            $table->decimal('tax_amount', 15, 2)->default(0)->comment('稅額');
            $table->decimal('grand_total', 15, 2)->default(0)->comment('總計');
            
            $table->text('remarks')->nullable()->comment('備註');
            
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('posted_by')->nullable();
            $table->timestamp('posted_at')->nullable();
            
            $table->timestamps();
            
            $table->index('warehouse_id');
            $table->index('status');
            $table->index('shipping_date');
        });

        Schema::create('shipping_order_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('shipping_order_id')->constrained('shipping_orders')->onDelete('cascade');
            $table->unsignedBigInteger('product_id')->comment('商品 ID');
            $table->string('batch_number')->nullable()->comment('批號');
            $table->decimal('quantity', 15, 4)->comment('出貨數量');
            $table->decimal('unit_price', 15, 4)->default(0)->comment('單價');
            $table->decimal('subtotal', 15, 2)->default(0)->comment('小計');
            $table->string('remark')->nullable()->comment('項目備註');
            $table->timestamps();

            $table->index('product_id');
        });
    }

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