<?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('legal_document_provisions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('document_id');
            $table->unsignedBigInteger('parent_id')->nullable(); // For hierarchical structure
            $table->integer('level')->default(0); // 0=section, 1=subsection, 2=paragraph, 3=subparagraph
            $table->integer('sort_order')->default(0); // For maintaining order
            
            // Element identification
            $table->string('element_type', 50); // section, subsection, paragraph, subparagraph, clause, etc.
            $table->string('element_id')->nullable(); // section number, e.g., "1", "25(1)", "25(1)(a)"
            $table->string('label')->nullable(); // Display label
            
            // Content fields
            $table->string('heading')->nullable(); // Section heading/title
            $table->text('marginal_note')->nullable(); // Marginal notes
            $table->text('content')->nullable(); // Main provision text
            
            // Metadata
            $table->json('attributes')->nullable(); // Store XML attributes as JSON
            $table->timestamps();
            
            // Foreign keys
            $table->foreign('document_id')->references('id')->on('legal_documents')->onDelete('cascade');
            $table->foreign('parent_id')->references('id')->on('legal_document_provisions')->onDelete('cascade');
            
            // Indexes for performance
            $table->index('document_id');
            $table->index('parent_id');
            $table->index('level');
            $table->index('sort_order');
            $table->index('element_type');
            $table->index('element_id');
        });
    }

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