<?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('inventory_count_docs', function (Blueprint $table) {
            $table->id();
            $table->string('doc_no')->unique(); // 單號
            $table->foreignId('warehouse_id')->constrained('warehouses')->cascadeOnDelete();
            $table->string('status')->default('draft'); // draft, counting, completed, cancelled
            $table->timestamp('snapshot_date')->nullable(); // 快照建立時間
            $table->timestamp('completed_at')->nullable(); // 完成時間
            $table->string('remarks')->nullable();
            
            // 審核/建立資訊
            $table->foreignId('created_by')->constrained('users'); 
            $table->foreignId('updated_by')->nullable()->constrained('users');
            $table->foreignId('completed_by')->nullable()->constrained('users');
            
            $table->timestamps();
        });

        Schema::create('inventory_count_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('count_doc_id')->constrained('inventory_count_docs')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products');
            $table->string('batch_number')->nullable(); // 針對特定批號盤點
            
            $table->decimal('system_qty', 10, 2)->default(0); // 系統帳面數量 (快照當下)
            $table->decimal('counted_qty', 10, 2)->nullable(); // 實盤數量
            $table->decimal('diff_qty', 10, 2)->default(0); // 差異 (實盤 - 系統)
            $table->string('notes')->nullable();
            
            $table->timestamps();
        });
    }

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