<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\WeightConfigController as ApiWeightConfigController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class WeightConfigController extends Controller
{
    public function index()
    {
        $config = ApiWeightConfigController::getConfig();

        $totalRaw = Redis::hgetall(ApiWeightConfigController::REDIS_KEY_CLICKS);
        $totalClicks = [];
        foreach (ApiWeightConfigController::VALID_IDS as $id) {
            $totalClicks[$id] = isset($totalRaw[$id]) ? intval($totalRaw[$id]) : 0;
        }

        $days = 7;
        $dailyClicks = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $raw = Redis::hgetall(ApiWeightConfigController::REDIS_KEY_CLICKS_DAILY_PREFIX . $date);
            $row = ['date' => $date];
            foreach (ApiWeightConfigController::VALID_IDS as $id) {
                $row[$id] = isset($raw[$id]) ? intval($raw[$id]) : 0;
            }
            $dailyClicks[] = $row;
        }

        return view('admin.weight_config.index', compact('config', 'totalClicks', 'dailyClicks'));
    }

    public function update(Request $request)
    {
        $config = $request->input('config');
        if (is_string($config)) {
            $config = json_decode($config, true);
        }
        if (!is_array($config)) {
            return response()->json(['status' => 'error', 'message' => '参数错误']);
        }

        $save = [];
        foreach (ApiWeightConfigController::VALID_IDS as $id) {
            $val = isset($config[$id]) ? intval($config[$id]) : 0;
            if ($val < 0) $val = 0;
            $save[$id] = $val;
        }

        if (array_sum($save) <= 0) {
            return response()->json(['status' => 'error', 'message' => '权重之和必须大于 0']);
        }

        Redis::set(ApiWeightConfigController::REDIS_KEY_CONFIG, json_encode($save));
        return response()->json(['status' => 'success', 'message' => '更新成功', 'config' => $save]);
    }

    public function resetStats(Request $request)
    {
        $type = $request->input('type', 'total');
        if ($type === 'all') {
            Redis::del(ApiWeightConfigController::REDIS_KEY_CLICKS);
            $keys = Redis::keys(ApiWeightConfigController::REDIS_KEY_CLICKS_DAILY_PREFIX . '*');
            if (!empty($keys)) {
                $prefix = config('database.redis.options.prefix', '');
                if ($prefix) {
                    $keys = array_map(function ($k) use ($prefix) {
                        return strpos($k, $prefix) === 0 ? substr($k, strlen($prefix)) : $k;
                    }, $keys);
                }
                foreach ($keys as $k) {
                    Redis::del($k);
                }
            }
        } else {
            Redis::del(ApiWeightConfigController::REDIS_KEY_CLICKS);
        }
        return response()->json(['status' => 'success', 'message' => '清除成功']);
    }
}
