<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\KeyModel;
use App\Models\SystemModel;

class QueryController extends Controller
{
    public function index(): void
    {
        $this->renderPage();
    }

    public function queryPost(): void
    {
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('query-key');
        }

        $rate = app_rate_limit_consume('web_query_key', 20, 300, app_client_ip());
        if (!empty($rate['limited'])) {
            flash('error', app_zh('查询请求过于频繁，请稍后再试'));
            redirect('query-key');
        }

        $input = app_request_data();
        $userKey = app_clean_text((string)($input['user_key'] ?? ''));
        if ($userKey === '') {
            flash('query_key', $userKey);
            flash('error', app_zh('请输入需要查询的卡密'));
            redirect('query-key');
        }

        $result = $this->buildResult($userKey);
        if (!$result) {
            flash('query_key', $userKey);
            flash('error', app_zh('未找到该卡密，请核对后重试'));
            redirect('query-key');
        }

        flash('query_result', $result);
        flash('query_key', $userKey);
        redirect('query-key');
    }

    public function unbindPost(): void
    {
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('query-key');
        }

        $rate = app_rate_limit_consume('web_query_unbind', 5, 600, app_client_ip());
        if (!empty($rate['limited'])) {
            flash('error', app_zh('解绑请求过于频繁，请稍后再试'));
            redirect('query-key');
        }

        $input = app_request_data();
        $userKey = app_clean_text((string)($input['user_key'] ?? ''));
        if ($userKey === '') {
            flash('error', app_zh('参数错误'));
            redirect('query-key');
        }

        $system = (new SystemModel())->get();
        if (empty($system['allow_self_unbind'])) {
            flash('error', app_zh('当前站点未开启自助解绑'));
            redirect('query-key');
        }

        $model = new KeyModel();
        $key = $model->findByUserKey($userKey);
        if (!$key) {
            flash('error', app_zh('未找到该卡密'));
            redirect('query-key');
        }

        $model->update((int)$key['id'], ['devices' => null]);
        flash('success', app_zh('设备解绑成功'));

        $result = $this->buildResult($userKey);
        if ($result) {
            flash('query_result', $result);
            flash('query_key', $userKey);
        }
        redirect('query-key');
    }

    private function renderPage(): void
    {
        $queryKey = (string)(flash('query_key') ?? '');
        $result = flash('query_result');
        if (!is_array($result)) {
            $result = null;
        }

        view('query/index', [
            'layout' => 'query',
            'title' => app_zh('卡密查询'),
            'query_key' => $queryKey,
            'result' => $result,
        ]);
    }

    private function buildResult(string $userKey): ?array
    {
        $model = new KeyModel();
        $key = $model->findByUserKey($userKey);
        if (!$key) {
            return null;
        }

        $system = (new SystemModel())->get();
        $devices = app_normalize_device_list((string)($key['devices'] ?? ''));
        $activated = !empty($key['expired_at']);

        return [
            'game' => (string)($key['game'] ?? ''),
            'user_key' => (string)($key['user_key'] ?? ''),
            'status' => (string)($key['status'] ?? ''),
            'activated' => $activated,
            'expired_at' => (string)($key['expired_at'] ?? ''),
            'devices_count' => count($devices),
            'devices' => $devices,
            'max_devices' => (int)($key['max_devices'] ?? 0),
            'allow_self_unbind' => !empty($system['allow_self_unbind']),
        ];
    }
}
