<?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('t_stock_movements', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('store_id');
            $table->unsignedBigInteger('raw_material_id');
            $table->enum('movement_type', ['IN', 'OUT', 'ADJUSTMENT', 'OPENING', 'TRANSFER']);
            $table->string('reference_type')->nullable(); // 'SO', 'SPB', 'DO', 'MANUAL', etc.
            $table->unsignedBigInteger('reference_id')->nullable();
            $table->decimal('qty_before', 10, 2)->default(0);
            $table->decimal('qty_movement', 10, 2);
            $table->decimal('qty_after', 10, 2);
            $table->string('uom', 10);
            $table->text('notes')->nullable();
            $table->date('movement_date');
            $table->timestamp('movement_time');
            $table->unsignedBigInteger('created_by');
            $table->boolean('delete_flag')->default(false);
            $table->timestamps();

            $table->foreign('store_id')->references('id')->on('m_stores');
            $table->foreign('raw_material_id')->references('id')->on('m_raw_materials');
            $table->foreign('created_by')->references('id')->on('users');
            
            $table->index(['store_id', 'raw_material_id', 'movement_date']);
            $table->index(['reference_type', 'reference_id']);
        });
    }

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