<?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_entries', function (Blueprint $table) {
            $table->id();
            $table->string('reference')->unique();

            // Relations
            $table->foreignId('supplier_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('product_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();

            // NEW: Link to PO + PO Item
            $table->foreignId('purchase_order_id')->nullable()->constrained('purchase_orders')->nullOnDelete();
            $table->foreignId('purchase_order_item_id')->nullable()->constrained('purchase_order_items')->nullOnDelete();

            // Stock
            $table->integer('quantity')->default(0);              // Total added now
            $table->string('unit', 50)->default('pièce');        // Unit of measurement
            $table->integer('remaining_quantity')->default(0);     // Still available from this batch

            // Pricing and Batch Info
            $table->decimal('purchase_price', 10, 2)->nullable();  // Optional override
            $table->string('batch_no')->nullable();
            $table->date('expiry_date')->nullable();

            // Metadata
            $table->string('source_type')->default('purchase'); // purchase, return, transfer, adjustment

            $table->boolean('status')->default(false);
            $table->text('notes')->nullable();

            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->index('reference');
            $table->index(['product_id']);
            $table->index('remaining_quantity');
            $table->index(['product_id', 'remaining_quantity'], 'stock_entries_product_remaining_index');
            $table->index(['expiry_date', 'remaining_quantity'], 'stock_entries_expiry_remaining_index');
        });

    }

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