<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Account\UserBlacklist;
use App\Models\AccountsInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BlacklistController extends Controller
{
    public function index(Request $request)
    {
        $query = UserBlacklist::query()->with('accountsInfo', 'admin');
        if ($request->input('UserID')) {
            $query->where('UserID', $request->input('UserID'));
        }
        $list = $query->paginate(20);

        return view('admin.blacklist.index', [
            'list' => $list,
            'request' => $request,
        ]);
    }

    public function config($id, Request $request)
    {
        $blacklist = UserBlacklist::findOrFail($id);
        if ($request->method() == 'GET') {
            return view('admin.blacklist.config', [
                'blacklist' => $blacklist,
            ]);
        }
        $validator = Validator::make($request->all(), [
            'SameIP' => 'required|in:0,1',
        ]);
        $blacklist->SameIP = $request->input('SameIP', 0);
        $blacklist->save();

        return apiReturnSuc();
    }

    public function add($UserID)
    {
        $exists = UserBlacklist::find($UserID);
        if ($exists) {
            return apiReturnFail(__('messages.admin.blacklist.user_in_blacklist'));
        }
        $accountInfo = AccountsInfo::where('UserID', $UserID)->first();
        $blacklist = new UserBlacklist();
        $blacklist->UserID = $UserID;
        $blacklist->GameID = $accountInfo->GameID;
        /** @var mixed $admin */
        $admin = session('admin');
        $blacklist->AdminID = $admin->id;
        $blacklist->save();

        return apiReturnSuc();
    }

    public function remove($UserID)
    {
        $exists = UserBlacklist::where('UserID', $UserID)->first();
        if (!$exists) {
            return apiReturnFail(__('messages.admin.blacklist.user_not_in_blacklist'));
        }
        $exists->IsDel = 1;
        $exists->save();
        return apiReturnSuc();
    }

    public function history(Request $request)
    {
        $query = UserBlacklist::query();
        $query->withoutGlobalScope('soft_delete')->where('IsDel', 1);

        $list = $query->orderBy('ID', 'desc')
                    ->paginate(20);

        return view('admin.blacklist.history', [
            'list' => $list,
            'request' => $request
        ]);
    }
}
