<?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('productions', function (Blueprint $table) {
            $table->id();
            $table->string('batch_no', 50)->unique();
            $table->date('date');
            $table->string('machine', 100)->nullable();
            
            // Raw Material Input
            $table->decimal('raw_material_cost', 15, 2)->default(0);
            
            // Additional Costs
            $table->decimal('agent_commission', 15, 2)->default(0);
            $table->decimal('transportation_cost', 15, 2)->default(0);
            $table->decimal('labor_cost', 15, 2)->default(0);
            $table->decimal('electricity_cost', 15, 2)->default(0);
            $table->decimal('other_expenses', 15, 2)->default(0);
            $table->string('other_expenses_description', 255)->nullable();
            
            // Total Production Cost
            $table->decimal('total_cost', 15, 2)->default(0);
            
            // Output
            $table->decimal('output_quantity', 15, 3)->default(0);
            $table->decimal('wastage_quantity', 15, 3)->default(0);
            $table->decimal('cost_per_unit', 15, 2)->default(0);
            
            $table->text('narration')->nullable();
            $table->enum('status', ['draft', 'completed', 'cancelled'])->default('completed');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            $table->softDeletes();
            
            $table->index('date');
            $table->index('status');
        });
        
        // Production Items (for multiple raw materials input and finished goods output)
        Schema::create('production_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('production_id')->constrained('productions')->onDelete('cascade');
            $table->foreignId('item_id')->constrained('items')->onDelete('restrict');
            $table->enum('type', ['input', 'output', 'wastage']); // input = raw material, output = finished product
            $table->decimal('quantity', 15, 3);
            $table->decimal('rate', 15, 2)->default(0);
            $table->decimal('amount', 15, 2)->default(0);
            $table->timestamps();
            
            $table->index(['production_id', 'type']);
        });
    }

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