<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A consent form issued for an appointment. Stores a rendered snapshot of the
 * template body (body_en / body_ar) so later edits to the template — or its
 * deletion — never change a consent that was already issued.
 */
class VcConsent extends Model
{
    protected $table = 'vc_consents';
    protected $guarded = ['id'];

    protected $casts = [
        'issued_at'          => 'datetime',
        'signed_uploaded_at' => 'datetime',
        'archived_at'        => 'datetime',
    ];

    public function template()
    {
        return $this->belongsTo(VcConsentTemplate::class, 'consent_template_id');
    }

    /** All signature events for this consent (including superseded ones, latest first). */
    public function signatures()
    {
        return $this->hasMany(VcConsentSignature::class, 'consent_id')->orderByDesc('signed_at');
    }

    /** Currently-binding signature (the one not superseded). */
    public function activeSignature()
    {
        return $this->hasOne(VcConsentSignature::class, 'consent_id')->whereNull('superseded_at');
    }

    public function getIsDigitallySignedAttribute(): bool
    {
        return $this->activeSignature()->exists();
    }

    public function getIsArchivedAttribute(): bool
    {
        return !empty($this->archived_at);
    }

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

    /** Public URL of the uploaded signed copy, or null. */
    public function getSignedUrlAttribute(): ?string
    {
        return $this->signed_file_path
            ? \Illuminate\Support\Facades\Storage::disk('public')->url($this->signed_file_path)
            : null;
    }

    public function getHasSignedCopyAttribute(): bool
    {
        return !empty($this->signed_file_path);
    }

    public function appointment()
    {
        return $this->belongsTo(VcAppointment::class, 'appointment_id');
    }

    public function pet()
    {
        return $this->belongsTo(VcPet::class, 'pet_id');
    }

    public function owner()
    {
        return $this->belongsTo(\App\Contact::class, 'contact_id');
    }

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