<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Updater;
use App\Models\ReferralModel;
use App\Models\StatsModel;
use App\Models\SystemModel;
use App\Models\UserModel;

class AdminController extends Controller
{
    public function users(): void
    {
        $this->requireAdmin();
        $users = (new UserModel())->listUsers();
        view('admin/users', [
            'title' => app_zh('用户管理'),
            'user' => $this->user,
            'users' => $users,
        ]);
    }

    public function userEdit($id): void
    {
        $this->requireAdmin();
        $target = (new UserModel())->findById((int)$id);
        if (!$target) {
            flash('error', app_zh('用户不存在'));
            redirect('admin/users');
        }

        view('admin/user_edit', [
            'title' => app_zh('编辑用户'),
            'user' => $this->user,
            'target' => $target,
        ]);
    }

    public function userEditPost($id): void
    {
        $this->requireAdmin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('admin/users');
        }

        $input = app_request_data();
        $balance = (float)($input['balance'] ?? 0);
        $maxBalance = 9999999999.99;
        if ($balance < 0 || $balance > $maxBalance) {
            flash('error', app_zh('余额超出范围(0-9999999999.99)'));
            redirect('admin/users');
        }

        $data = [
            'username' => app_clean_text((string)($input['username'] ?? ''), 64),
            'full_name' => app_clean_text((string)($input['full_name'] ?? ''), 120),
            'role' => (($input['role'] ?? 'reseller') === 'admin') ? 'admin' : 'reseller',
            'status' => (($input['status'] ?? 'active') === 'active') ? 'active' : 'disabled',
            'balance' => $balance,
        ];
        (new UserModel())->update((int)$id, $data);
        flash('success', app_zh('用户已更新'));
        redirect('admin/users');
    }

    public function userDelete(): void
    {
        $this->requireAdmin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('admin/users');
        }

        $input = app_request_data();
        $id = (int)($input['id'] ?? 0);
        if ($id <= 0) {
            flash('error', app_zh('参数错误'));
            redirect('admin/users');
        }
        if ((int)$this->user['id'] === $id) {
            flash('error', app_zh('不能删除当前登录账号'));
            redirect('admin/users');
        }

        $model = new UserModel();
        $target = $model->findById($id);
        if (!$target) {
            flash('error', app_zh('用户不存在'));
            redirect('admin/users');
        }

        $model->deleteById($id);
        flash('success', app_zh('用户已删除'));
        redirect('admin/users');
    }

    public function referrals(): void
    {
        $this->requireAdmin();
        $referrals = (new ReferralModel())->listLatest(100);
        view('admin/referrals', [
            'title' => app_zh('邀请码管理'),
            'user' => $this->user,
            'referrals' => $referrals,
        ]);
    }

    public function referralsPost(): void
    {
        $this->requireAdmin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('admin/referrals');
        }

        $input = app_request_data();
        $setBalance = (float)($input['set_balance'] ?? 0);
        $code = strtoupper(substr(bin2hex(random_bytes(6)), 0, 6));
        (new ReferralModel())->create([
            'code' => $code,
            'code_hash' => hash('sha256', $code),
            'set_balance' => $setBalance,
            'created_by' => (int)$this->user['id'],
        ]);
        flash('success', app_zh('邀请码已生成：') . $code);
        redirect('admin/referrals');
    }

    public function stats(): void
    {
        $this->requireAdmin();
        $stats = (new StatsModel())->overview();
        view('admin/stats', [
            'title' => app_zh('数据统计'),
            'user' => $this->user,
            'stats' => $stats,
        ]);
    }

    public function system(): void
    {
        $this->requireAdmin();
        $system = (new SystemModel())->get();
        $cfg = app_config();
        $latestFromFlash = flash('update_latest');
        if (!is_array($latestFromFlash)) {
            $notice = remote_notice_data(false);
            $fromNotice = $notice['update_notice'] ?? null;
            if (is_array($fromNotice)) {
                $latestFromFlash = $fromNotice;
            }
        }

        $prices = app_normalize_key_prices($cfg['key_prices'] ?? []);

        view('admin/system', [
            'title' => app_zh('系统设置'),
            'user' => $this->user,
            'system' => $system,
            'app_name' => $cfg['app_name'] ?? '',
            'price_lines' => app_key_prices_to_text($prices),
            'app_version' => $cfg['app_version'] ?? '0.0.0',
            'update_latest' => $latestFromFlash,
            'update_error' => flash('update_error'),
            'update_success' => flash('update_success'),
            'migration_logs' => Updater::recentMigrationLogs(20),
        ]);
    }

    public function systemPost(): void
    {
        $this->requireAdmin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('admin/system');
        }

        $input = app_request_data();
        $appName = app_clean_text((string)($input['app_name'] ?? ''), 120);
        $priceRaw = app_clean_multiline_text((string)($input['key_prices'] ?? ''), 20000);

        $data = [
            'mod_name' => app_clean_text((string)($input['mod_name'] ?? ''), 120),
            'mod_status' => (($input['mod_status'] ?? 'on') === 'on') ? 'on' : 'off',
            'notice_text' => app_clean_multiline_text((string)($input['notice_text'] ?? ''), 5000),
            'notice_status' => app_clean_text((string)($input['notice_status'] ?? ''), 64),
            'maintenance_reason' => app_clean_multiline_text((string)($input['maintenance_reason'] ?? ''), 5000),
            'allow_self_unbind' => (($input['allow_self_unbind'] ?? '0') === '1') ? 1 : 0,
        ];
        (new SystemModel())->update($data);

        $cfg = app_config();
        try {
            $prices = app_parse_key_prices_text($priceRaw);
        } catch (\InvalidArgumentException $e) {
            flash('error', $e->getMessage());
            redirect('admin/system');
        }

        $newCfg = $cfg;
        $newCfg['app_name'] = $appName;
        $newCfg['key_prices'] = $prices;
        unset($newCfg['update_server'], $newCfg['update_token'], $newCfg['update_hmac_secret']);

        $configPath = __DIR__ . '/../../config/config.php';
        $cfgContent = "<?php\nreturn " . var_export($newCfg, true) . ";\n";
        $tmpPath = $configPath . '.tmp_' . bin2hex(random_bytes(4));

        if (file_put_contents($tmpPath, $cfgContent, LOCK_EX) === false || @rename($tmpPath, $configPath) === false) {
            @unlink($tmpPath);
            flash('error', app_zh('无法写入配置文件，请检查权限'));
            redirect('admin/system');
        }

        flash('success', app_zh('系统设置已保存'));
        redirect('admin/system');
    }

    public function updateCheck(): void
    {
        $this->requireAdmin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('admin/system');
        }

        $updater = new Updater();
        $res = $updater->check();
        if (!$res['ok']) {
            flash('update_error', $res['error'] ?? app_zh('检测更新失败'));
            redirect('admin/system');
        }

        $latest = $res['data'];
        $currentVersion = (string)(app_config()['app_version'] ?? '0.0.0');
        if (!$latest) {
            if ($currentVersion === '' || $currentVersion === '0.0.0') {
                flash('update_error', app_zh('未找到可用版本，请确认云端更新服务已发布版本且当前域名已授权。'));
            } else {
                flash('update_success', app_zh('当前已是最新版本（') . $currentVersion . app_zh('）'));
            }
            redirect('admin/system');
        }

        $latestVersion = (string)($latest['version'] ?? '');
        if ($latestVersion === '') {
            flash('update_error', app_zh('更新服务返回的版本号为空'));
            redirect('admin/system');
        }

        if (!station_is_version_newer($latestVersion, $currentVersion)) {
            flash('update_success', app_zh('当前已是最新版本（') . $currentVersion . app_zh('）'));
            redirect('admin/system');
        }

        flash('update_latest', $latest);
        flash('update_success', app_zh('检测到新版本：') . $latestVersion . app_zh('（当前：') . $currentVersion . app_zh('）'));
        redirect('admin/system');
    }

    public function updateDebug(): void
    {
        $this->requireAdmin();

        $forceRefresh = !empty($_GET['refresh']);
        $debug = function_exists('station_update_debug_snapshot')
            ? station_update_debug_snapshot($forceRefresh)
            : [];

        view('admin/update_debug', [
            'title' => app_zh('更新链路调试'),
            'user' => $this->user,
            'debug' => $debug,
            'app_version' => (string)(app_config()['app_version'] ?? '0.0.0'),
        ]);
    }

    public function updateApply(): void
    {
        $this->requireAdmin();
        if (!verify_csrf()) {
            flash('error', app_zh('安全校验失败'));
            redirect('admin/system');
        }

        $updater = new Updater();
        $check = $updater->check();
        if (!$check['ok']) {
            flash('update_error', $check['error'] ?? app_zh('检测更新失败'));
            redirect('admin/system');
        }

        $latest = $check['data'];
        $currentVersion = (string)(app_config()['app_version'] ?? '0.0.0');
        if (!$latest) {
            if ($currentVersion === '' || $currentVersion === '0.0.0') {
                flash('update_error', app_zh('未找到可用版本，请确认云端更新服务已发布版本且当前域名已授权。'));
            } else {
                flash('update_success', app_zh('当前已是最新版本（') . $currentVersion . app_zh('）'));
            }
            redirect('admin/system');
        }

        $latestVersion = (string)($latest['version'] ?? '');
        if ($latestVersion === '') {
            flash('update_error', app_zh('更新服务返回的版本号为空'));
            redirect('admin/system');
        }

        if (!station_is_version_newer($latestVersion, $currentVersion)) {
            flash('update_success', app_zh('当前已是最新版本（') . $currentVersion . app_zh('）'));
            redirect('admin/system');
        }

        $apply = $updater->apply($latest);
        if (!$apply['ok']) {
            flash('update_error', $apply['error'] ?? app_zh('更新失败'));
            redirect('admin/system');
        }

        flash('update_success', app_zh('已更新到版本 ') . $latestVersion);
        redirect('admin/system');
    }
}
