<?php

namespace App\Notifications;

use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class EmailUserNotification extends Notification
{
    public string $subjectLine;
    public string $messageBody;
    public string $buttonUrl;
    public array $attachments;

    public function __construct(
        string $subjectLine = 'Notification',
        string $messageBody = 'You have a new message.',
        string $buttonUrl = '',
        array $attachments = []
    ) {
        $this->subjectLine = $subjectLine;
        $this->messageBody = $messageBody;
        $this->buttonUrl = $buttonUrl;
        $this->attachments = $attachments;
    }

    public function via($notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail($notifiable): MailMessage
    {
        $mail = (new MailMessage)
            ->subject($this->subjectLine)
            ->view('emails.emailuser', [
                'subject' => $this->subjectLine,
                'messagebody' => $this->messageBody,
                'buttonurl' => $this->buttonUrl ?: null,
                'supportEmail' => config('mail.from.address'),
                'appName' => config('app.name'),
            ]);

        // Attach files safely
        foreach ($this->attachments as $path) {
            if (Storage::disk('public')->exists($path)) {
                $mail->attach(Storage::disk('public')->path($path));
            }
        }

        return $mail;
    }

    public function toArray($notifiable): array
    {
        // Strip HTML tags
        $cleanMessage = strip_tags($this->messageBody ?: 'You have a new message.');

        // Limit to 50 words
        $limitedMessage = Str::words($cleanMessage, 80, '...');

        return [
            'title' => $this->subjectLine ?: 'Notification',
            'message' => $limitedMessage,
            'link' => $this->buttonUrl ?: null,
            'app_name' => config('app.name'),
            'support_email' => config('mail.from.address'),
        ];
    }
}
