<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Menu;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GeminiChatController extends Controller
{
    public function index()
    {
        return view('frontend.chatbot');
    }

    public function chat(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'message' => ['required', 'string', 'max:1500'],
            'history' => ['nullable', 'array'],
            'history.*.role' => ['nullable', 'string'],
            'history.*.text' => ['nullable', 'string', 'max:3000'],
            'phone' => ['nullable', 'string', 'max:30'],
        ]);

        $apiKey = trim((string) config('services.gemini.api_key'));
        $model = trim((string) config('services.gemini.model', 'gemini-2.5-flash-lite'));

        if ($apiKey === '') {
            return response()->json([
                'success' => false,
                'message' => 'Gemini API key set করা নেই। .env ফাইলে GEMINI_API_KEY যোগ করুন।',
            ], 500);
        }

        $contents = [];

        foreach (($validated['history'] ?? []) as $item) {
            $text = trim((string) ($item['text'] ?? ''));
            if ($text === '') {
                continue;
            }

            $role = (($item['role'] ?? 'user') === 'model') ? 'model' : 'user';
            $contents[] = [
                'role' => $role,
                'parts' => [
                    ['text' => $text],
                ],
            ];
        }

        $contents[] = [
            'role' => 'user',
            'parts' => [
                ['text' => trim((string) $validated['message'])],
            ],
        ];

        $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent';

        $payload = [
            'system_instruction' => [
                'parts' => [
                    ['text' => $this->buildSystemInstruction()],
                ],
            ],
            'contents' => $contents,
            'generationConfig' => [
                'temperature' => 0.5,
                'topP' => 0.9,
                'maxOutputTokens' => 700,
            ],
        ];

        try {
            $response = Http::timeout(45)
                ->acceptJson()
                ->withQueryParameters(['key' => $apiKey])
                ->post($endpoint, $payload);
        } catch (\Throwable $e) {
            Log::error('Gemini HTTP request failed', [
                'message' => $e->getMessage(),
                'model' => $model,
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Server থেকে Gemini API-তে connect করা যায়নি।',
                'debug' => app()->environment('local') ? $e->getMessage() : null,
            ], 500);
        }

        $responseBody = $response->json();

        if (! $response->successful()) {
            $googleMessage = data_get($responseBody, 'error.message')
                ?: data_get($responseBody, 'message')
                ?: $response->body();

            Log::error('Gemini API response error', [
                'status' => $response->status(),
                'model' => $model,
                'body' => $responseBody ?: $response->body(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Gemini API response error: ' . $googleMessage,
                'status' => $response->status(),
            ], 500);
        }

        $answerParts = data_get($responseBody, 'candidates.0.content.parts', []);
        $answer = collect($answerParts)
            ->pluck('text')
            ->filter(fn ($text) => is_string($text) && trim($text) !== '')
            ->implode("\n");

        if (trim($answer) === '') {
            Log::warning('Gemini empty answer', [
                'model' => $model,
                'body' => $responseBody,
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Gemini কোনো valid উত্তর দেয়নি।',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'answer' => trim($answer),
        ]);
    }

    protected function buildSystemInstruction(): string
    {
        $siteName = config('app.name', 'SEF Card');
        $phone = function_exists('getOption') ? (getOption('phone') ?: 'N/A') : 'N/A';
        $email = function_exists('getOption') ? (getOption('email') ?: 'N/A') : 'N/A';
        $address = function_exists('getOption') ? (getOption('address') ?: 'N/A') : 'N/A';
        $homepage = url('/');

        $menuNames = Menu::whereNull('parent_id')
            ->orderBy('order')
            ->pluck('name')
            ->filter()
            ->take(12)
            ->values()
            ->implode(', ');

        $products = Product::latest()
            ->take(12)
            ->get(['name', 'slug', 'price', 'discount_price'])
            ->map(function ($product) {
                $price = ((float) $product->discount_price > 0) ? $product->discount_price : $product->price;
                $productUrl = route('details', $product->slug);

                return sprintf(
                    '- %s | Price: %s | URL: %s',
                    $product->name,
                    number_format((float) $price, 2),
                    $productUrl
                );
            })
            ->implode("\n");

        return trim(
            "You are the official customer support chatbot for {$siteName}. " .
            "Always answer in a helpful, short, sales-friendly way. " .
            "Reply in Bangla when the customer writes in Bangla, otherwise reply in English. " .
            "Focus on products, pricing, ordering, delivery, support, and website navigation. " .
            "When the user asks to see products, visit products, or browse items, tell them to click the 'Show Product' button or go to {$homepage}. " .
            "Never invent unavailable policies or contact details. If you are unsure, politely say the customer can contact support. " .
            "Store info: phone {$phone}, email {$email}, address {$address}. " .
            "Main website URL: {$homepage}. " .
            "Top categories: {$menuNames}. " .
            "Example product references:\n{$products}\n" .
            "Keep answers clean text only, no markdown tables, no code, no fake links."
        );
    }
}
