<?php

// 2. Presence Controller for AJAX calls
namespace App\Http\Controllers;

use App\Services\PresenceService;
use Illuminate\Http\Request;

class PresenceController extends Controller
{
    protected $presenceService;

    public function __construct(PresenceService $presenceService)
    {
        $this->presenceService = $presenceService;
    }

    public function heartbeat(Request $request)
    {
        $guard = $request->get('guard', 'web');

        if (auth($guard)->check()) {
            $this->presenceService->updatePresence(auth($guard)->user(), $guard);

            return response()->json([
                'status' => 'online',
                'timestamp' => now(),
                'user_id' => auth($guard)->id()
            ]);
        }

        return response()->json(['status' => 'unauthorized'], 401);
    }

    public function setOffline(Request $request)
    {
        $guard = $request->get('guard', 'web');

        if (auth($guard)->check()) {
            $this->presenceService->setUserOffline(auth($guard)->user(), $guard);

            return response()->json([
                'status' => 'offline',
                'timestamp' => now(),
                'user_id' => auth($guard)->id()
            ]);
        }

        return response()->json(['status' => 'unauthorized'], 401);
    }

    public function getOnlineUsers(Request $request)
    {
        $guard = $request->get('guard', 'web');
        $users = $this->presenceService->getOnlineUsers($guard);

        return response()->json([
            'users' => $users,
            'count' => $users->count(),
            'guard' => $guard,
            'updated_at' => now()
        ]);
    }
}
