<?php

namespace App\Notifications;

use App\Models\Prescription;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class PrescriptionCreatedNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public $prescription;

    /**
     * Create a new notification instance.
     */
    public function __construct(Prescription $prescription)
    {
        $this->prescription = $prescription;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        $channels = ['database'];
        
        // Include mail channel - errors will be caught by try-catch in controllers
        // For development, set MAIL_MAILER=log in .env to avoid connection errors
        $channels[] = 'mail';
        
        return $channels;
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $role = $notifiable->role;
        $greeting = $role === 'admin' ? 'Hello Admin,' : 'Hello ' . ($notifiable->pharmacist ? $notifiable->pharmacist->first_name : $notifiable->name) . ',';

        return (new MailMessage)
            ->subject('New Prescription Created - ' . config('app.name'))
            ->greeting($greeting)
            ->line('A new prescription has been created.')
            ->line('**Prescription Number:** ' . $this->prescription->prescription_number)
            ->line('**Patient:** ' . $this->prescription->patient->full_name)
            ->line('**Doctor:** ' . $this->prescription->doctor->full_name)
            ->line('**Date:** ' . $this->prescription->created_at->format('F d, Y'))
            ->action('View Prescription', route('prescriptions.show', $this->prescription->id))
            ->line('Thank you for using ' . config('app.name') . '!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'prescription_id' => $this->prescription->id,
            'prescription_number' => $this->prescription->prescription_number,
            'patient_name' => $this->prescription->patient->full_name,
            'doctor_name' => $this->prescription->doctor->full_name,
            'message' => 'New prescription created for ' . $this->prescription->patient->full_name,
            'type' => 'prescription_created',
        ];
    }
}
