<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Article;
use App\Models\Category;
use App\Models\Produk;
use App\Models\ChatLog;

class DashboardController extends Controller
{
    public function index()
    {
        // ==========================
        // 📊 DATA UTAMA
        // ==========================
        $userCount = User::count();
        $articleCount = Article::count();
        $categoryCount = Category::count();
        $productCount = Produk::count();
        $recentArticles = Article::with('category')->latest()->take(4)->get();

        $threshold = 0.60;

        $totalChats = ChatLog::count();

        $totalSessions = ChatLog::distinct('session_id')
            ->count('session_id');


        $chatBase = ChatLog::whereNotNull('similarity_score');

        $validContext = (clone $chatBase)
            ->where('similarity_score', '>=', $threshold)
            ->where('bot_response', 'not like', '%Maaf%')
            ->count();

        $knowledgeGap = (clone $chatBase)
            ->where('similarity_score', '>=', $threshold)
            ->where('bot_response', 'like', '%Maaf%')
            ->count();
        $outOfContext = (clone $chatBase)
            ->where('similarity_score', '<', $threshold)
            ->count();

        $relevantTotal = $validContext + $knowledgeGap;

        $successRate = $relevantTotal > 0
            ? ($validContext / $relevantTotal) * 100
            : 0;

        // $fallbackRate = $relevantTotal > 0
        //     ? ($knowledgeGap / $relevantTotal) * 100
        //     : 0;
        $fallbackRate = $totalChats > 0 ? ($knowledgeGap / $totalChats) * 100 : 0;

        $totalEvaluated = ChatLog::whereNotNull('is_correct')->count();

        $correctAnswers = ChatLog::where('is_correct', true)->count();

        $accuracy = $totalEvaluated > 0
            ? ($correctAnswers / $totalEvaluated) * 100
            : 0;

        $finalScore = (0.6 * $successRate) + (0.4 * $accuracy);

        $recentChats = ChatLog::latest()->take(5)->get();

        return view('admin.dashboard', compact(
            'userCount',
            'articleCount',
            'categoryCount',
            'productCount',
            'recentArticles',
            'totalChats',        
            'totalSessions',     
            'validContext',
            'knowledgeGap',
            'outOfContext',
            'successRate',
            'fallbackRate',
            'accuracy',
            'finalScore',
            'recentChats'
        ));
    }
}