<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class NotificationTemplate extends Model
{
    protected $fillable = [
        'event',
        'title',
        'body',
        'image_url',
        'is_enabled',
    ];

    protected $casts = [
        'is_enabled' => 'boolean',
    ];

    /**
     * Built-in event definitions — label and description for the admin UI.
     */
    public const EVENTS = [
        'user_registered'       => ['label' => 'User Registered',        'desc' => 'Sent when a new user creates an account.'],
        'password_changed'      => ['label' => 'Password Changed',        'desc' => 'Sent when a user changes their password.'],
        'subscription_activated'=> ['label' => 'Subscription Activated',  'desc' => 'Sent when a subscription is activated via any payment method.'],
        'subscription_expiring' => ['label' => 'Subscription Expiring',   'desc' => 'Sent a few days before a subscription expires.'],
        'subscription_expired'  => ['label' => 'Subscription Expired',    'desc' => 'Sent when a subscription has expired.'],
        'grace_period_warning'  => ['label' => 'Grace Period Warning',    'desc' => 'Sent when a subscription enters the grace period.'],
    ];

    /**
     * Available placeholder variables for template bodies.
     */
    public const VARIABLES = [
        '{name}'       => 'User\'s full name',
        '{email}'      => 'User\'s e-mail address',
        '{plan}'       => 'Plan name (Starter / Growth / Pro)',
        '{expires_at}' => 'Subscription expiry date (Y-m-d)',
        '{days}'       => 'Days remaining or in grace period',
    ];

    /**
     * Fetch the template for a given event, or null if none / disabled.
     */
    public static function forEvent(string $event): ?self
    {
        return static::where('event', $event)->where('is_enabled', true)->first();
    }

    /**
     * Render the title and body with real values substituted for placeholders.
     *
     * @param array<string,string> $vars  e.g. ['{name}' => 'Alice', '{plan}' => 'Pro']
     * @return array{title: string, body: string}
     */
    public function render(array $vars): array
    {
        return [
            'title' => str_replace(array_keys($vars), array_values($vars), $this->title),
            'body'  => str_replace(array_keys($vars), array_values($vars), $this->body),
        ];
    }
}
