<?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('stock_ledgers', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('igp_id')->nullable();
            $table->unsignedBigInteger('qc_id')->nullable();
            $table->unsignedBigInteger('po_id')->nullable();
            $table->unsignedBigInteger('item_id');
            $table->decimal('quantity', 10, 2);
            $table->unsignedBigInteger('warehouse_id')->nullable();
            $table->unsignedBigInteger('bin_id')->nullable();
            $table->text('remarks')->nullable();
            $table->timestamp('timestamp')->useCurrent();
            $table->timestamps();

            $table->foreign('igp_id')->references('id')->on('gate_passes')->onDelete('set null');
            $table->foreign('qc_id')->references('id')->on('qcs')->onDelete('set null');
            $table->foreign('po_id')->references('id')->on('purchase_orders')->onDelete('set null');
            $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
            $table->foreign('warehouse_id')->references('id')->on('warehouses')->onDelete('set null');
            $table->foreign('bin_id')->references('id')->on('warehouse_bins')->onDelete('set null');

            $table->index(['igp_id', 'qc_id', 'po_id']);
            $table->index(['item_id', 'warehouse_id', 'bin_id']);
            $table->index('timestamp');
        });
    }

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