<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Stats;
use App\Models\Visits;
use App\Services\AppDataResetService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function stats()
    {
        $totalClients = Client::count();
        $bannedClients = Client::where('ban', 1)->count();
        $botBlocked = Client::query()
            ->where(function ($q) {
                $q->where('ban', 1)->orWhere('ban', true);
            })
            ->count();

        $verdictBreakdown = Client::query()
            ->select('bot_verdict')
            ->selectRaw('count(*) as total')
            ->groupBy('bot_verdict')
            ->get()
            ->map(fn ($row) => [
                'verdict' => $row->bot_verdict ?: 'unknown',
                'total' => (int) $row->total,
            ]);

        $clean = (int) Client::where('bot_verdict', 'clean')->count();
        $suspicious = (int) Client::where('bot_verdict', 'suspicious')->count();
        $bot = (int) Client::where('bot_verdict', 'bot')->count();
        $unknown = (int) Client::whereNull('bot_verdict')->orWhere('bot_verdict', '')->count();

        $scoreBuckets = [
            [
                'label' => 'Clean (0–30)',
                'range' => '0-30',
                'total' => (int) Client::whereNotNull('bot_score')->where('bot_score', '<=', 30)->count(),
            ],
            [
                'label' => 'Suspicious (31–60)',
                'range' => '31-60',
                'total' => (int) Client::whereBetween('bot_score', [31, 60])->count(),
            ],
            [
                'label' => 'Bot (61+)',
                'range' => '61+',
                'total' => (int) Client::where('bot_score', '>=', 61)->count(),
            ],
        ];

        $avgScore = Client::whereNotNull('bot_score')->avg('bot_score');
        $recent24h = Client::where('created_at', '>=', now()->subDay())->count();
        $captchaPassed = Client::whereNotNull('captcha_passed_at')->count();

        $recentClients = Client::query()
            ->orderByDesc('updated_at')
            ->limit(12)
            ->get([
                'id',
                'unique_id',
                'ip',
                'country_code',
                'isp',
                'bot_score',
                'bot_verdict',
                'ban',
                'why',
                'action',
                'updated_at',
            ])
            ->map(fn (Client $c) => [
                'id' => $c->id,
                'unique_id' => $c->unique_id,
                'ip' => $c->ip,
                'country_code' => $c->country_code,
                'isp' => $c->isp,
                'bot_score' => $c->bot_score,
                'bot_verdict' => $c->bot_verdict,
                'ban' => (bool) $c->ban,
                'why' => $c->why,
                'action' => $c->action,
                'updated_at' => $c->updated_at?->toIso8601String(),
            ]);

        $flaggedClients = Client::query()
            ->where(function ($q) {
                $q->whereIn('bot_verdict', ['suspicious', 'bot'])
                    ->orWhere('bot_score', '>=', 31);
            })
            ->orderByDesc('bot_score')
            ->limit(8)
            ->get([
                'id',
                'unique_id',
                'ip',
                'bot_score',
                'bot_verdict',
                'ban',
                'updated_at',
            ])
            ->map(fn (Client $c) => [
                'id' => $c->id,
                'unique_id' => $c->unique_id,
                'ip' => $c->ip,
                'bot_score' => $c->bot_score,
                'bot_verdict' => $c->bot_verdict,
                'ban' => (bool) $c->ban,
                'updated_at' => $c->updated_at?->toIso8601String(),
            ]);

        return [
            'success' => true,
            'data' => [
                'summary' => [
                    'total_clients' => $totalClients,
                    'banned_clients' => $bannedClients,
                    'bot_blocked' => $botBlocked,
                    'clean' => $clean,
                    'suspicious' => $suspicious,
                    'bot' => $bot,
                    'unknown' => $unknown,
                    'recent_24h' => $recent24h,
                    'avg_bot_score' => $avgScore !== null ? round((float) $avgScore, 1) : null,
                    'captcha_passed' => $captchaPassed,
                ],
                'verdict_breakdown' => $verdictBreakdown,
                'score_buckets' => $scoreBuckets,
                'recent_clients' => $recentClients,
                'flagged_clients' => $flaggedClients,
            ],
        ];
    }

    public function resetStats(Request $request, AppDataResetService $resetService): JsonResponse
    {
        $resetService->reset();

        return response()->json([
            'success' => true,
            'message' => 'All clients, visits, and app stats have been reset.',
        ]);
    }
}
