<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\HistoryModel;
use App\Models\KeyModel;
use App\Models\ReferralModel;
use App\Models\StatsModel;
use App\Models\UserModel;

class DashboardController extends Controller
{
    public function index(): void
    {
        $this->requireLogin();
        $isAdmin = ($this->user['role'] ?? '') === 'admin';
        $historyModel = new HistoryModel();
        $history = $isAdmin
            ? $historyModel->listLatest(20)
            : $historyModel->listLatestForUser((int)$this->user['id'], 20);
        $keysCount = (new KeyModel())->countForUser((int)$this->user['id'], $isAdmin);
        $statsModel = new StatsModel();
        $stats = $isAdmin
            ? $statsModel->overview()
            : $statsModel->overviewForUser((int)$this->user['id']);

        view('dashboard/index', [
            'title' => app_zh('控制台'),
            'user' => $this->user,
            'history' => $history,
            'keysCount' => $keysCount,
            'stats' => $stats,
        ]);
    }

    public function settings(): void
    {
        $this->requireLogin();
        view('dashboard/settings', [
            'title' => app_zh('个人设置'),
            'user' => $this->user,
        ]);
    }

    public function updateProfile(): void
    {
        $this->requireLogin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('settings');
        }

        $input = app_request_data();
        $name = app_clean_text((string)($input['full_name'] ?? ''), 120);
        (new UserModel())->update((int)$this->user['id'], ['full_name' => $name]);
        flash('success', app_zh('资料已更新'));
        redirect('settings');
    }

    public function updatePassword(): void
    {
        $this->requireLogin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('settings');
        }

        $input = app_request_data();
        $current = (string)($input['current'] ?? '');
        $password = (string)($input['password'] ?? '');
        $password2 = (string)($input['password2'] ?? '');

        if (!verify_password($current, (string)$this->user['password_hash'])) {
            flash('error', app_zh('当前密码错误'));
            redirect('settings');
        }
        if (strlen($password) < 6) {
            flash('error', app_zh('新密码至少 6 位'));
            redirect('settings');
        }
        if ($password !== $password2) {
            flash('error', app_zh('两次密码不一致'));
            redirect('settings');
        }

        (new UserModel())->update((int)$this->user['id'], ['password_hash' => create_password($password)]);
        flash('success', app_zh('密码已更新'));
        redirect('settings');
    }

    public function recharge(): void
    {
        $this->requireLogin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('settings');
        }

        $input = app_request_data();
        $code = app_clean_text((string)($input['recharge_code'] ?? ''), 128);
        if ($code === '') {
            flash('error', app_zh('请输入充值码'));
            redirect('settings');
        }

        $amount = (new ReferralModel())->redeemForUser($code, (int)$this->user['id']);
        if ($amount === null) {
            flash('error', app_zh('充值码无效或已被使用'));
            redirect('settings');
        }

        flash('success', app_zh('充值成功，到账金额：') . $amount);
        redirect('settings');
    }

    public function connectDemo(): void
    {
        $this->requireLogin();

        $games = app_game_catalog();
        $defaultGameCode = (string)array_key_first($games);
        if ($defaultGameCode === '') {
            $defaultGameCode = 'PUBG';
        }

        $isPublicMode = app_uses_public_root();
        $connectUrl = $isPublicMode ? app_pretty_url('conncet') : app_absolute_url('conncet');
        $apiPingUrl = $isPublicMode ? app_pretty_url('api/v1/ping') : app_absolute_url('api/v1/ping');
        $apiLoginUrl = $isPublicMode ? app_pretty_url('api/v1/login') : app_absolute_url('api/v1/login');
        $apiQueryUrl = $isPublicMode ? app_pretty_url('api/v1/key/query') : app_absolute_url('api/v1/key/query');
        $apiUnbindUrl = $isPublicMode ? app_pretty_url('api/v1/key/unbind') : app_absolute_url('api/v1/key/unbind');
        $queryPageUrl = $isPublicMode ? app_pretty_url('query-key') : app_absolute_url('query-key');

        view('dashboard/connect_demo', [
            'title' => app_zh('对接示例'),
            'user' => $this->user,
            'is_public_mode' => $isPublicMode,
            'connect_get_url' => $connectUrl,
            'connect_post_url' => $connectUrl,
            'api_ping_url' => $apiPingUrl,
            'api_login_url' => $apiLoginUrl,
            'api_query_url' => $apiQueryUrl,
            'api_unbind_url' => $apiUnbindUrl,
            'query_page_url' => $queryPageUrl,
            'default_game_code' => $defaultGameCode,
            'games' => $games,
        ]);
    }
}
