<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

/**
 * One digital signature on a consent. Re-signing creates a new row and stamps
 * `superseded_at` on the previous one — never deletes — so the audit trail is
 * preserved and the hash chain remains verifiable.
 */
class ClcConsentSignature extends Model
{
    protected $table = 'clc_consent_signatures';
    protected $guarded = ['id'];

    protected $casts = [
        'signed_at'     => 'datetime',
        'superseded_at' => 'datetime',
    ];

    public function consent()
    {
        return $this->belongsTo(ClcConsent::class, 'consent_id');
    }

    public function capturedBy()
    {
        return $this->belongsTo(\App\User::class, 'captured_by');
    }

    /** First 12 chars of the SHA-256 hash — what's printed on the consent. */
    public function getShortHashAttribute(): string
    {
        return substr($this->png_hash_sha256, 0, 12);
    }

    /** Public URL of the signature/scan file (PNG, JPG, or PDF). */
    public function getPngUrlAttribute(): ?string
    {
        return $this->png_path
            ? Storage::disk('public')->url($this->png_path)
            : null;
    }

    /** Same file, more honest name (works for canvas + uploaded scans). */
    public function getFileUrlAttribute(): ?string
    {
        return $this->png_url;
    }

    /** True if the stored file is an image (and can be embedded in the printout). */
    public function getIsImageAttribute(): bool
    {
        $mime = $this->file_mime ?: '';
        if (str_starts_with($mime, 'image/')) return true;
        // Canvas-method rows pre-date `file_mime`; they are always PNG.
        return ($this->method ?? 'canvas') === 'canvas';
    }

    /** True if the uploaded scan is a PDF — embed-by-link only. */
    public function getIsPdfAttribute(): bool
    {
        return ($this->file_mime ?: '') === 'application/pdf';
    }

    /** Human label for the method. */
    public function getMethodLabelAttribute(): string
    {
        return ($this->method ?? 'canvas') === 'uploaded_scan'
            ? 'Hand-signed (scanned)'
            : 'Digital (touch device)';
    }

    /** Currently-binding signature for a consent (or null). */
    public static function activeFor(int $consentId): ?self
    {
        return self::where('consent_id', $consentId)
            ->whereNull('superseded_at')
            ->first();
    }
}
