<?php

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

/**
 * Digital signatures captured on an in-clinic touch device for a consent.
 *
 *  - One active row per consent at a time (re-signing supersedes the previous
 *    row by setting `superseded_at`, never deletes — full audit trail).
 *  - `png_hash_sha256` is the tamper-evident anchor; the public verification
 *    URL keys off the first 12 chars of this hash.
 *  - `archived_at` on `vc_consents` provides a soft-lock so signed consents
 *    can be retired without losing the record.
 */
class CreateVcConsentSignaturesTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('vc_consent_signatures')) {
            Schema::create('vc_consent_signatures', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('consent_id')->index();
                $table->string('signed_by_name', 191);
                $table->string('signed_by_relation', 60)->nullable();
                $table->string('png_path', 255);
                $table->char('png_hash_sha256', 64);
                $table->string('ip', 45)->nullable();
                $table->string('user_agent', 255)->nullable();
                $table->timestamp('signed_at')->nullable();
                $table->timestamp('superseded_at')->nullable();
                $table->unsignedInteger('captured_by')->nullable();
                $table->timestamps();

                $table->index('png_hash_sha256');
                $table->index(['consent_id', 'superseded_at']);
            });
        }

        if (Schema::hasTable('vc_consents') && !Schema::hasColumn('vc_consents', 'archived_at')) {
            Schema::table('vc_consents', function (Blueprint $table) {
                $table->timestamp('archived_at')->nullable()->after('signed_uploaded_by');
                $table->unsignedInteger('archived_by')->nullable()->after('archived_at');
            });
        }
    }

    public function down()
    {
        Schema::dropIfExists('vc_consent_signatures');

        if (Schema::hasTable('vc_consents') && Schema::hasColumn('vc_consents', 'archived_at')) {
            Schema::table('vc_consents', function (Blueprint $table) {
                $table->dropColumn(['archived_at', 'archived_by']);
            });
        }
    }
}
