<?php

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class LogSentEmail
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(MessageSent $event): void
    {
        try {
            $message = $event->message;
            
            $recipient = null;
            foreach ($message->getTo() as $address) {
                $recipient = $address->getAddress();
                break; // Log the first recipient for now
            }

            $subject = $message->getSubject();
            
            // Try to identify template slug if passed in headers or context
            // For now, we'll leave it null or try to infer from subject if needed
            $templateSlug = null; 

            \App\Models\EmailLog::create([
                'recipient' => $recipient,
                'subject' => $subject,
                'template_slug' => $templateSlug,
                'status' => 'sent',
                'sent_at' => now(),
            ]);
        } catch (\Exception $e) {
            // Prevent logging failure from stopping the application
            \Illuminate\Support\Facades\Log::error('Failed to log sent email: ' . $e->getMessage());
        }
    }
}
