<?php

namespace App\Models;

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

class NotificationTemplate extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'name',
        'category',
        'description',
        'email_subject',
        'email_body',
        'email_enabled',
        'sms_body',
        'sms_enabled',
        'push_title',
        'push_body',
        'push_enabled',
        'available_variables',
        'is_active',
    ];

    protected $casts = [
        'email_enabled' => 'boolean',
        'sms_enabled' => 'boolean',
        'push_enabled' => 'boolean',
        'available_variables' => 'array',
        'is_active' => 'boolean',
    ];

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

    /**
     * Scope for specific category
     */
    public function scopeOfCategory($query, string $category)
    {
        return $query->where('category', $category);
    }

    /**
     * Render template with variables
     */
    public function render(string $type, array $variables): string
    {
        $template = match ($type) {
            'email_subject' => $this->email_subject,
            'email_body' => $this->email_body,
            'sms_body' => $this->sms_body,
            'push_title' => $this->push_title,
            'push_body' => $this->push_body,
            default => '',
        };

        if (!$template) {
            return '';
        }

        foreach ($variables as $key => $value) {
            $template = str_replace('{{' . $key . '}}', $value, $template);
        }

        return $template;
    }

    /**
     * Check if template is enabled for a specific channel
     */
    public function isEnabledFor(string $channel): bool
    {
        return match ($channel) {
            'email' => $this->email_enabled,
            'sms' => $this->sms_enabled,
            'push' => $this->push_enabled,
            default => false,
        };
    }
}
