<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;

class VcReminderTemplate extends Model
{
    protected $table = 'vc_reminder_templates';

    protected $fillable = [
        'business_id',
        'type',
        'name',
        'subject',
        'body',
        'is_active',
        'is_system_default',
    ];

    protected $casts = [
        'is_active'          => 'boolean',
        'is_system_default'  => 'boolean',
    ];

    /**
     * Available template variable tokens with descriptions.
     */
    public static function availableVariables(): array
    {
        return [
            '{{owner_name}}'     => 'Pet owner full name',
            '{{pet_name}}'       => 'Pet\'s name',
            '{{pet_species}}'    => 'Pet species (dog, cat, etc.)',
            '{{vaccine_name}}'   => 'Vaccine type name',
            '{{due_date}}'       => 'Scheduled / due date',
            '{{days_until_due}}' => 'Days until due (or days overdue)',
            '{{clinic_name}}'    => 'Clinic / business name',
            '{{clinic_phone}}'   => 'Clinic phone number',
            '{{clinic_email}}'   => 'Clinic email address',
            '{{clinic_address}}' => 'Clinic address',
        ];
    }

    /**
     * Render a template body/subject by substituting variables.
     */
    public static function render(string $text, array $vars): string
    {
        foreach ($vars as $token => $value) {
            $text = str_replace($token, $value ?? '', $text);
        }
        return $text;
    }

    /**
     * Get the active template for a business and type.
     * Falls back to the system default if no business-specific template exists.
     */
    public static function activeFor(int $businessId, string $type): ?self
    {
        return static::where('type', $type)
            ->where('is_active', true)
            ->where(function ($q) use ($businessId) {
                $q->where('business_id', $businessId)
                  ->orWhereNull('business_id');
            })
            ->orderByRaw('business_id IS NULL ASC') // business-specific first
            ->first();
    }
}
