<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\UpdateAccountAccessRequest;
use App\Services\AzerothCoreAccountService;
use App\Services\InviteCodeService;
use App\Support\WowData;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AccountController extends Controller
{
    public function index(
        Request $request,
        AzerothCoreAccountService $accounts,
        InviteCodeService $inviteCodes,
    ): View
    {
        $search = trim((string) $request->query('search', ''));
        $searchTerm = $search !== '' ? $search : null;
        $activeTab = (string) $request->query('tab', AzerothCoreAccountService::ACCOUNT_TAB_PLAYERS);

        if (! in_array($activeTab, [AzerothCoreAccountService::ACCOUNT_TAB_PLAYERS, AzerothCoreAccountService::ACCOUNT_TAB_BOTS], true)) {
            $activeTab = AzerothCoreAccountService::ACCOUNT_TAB_PLAYERS;
        }

        $accountStats = $accounts->accountTypeStats($searchTerm);

        return view('admin.accounts.index', [
            'accounts' => $accounts->listAccounts($searchTerm, $activeTab),
            'accountStats' => $accountStats,
            'accountTabs' => [
                AzerothCoreAccountService::ACCOUNT_TAB_PLAYERS => [
                    'label' => 'Игроки',
                    'count' => $accountStats[AzerothCoreAccountService::ACCOUNT_TAB_PLAYERS] ?? 0,
                ],
                AzerothCoreAccountService::ACCOUNT_TAB_BOTS => [
                    'label' => 'Боты',
                    'count' => $accountStats[AzerothCoreAccountService::ACCOUNT_TAB_BOTS] ?? 0,
                ],
            ],
            'activeTab' => $activeTab,
            'inviteCodes' => $inviteCodes->latest(),
            'inviteStats' => $inviteCodes->stats(),
            'search' => $search,
            'accessLevels' => WowData::securityLevels(),
        ]);
    }

    public function updateAccess(int $accountId, UpdateAccountAccessRequest $request, AzerothCoreAccountService $accounts): RedirectResponse
    {
        abort_unless($accounts->findUserById($accountId), 404);

        $accounts->updateAccessLevel($accountId, (int) $request->input('gmlevel'));

        return back()->with('status', 'Уровень доступа обновлён.');
    }
}
