<?php

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

/**
 * Extend vc_consent_signatures so the "print -> hand-sign on paper -> scan ->
 * upload" path produces the same auditable signature row as the canvas pad.
 *
 *  - method = 'canvas'        : owner signed on an in-clinic touch device.
 *  - method = 'uploaded_scan' : staff uploaded a scanned, paper-signed copy.
 *
 * Either way the hash anchors the row, the consent is locked from delete, and
 * the QR on the printout points to the same /verify-consent/{hash} URL.
 */
class ExtendVcConsentSignaturesForUploads extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('vc_consent_signatures')) return;

        Schema::table('vc_consent_signatures', function (Blueprint $table) {
            if (!Schema::hasColumn('vc_consent_signatures', 'method')) {
                $table->string('method', 20)->default('canvas')->after('consent_id');
            }
            if (!Schema::hasColumn('vc_consent_signatures', 'file_mime')) {
                $table->string('file_mime', 100)->nullable()->after('png_path');
            }
            if (!Schema::hasColumn('vc_consent_signatures', 'file_size')) {
                $table->unsignedInteger('file_size')->nullable()->after('file_mime');
            }
            if (!Schema::hasColumn('vc_consent_signatures', 'original_filename')) {
                $table->string('original_filename', 191)->nullable()->after('file_size');
            }
        });

        // The png_path column was originally NOT NULL but the uploaded-scan
        // path stores a PDF/JPG/PNG just as well; the column now holds the
        // path to whatever file the signature row represents. We don't ALTER
        // the column's NOT NULL constraint because existing rows already have
        // a value and our writer always supplies one.
    }

    public function down()
    {
        if (!Schema::hasTable('vc_consent_signatures')) return;

        Schema::table('vc_consent_signatures', function (Blueprint $table) {
            foreach (['method', 'file_mime', 'file_size', 'original_filename'] as $col) {
                if (Schema::hasColumn('vc_consent_signatures', $col)) {
                    $table->dropColumn($col);
                }
            }
        });
    }
}
