<?php

namespace Modules\VetClinic\Entities;

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

/**
 * Vet-side wrapper for an ERP quotation row. Owns the approval token, the
 * owner-side signature, and the back-reference to the converted invoice.
 */
class VcQuotationMeta extends Model
{
    protected $table = 'vc_quotation_meta';
    protected $guarded = ['id'];

    protected $casts = [
        'sent_at'     => 'datetime',
        'viewed_at'   => 'datetime',
        'approved_at' => 'datetime',
        'rejected_at' => 'datetime',
        'expires_at'  => 'date',
    ];

    public function transaction()
    {
        return $this->belongsTo(Transaction::class, 'transaction_id');
    }

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

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

    public function getSignatureUrlAttribute(): ?string
    {
        return $this->approval_signature_path
            ? Storage::disk('public')->url($this->approval_signature_path)
            : null;
    }

    public function getIsApprovedAttribute(): bool
    {
        return $this->status === 'approved';
    }

    public function getIsActionableAttribute(): bool
    {
        return in_array($this->status, ['draft', 'sent', 'viewed'], true)
            && (!$this->expires_at || !$this->expires_at->isPast());
    }

    /** Generate (and persist) a new random approval token. */
    public function regenerateToken(): string
    {
        $this->approval_token = bin2hex(random_bytes(24)); // 48 hex chars
        $this->save();
        return $this->approval_token;
    }

    public static function forTransaction(int $transactionId): ?self
    {
        return self::where('transaction_id', $transactionId)->first();
    }
}
