<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\SRO_VT_PROXY\_Players;
use App\Models\Z_Website\SiteSettings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class PlayerCounter extends Component
{
    public $onlinePlayers = 0;
    public $totalPlayers = 0;
    public $fakeCount = 0;

    public function mount()
    {
        $this->updatePlayerCount();
    }

    public function updatePlayerCount()
    {
        try {
            // Get online players count with caching for better performance
            $this->onlinePlayers = Cache::remember('online_players_count', 30, function () {
                return _Players::where('cur_status', 1)->count();
            });

            // Get fake count from site settings
            $this->fakeCount = Cache::remember('fake_players_count', 60, function () {
                $settings = SiteSettings::first();
                return $settings ? (int) $settings->fake : 0;
            });

            // Calculate total displayed players
            $this->totalPlayers = $this->onlinePlayers + $this->fakeCount;

        } catch (\Exception $e) {
            // Fallback values if database connection fails
            $this->onlinePlayers = 0;
            $this->fakeCount = rand(50, 150); // Fallback fake count
            $this->totalPlayers = $this->fakeCount;
        }
    }

    public function render()
    {
        return view('livewire.player-counter');
    }

    // Auto-refresh every 30 seconds
    public function getListeners()
    {
        return [
            'refreshPlayerCount' => 'updatePlayerCount',
        ];
    }
}
