<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Logout;
use Illuminate\Support\Facades\Log;
use App\Models\UserSession;

class LogUserLogout
{
    /**
     * Handle the event.
     */
    public function handle(Logout $event): void
    {
        // Log the logout event
        Log::info('User logged out', [
            'user_id' => $event->user->id,
            'session_id' => session()->getId(),
            'ip' => request()->ip(),
            'user_agent' => request()->userAgent()
        ]);

        // Update user_sessions table for auditing
        $userSession = UserSession::where('user_id', $event->user->id)
            ->where('session_id', session()->getId())
            ->where('status', 'active')
            ->first();

        if ($userSession) {
            $userSession->update([
                'logged_out_at' => now(),
                'status' => 'logged_out',
            ]);
        }
    }
}
