<?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;

class MiniPlayerCounter extends Component
{
    public $onlinePlayers = 0;
    public $totalPlayers = 0;
    public $fakeCount = 0;
    public $maxCapacity = 5000;
    public $isLoading = true;

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

    public function updatePlayerCount()
    {
        try {
            // Get settings including max capacity
            $settings = Cache::remember('site_settings', 10, function () {
                return SiteSettings::first();
            });

            // Get max capacity from settings
            if ($settings && isset($settings->settings['sro_max_server'])) {
                $this->maxCapacity = (int) $settings->settings['sro_max_server'];
            }

            // Get online players count with shorter cache for more real-time feel
            $this->onlinePlayers = Cache::remember('online_players_count', 15, function () {
                return _Players::where('cur_status', 1)->count();
            });

            // Get fake count from site settings with much shorter cache (5 seconds for more responsive updates)
            $this->fakeCount = Cache::remember('fake_players_count', 5, function () use ($settings) {
                if (!$settings) {
                    $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);
            $this->totalPlayers = $this->fakeCount;
            $this->maxCapacity = 5000; // fallback capacity
        }
    }

    // Method to force refresh the cache (useful for admin updates)
    public function forceRefresh()
    {
        Cache::forget('fake_players_count');
        Cache::forget('online_players_count');
        Cache::forget('site_settings');
        $this->updatePlayerCount();
    }

    public function getFormattedTotalPlayersProperty()
    {
        return number_format($this->totalPlayers);
    }

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

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