<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('reports', function (Blueprint $table) {
            $table->foreignId('project_id')->nullable()->after('user_id')->constrained('projects')->nullOnDelete();
            $table->foreignId('producer_id')->nullable()->after('project_id')->constrained('producers')->nullOnDelete();
            $table->string('workflow_status', 30)->default('pending')->after('status'); // pending, approved, rejected, needs_edit
            $table->text('admin_reason')->nullable()->after('workflow_status'); // دلیل رد یا ویرایش
            $table->string('unit', 50)->nullable()->after('admin_reason'); // kg, m, ...
            $table->string('report_type', 80)->nullable()->after('type'); // وزن‌کشی، رشد، ...
            $table->text('written_report')->nullable()->after('desc');
            $table->json('documents')->nullable()->after('attachments');
        });

        Schema::create('report_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('report_id')->constrained('reports')->cascadeOnDelete();
            $table->foreignId('product_id')->nullable()->constrained('products')->nullOnDelete();
            $table->string('unit', 50)->nullable();
            $table->decimal('min_value', 15, 3)->nullable();
            $table->decimal('max_value', 15, 3)->nullable();
            $table->decimal('value', 15, 3)->nullable(); // مقدار تکی در صورت عدم بازه
            $table->integer('sort_order')->default(0);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('report_items');
        Schema::table('reports', function (Blueprint $table) {
            $table->dropForeign(['project_id']);
            $table->dropForeign(['producer_id']);
            $table->dropColumn([
                'project_id', 'producer_id', 'workflow_status', 'admin_reason',
                'unit', 'report_type', 'written_report', 'documents',
            ]);
        });
    }
};
