<?php

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

/**
 * SIFA P3-T3 — sign & lock for the inline SOAP note (spec §7 clinical_notes:
 * signed_by/at, co-sign, lock_after_sign). Additive + nullable so unsigned
 * notes behave exactly as before. When soap_locked is true the SOAP fields
 * render read-only and further edits go through the amendment workflow
 * (clc_note_amendments).
 */
class AddSoapSignLockToClcAppointments extends Migration
{
    public function up()
    {
        Schema::table('clc_appointments', function (Blueprint $table) {
            if (!Schema::hasColumn('clc_appointments', 'soap_signed_by')) {
                $table->unsignedInteger('soap_signed_by')->nullable()->after('soap_plan');   // users.id
            }
            if (!Schema::hasColumn('clc_appointments', 'soap_signed_at')) {
                $table->timestamp('soap_signed_at')->nullable()->after('soap_signed_by');
            }
            if (!Schema::hasColumn('clc_appointments', 'soap_cosigned_by')) {
                $table->unsignedInteger('soap_cosigned_by')->nullable()->after('soap_signed_at'); // users.id
            }
            if (!Schema::hasColumn('clc_appointments', 'soap_cosigned_at')) {
                $table->timestamp('soap_cosigned_at')->nullable()->after('soap_cosigned_by');
            }
            if (!Schema::hasColumn('clc_appointments', 'soap_locked')) {
                $table->boolean('soap_locked')->default(false)->after('soap_cosigned_at');
            }
        });
    }

    public function down()
    {
        foreach (['soap_signed_by', 'soap_signed_at', 'soap_cosigned_by', 'soap_cosigned_at', 'soap_locked'] as $col) {
            if (Schema::hasColumn('clc_appointments', $col)) {
                Schema::table('clc_appointments', function (Blueprint $table) use ($col) {
                    $table->dropColumn($col);
                });
            }
        }
    }
}
