<?php

namespace App\Listeners\Company;

use App\Models\Company;
use App\Models\CompanyUser;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Mail\Company\PusherNotificationMail;
use App\Events\Company\PusherNotificationEvent;

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

    /**
     * Handle the event.
     */
    public function handle(PusherNotificationEvent $event): void
    {
        $notification = (object) $event->notification;

        // Log::info('PusherNotificationEventListener: Handling event', [
        //     'notification' => $notification,
        // ]);

        // {"notification":{"type":"Loan Invoice","company_id":15,"link":"/company/borrow/financials","message":"You have approved an invoice for Employee <b>0016-060925-0001</b> on <b>June 28 2025</b> to <b>June 30 2025</b>. ","is_read":0},"socket":null}}} 
        
        // Send email to a recipient

        if(property_exists($notification, 'company_id') && !empty($notification->company_id)) {
            $company = Company::find($notification->company_id);
            if ($company) {
                $email_address = $company->email_address;

                Mail::to($email_address)->send(new PusherNotificationMail($notification));
            } else {
                Log::error('PusherNotificationEventListener Company not found for ID: ' . $notification->company_id);
                return;
            }
        } else {
            Log::error('PusherNotificationEventListener Company ID is missing in the notification ', [
                'notification' => $notification,
            ]);
            return;
        }
        // Mail::to('recipient@example.com')->send(new PusherNotificationMail($notification));
        // Mail::to($email_address)->send(new \App\Mail\Admin\ResetUserLoginCredentials($user_data));
        
    }
}
