<?php

namespace App\Http\Livewire;

use App\Services\PresenceService;
use Livewire\Component;

/**
 * Simplified version of OnlineReactedProfiles for easier debugging
 */
class SimpleOnlineReactedProfiles extends Component
{
    public $profiles = [];
    public $reactionType = 'Bookmark'; // Single reaction type for simplicity
    public $guard = 'web';
    public $refreshInterval = 30;

    public function mount($reactionType = 'Bookmark', $guard = 'web')
    {
        $this->reactionType = $reactionType;
        $this->guard = $guard;
        $this->loadProfiles();
    }

    public function loadProfiles()
    {
        $this->profiles = [];

        // Get current authenticated user
        $authUser = auth($this->guard)->user();

        if (!$authUser) {
            return;
        }

        // Get online users
        try {
            $presenceService = app(PresenceService::class);
            $onlineUsers = $presenceService->getOnlineUsers($this->guard);

            foreach ($onlineUsers as $userData) {
                // Get the actual user model
                $userId = is_array($userData) ? ($userData['id'] ?? null) : ($userData->id ?? null);

                if (!$userId) continue;

                $user = \App\Models\User::find($userId);

                if (!$user) continue;

                // Check if auth user has reacted to this user
                if ($this->hasReaction($authUser, $user)) {
                    $this->profiles[] = [
                        'id' => $user->id,
                        'name' => $user->name,
                        'avatar' => $user->avatar ?? null,
                        'last_seen' => is_array($userData) ?
                            ($userData['last_seen'] ?? now()) : ($userData->last_seen ?? now()),
                    ];
                }
            }
        } catch (\Exception $e) {
            \Log::error('SimpleOnlineReactedProfiles error: ' . $e->getMessage());
        }
    }

    protected function hasReaction($authUser, $targetUser)
    {
        try {
            // Check both users have the required methods
            if (!method_exists($targetUser, 'viaLoveReactant')) {
                return false;
            }

            // Get the reactant facade for the target user
            $reactantFacade = $targetUser->viaLoveReactant();

            // Check if auth user has given the specified reaction
            // This is the correct way - pass the user model directly
            return $reactantFacade->isReactedBy($authUser, $this->reactionType);
        } catch (\Exception $e) {
            \Log::error('Error checking reaction: ' . $e->getMessage());
            return false;
        }
    }

    public function render()
    {
        return view('livewire.simple-online-reacted-profiles');
    }
}

