<?php

namespace App\Notifications;

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

class AdminActionNotification extends Notification
{
    use Queueable;

    public $actionType;
    public $details;
    public $user;

    /**
     * Create a new notification instance.
     *
     * @param string $actionType
     * @param array $details
     * @param \App\Models\User|null $user
     */
    public function __construct(string $actionType, array $details = [], $user = null)
    {
        $this->actionType = $actionType;
        $this->details = $details;
        $this->user = $user; // can be null
    }

    /**
     * Get the notification's delivery channels.
     */
    public function via($notifiable)
    {
        return ['mail', 'database'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail($notifiable)
    {
        $userName = $this->user ? $this->user->name : 'Guest';
        $subject = "New {$this->actionType} Action";

        return (new MailMessage)
            ->subject($subject)
            ->greeting("Hello Admin,")
            ->line("A new action has been taken on the system.")
            ->line("Action Type: {$this->actionType}")
            ->line("User: {$userName}")
            ->line(new \Illuminate\Support\HtmlString($this->formatDetails()))
            ->action('View Dashboard', route('admin.dashboard'))
            ->line('Thank you for monitoring the system.');
    }

    /**
     * Database representation of the notification.
     */
    public function toDatabase($notifiable)
    {
        $userName = $this->user?->name ?? 'Guest';

        // Create a simple message string for database notifications
        $message = "A new {$this->actionType} action was performed by {$userName}.";

        return [
            'title' => "New {$this->actionType} Action",
            'message' => $message,
            'action_type' => $this->actionType,
            'user_id' => $this->user?->id,
            'user_name' => $userName,
            'details' => $this->details,
        ];
    }

    /**
     * Format the details array into string for email.
     */

    protected function formatDetails(): string
    {
        if (empty($this->details)) {
            return 'No additional details provided.';
        }

        return collect($this->details)
            ->map(function ($value, $key) {
                // If the value is an array (like attachments), convert to clickable links
                if (is_array($value)) {
                    $value = collect($value)
                        ->map(fn($file) => "<a href='" . asset('storage/' . $file) . "' target='_blank'>" . basename($file) . "</a>")
                        ->implode('<br>');
                }

                return "<strong>" . ucfirst($key) . ":</strong> $value";
            })
            ->implode('<br>');
    }


}
