<?php

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

class CreatePatientCustomFieldValuesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('patient_custom_field_values', function (Blueprint $table) {
            $table->id();
            $table->string('patient_id'); // Patient ID reference as string to match patients table
            $table->unsignedBigInteger('field_id'); // Reference to the custom field
            $table->text('value')->nullable(); // The actual value stored as text (can be converted if needed)
            $table->unsignedBigInteger('updated_by'); // User who last updated this value
            $table->timestamps();
            
            // Define foreign keys
            $table->foreign('patient_id')->references('id')->on('patients')->onDelete('cascade');
            $table->foreign('field_id')->references('id')->on('patient_custom_fields')->onDelete('cascade');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
            
            // Create a unique constraint to prevent duplicate entries for the same field/patient
            $table->unique(['patient_id', 'field_id']);
        });
    }

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