<?php

namespace App\Listeners\Auth;

use App\Events\Auth\RegisteredByAdmin;
use App\Notifications\Auth\CredentialsGenerated; // Import the new notification
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log; // Optional: for logging

class SendAdminCreatedVerificationNotification // implements ShouldQueue
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\Auth\RegisteredByAdmin  $event
     * @return void
     */
    public function handle(RegisteredByAdmin $event)
    {
        $profile = $event->profile;

    // --- 1. Handle Email Verification  ---
    // Add check: Only send if it's a User model instance, as other models receive a verification email when switching their profile
    if ($profile instanceof \App\Models\User && $profile instanceof MustVerifyEmail && ! $profile->hasVerifiedEmail()) {
        try {
            $profile->sendEmailVerificationNotification();
            Log::info('Verification email sent to profile ID: ' . $profile->id); // Optional logging
        } catch (\Exception $e) {
            Log::error('Failed to send verification email to profile ID: ' . $profile->id . ' Error: ' . $e->getMessage());
        }
    }

        // --- 2. Handle Generated Password Notification ---
        // Check if a plain password was passed in the event
        // This now works for both generated and manually entered passwords
        if (!empty($event->plainPassword)) {
            try {
                // Send the CredentialsGenerated notification to the profile
                $profile->notify(new CredentialsGenerated($event->plainPassword));
                Log::info('Generated credentials email sent to profile ID: ' . $profile->id);
            } catch (\Exception $e) {
                Log::error('Failed to send generated credentials email to profile ID: ' . $profile->id . ' Error: ' . $e->getMessage());
            }
        } else {
            // Optional: Log if no password was provided (e.g., creating non-user profile)
            Log::info('No plain password provided in RegisteredByAdmin event for profile ID: ' . $profile->id . '. Skipping credentials email.');
        }

    }
}
