<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ChatLog;

class ChatLogController extends Controller
{
    public function index()
{
    $threshold = 0.60;


    $totalChats = ChatLog::count();

    $outOfContext = ChatLog::where('similarity_score', '<', $threshold)->count();

    $knowledgeGap = ChatLog::where('similarity_score', '>=', $threshold)
        ->whereRaw("LOWER(bot_response) LIKE '%maaf%'")
        ->count();

    $validContext = ChatLog::where('similarity_score', '>=', $threshold)
        ->whereRaw("LOWER(bot_response) NOT LIKE '%maaf%'")
        ->count();

    $relevantTotal = $validContext + $knowledgeGap;

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

    // $fallbackRate = $totalChats > 0 ? ($knowledgeGap / $totalChats) * 100 : 0;
    $fallbackRate = ($knowledgeGap / $relevantTotal) * 100;
    
    // outkonteks (dibawah 55)
    $outOfContextRate = $totalChats > 0 ? ($outOfContext / $totalChats) * 100 : 0;

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

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


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

    $dailyStats = (clone $chatBase)->selectRaw("
        DATE(created_at) as date,
        COUNT(*) as total,
        SUM(CASE 
            WHEN similarity_score >= $threshold 
            AND LOWER(bot_response) NOT LIKE '%maaf%' 
            THEN 1 ELSE 0 END) as success,
        SUM(CASE 
            WHEN similarity_score >= $threshold 
            AND LOWER(bot_response) LIKE '%maaf%' 
            THEN 1 ELSE 0 END) as gap
    ")
        ->groupBy('date')
        ->orderBy('date')
        ->get();

    $pendingCount = ChatLog::whereNull('is_correct')
        ->whereNotNull('similarity_score')
        ->whereRaw("LOWER(bot_response) NOT LIKE '%maaf%'")
        ->count();

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

    $gapCount = ChatLog::where('is_correct', false)
        ->whereRaw("LOWER(bot_response) NOT LIKE '%maaf%'")
        ->count();

    $autoCount = ChatLog::whereRaw("LOWER(bot_response) LIKE '%maaf%'")->count();
    $notAnsweredRate = $totalChats > 0 
    ? ($autoCount / $totalChats) * 100 
    : 0;

$notSuitableRate = $totalEvaluated > 0 
    ? ($gapCount / $totalEvaluated) * 100 
    : 0;

    $highScore = ChatLog::where('similarity_score', '>=', 0.7)->count();
    $mediumScore = ChatLog::whereBetween('similarity_score', [0.55, 0.69])->count();
    $lowScore = ChatLog::where('similarity_score', '<', 0.55)->count();


    $filter = request('filter') ?? 'pending';
    $query = ChatLog::latest();

    if ($filter == 'pending') {
        $query->whereNull('is_correct')
            ->whereRaw("LOWER(bot_response) NOT LIKE '%maaf%'");
    } elseif ($filter == 'valid') {
        $query->where('is_correct', true);
    } elseif ($filter == 'gap') {
        $query->where('is_correct', false)
            ->whereRaw("LOWER(bot_response) NOT LIKE '%maaf%'");
    } elseif ($filter == 'auto') {
        $query->whereRaw("LOWER(bot_response) LIKE '%maaf%'");
    } elseif ($filter == 'high') {
        $query->where('similarity_score', '>=', 0.7);
    } elseif ($filter == 'medium') {
        $query->whereBetween('similarity_score', [0.55, 0.69]);
    } elseif ($filter == 'low') {
        $query->where('similarity_score', '<', 0.55);
    } elseif ($filter == 'all') {
    }

    $chats = $query->paginate(10)->withQueryString();

    return view('admin.chatlogs.index', compact(
        'chats', 'totalChats', 'validContext', 'knowledgeGap', 'outOfContext',
        'successRate', 'fallbackRate', 'accuracy', 'dailyStats',
        'pendingCount', 'validCount', 'gapCount', 'autoCount',
        'filter', 'highScore', 'mediumScore', 'lowScore', 
        'notAnsweredRate',
    'notSuitableRate',
    ));
}
public function validateAnswer(Request $request, $id)
{
    $request->validate([
        'is_correct' => 'required|boolean'
    ]);

    $chat = ChatLog::findOrFail($id);

    $chat->is_correct = (bool) $request->is_correct;
    $chat->save();

    return back()->with('success', 'Validasi berhasil diperbarui');
}
public function exportRagas()
{
    $logs = ChatLog::whereNotNull('similarity_score')
        ->latest()
        ->take(20)
        ->get();

    $data = [];

    foreach ($logs as $log) {
        $contexts = [];

        if ($log->doc_scores) {
            $docs = json_decode($log->doc_scores, true);

            foreach ($docs as $d) {
                $contexts[] = "Dokumen dengan skor: " . $d['score'];
            }
        }

        $data[] = [
            "question" => $log->user_message,
            "answer" => $log->bot_response,
            "contexts" => $contexts,
            "ground_truth" => $log->bot_response 
        ];
    }

    return response()->json($data);
}
}