<?php

namespace Modules\MedNotify\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;

/**
 * The single database-channel notification MedNotify writes for in-app
 * delivery. It lands in the core `notifications` table and is rendered in the
 * existing bell dropdown via DataController::parse_notification() (spec §7).
 *
 * Mirrors Modules\Essentials database notifications (e.g. NewLeaveNotification):
 * via() => ['database'] (+ broadcast when Pusher is on), toArray() carries the
 * rendered message + link, and parse_notification() reads it back.
 */
class MedNotifyNotification extends Notification
{
    use Queueable;

    /** @var array */
    protected $data;

    /**
     * @param array $data ['event_key','subject','body','link','icon_class']
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function via($notifiable): array
    {
        $channels = ['database'];
        if (function_exists('isPusherEnabled') && isPusherEnabled()) {
            $channels[] = 'broadcast';
        }

        return $channels;
    }

    public function toArray($notifiable): array
    {
        return [
            'event_key'  => $this->data['event_key'] ?? '',
            'subject'    => $this->data['subject'] ?? '',
            'body'       => $this->data['body'] ?? '',
            'link'       => $this->data['link'] ?? '',
            'icon_class' => $this->data['icon_class'] ?? 'fas fa-bell bg-blue',
        ];
    }

    public function toBroadcast($notifiable): BroadcastMessage
    {
        return new BroadcastMessage([
            'title' => (string) ($this->data['subject'] ?? __('mednotify::lang.mednotify_module')),
            'body'  => strip_tags((string) ($this->data['body'] ?? '')),
            'link'  => (string) ($this->data['link'] ?? ''),
        ]);
    }
}
