<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\ChatLog;

class ChatbotController extends Controller
{
    public function handle(Request $request)
    {
        $request->validate([
            'message' => 'required|string|max:255',
        ]);

        $userMessage = $request->input('message');
        $baseUrl = env('RAG_API_URL', 'http://127.0.0.1:5000');

        $response = Http::timeout(60)->post($baseUrl . '/chat', [
            'message' => $userMessage,
            'session_id' => session()->getId(),
        ]);

        if ($response->successful()) {

            $data = $response->json();

            $botReply = $data['reply'] ?? 'Maaf, terjadi kesalahan saat memproses jawaban.';
            $score = $data['score'] ?? 0;
            $vector = $data['vector'] ?? null;
            $docScores = $data['doc_scores'] ?? [];

            $isCorrect = null;
            $lowerReply = strtolower($botReply);

            if (
                str_contains($lowerReply, 'maaf') ||
                str_contains($lowerReply, 'tidak tahu') ||
                str_contains($lowerReply, 'tidak tersedia')
            ) {
                $isCorrect = false;
            }

            try {
                ChatLog::create([
                    'session_id' => session()->getId(),
                    'user_message' => $userMessage,
                    'bot_response' => $botReply,
                    'similarity_score' => $score,
                    'is_correct' => $isCorrect, 
                    'query_vector' => $vector ? json_encode($vector) : null,
                    'doc_scores' => json_encode($docScores),
                ]);
            } catch (\Exception $e) {
                \Log::error('Gagal menyimpan ChatLog: ' . $e->getMessage());
            }

            return response()->json([
                'reply' => $botReply,
                'suggestions' => $data['suggestions'] ?? []
            ]);
        } else {

            \Log::error('RAG Engine Error: ' . $response->body());
            \Log::info('FLASK RESPONSE:', $response->json());
            return response()->json([
                'reply' => 'Maaf, asisten virtual sedang mengalami gangguan. Silakan coba lagi beberapa saat.'
            ], 500);
        }
    }
}