<?php

namespace App\Notifications;

use App\Http\Repository\UtilityRepository;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;

class ServiceBookingNotification extends Notification
{
    use Queueable;
    public $bookingData;
    public $ccRecipients;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($bookingData, $ccRecipients = [])
    {
        $this->bookingData = $bookingData;
        $this->ccRecipients = $ccRecipients;
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        try {
            $mailMessage = (new MailMessage)
                ->subject($this->bookingData['message_subject'])
                ->view($this->bookingData['view'], ['bookingData' => $this->bookingData]);

            // Add CC recipients
            foreach ($this->ccRecipients as $ccRecipient) {
                $mailMessage->cc($ccRecipient);
            }
    
            // Log successful email creation (before sending)
            Log::info('Email created successfully for booking.', [
                'bookingData' => $this->bookingData,
                'notifiable' => $notifiable
            ]);
    
            return $mailMessage;
    
        } catch (Exception $e) {
            // Log any exceptions that occur during email creation
            Log::error('Failed to create email for booking.', [
                'bookingData' => $this->bookingData,
                'notifiable' => $notifiable,
                'error' => $e->getMessage()
            ]);
    
            throw $e;
        }
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
