<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class NotificationTemplate extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'key',
        'message',
        'attachments',
        'inline_keyboard',
        'variables',
        'is_active',
        'description',
    ];

    protected $casts = [
        'attachments' => 'array',
        'inline_keyboard' => 'array',
        'variables' => 'array',
        'is_active' => 'boolean',
    ];

    /**
     * Scope for active templates
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Find template by key
     */
    public function scopeByKey($query, string $key)
    {
        return $query->where('key', $key);
    }

    /**
     * Get template variables
     */
    public function getVariableNames(): array
    {
        return $this->variables ?? [];
    }

    /**
     * Render template with variables
     */
    public function render(array $variables = []): string
    {
        $message = $this->message;

        foreach ($variables as $key => $value) {
            $message = str_replace("{{$key}}", $value, $message);
        }

        return $message;
    }

    /**
     * Extract variables from message text
     */
    public function extractVariables(): array
    {
        preg_match_all('/\{\{(\w+)\}\}/', $this->message, $matches);
        return array_unique($matches[1] ?? []);
    }

    /**
     * Validate template variables
     */
    public function validateVariables(array $variables): array
    {
        $required = $this->getVariableNames();
        $missing = array_diff($required, array_keys($variables));
        
        return [
            'valid' => empty($missing),
            'missing' => $missing,
        ];
    }

    /**
     * Generate unique key from name
     */
    public static function generateKey(string $name): string
    {
        return Str::slug($name, '_');
    }

    /**
     * Boot model events
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($template) {
            if (empty($template->key)) {
                $template->key = self::generateKey($template->name);
            }

            // Extract variables from message
            $template->variables = $template->extractVariables();
        });

        static::updating(function ($template) {
            if ($template->isDirty('message')) {
                $template->variables = $template->extractVariables();
            }
        });
    }
}