<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;

class AiController extends Controller
{
    public function chat(Request $request)
    {
        $request->validate([
            'message'           => 'required|string|max:2000',
            'history'           => 'nullable|array',
            'history.*.role'    => 'required|in:user,assistant',
            'history.*.content' => 'required|string',
        ]);

        $user    = $request->user();
        $message = $request->input('message');
        $history = $request->input('history', []);

        $context      = $this->buildContext($user);
        $searchResult = $this->needsWebSearch($message) ? $this->webSearch($message) : null;
        $systemPrompt = $this->buildSystemPrompt($context, $searchResult);

        $messages = [['role' => 'system', 'content' => $systemPrompt]];
        foreach (array_slice($history, -10) as $h) {
            $messages[] = ['role' => $h['role'], 'content' => $h['content']];
        }
        $messages[] = ['role' => 'user', 'content' => $message];

        $apiKey = env('OPENAI_API_KEY');
        if (!$apiKey) {
            return response()->json([
                'reply' => "Sarkin Mota AI is currently being finalised and will be fully available shortly. Thank you for your patience."
            ]);
        }

        try {
            $response = Http::withToken($apiKey)
                ->timeout(30)
                ->post('https://api.openai.com/v1/chat/completions', [
                    'model'       => 'gpt-4o-mini',
                    'messages'    => $messages,
                    'max_tokens'  => 1200,
                    'temperature' => 0.7,
                ]);

            if ($response->successful()) {
                $reply = $response->json('choices.0.message.content') ?? 'I could not generate a response. Please try again.';
                return response()->json(['reply' => $reply]);
            }

            $errMsg = $response->json('error.message') ?? 'AI service temporarily unavailable.';
            return response()->json(['reply' => $errMsg], 503);
        } catch (\Exception $e) {
            return response()->json(['reply' => 'AI service error. Please try again later.'], 500);
        }
    }

    private function buildContext($user): array
    {
        $context = [
            'user_name' => $user->name,
            'user_role' => $user->roles->pluck('name')->first() ?? 'User',
            'company'   => null,
            'stats'     => [],
        ];

        if ($user->company_id) {
            $company = $user->company;
            if ($company) {
                $context['company'] = [
                    'name'        => $company->name,
                    'industry'    => $company->industry ?? 'General',
                    'status'      => $company->status,
                ];

                $from = Carbon::now()->startOfMonth();
                $to   = Carbon::now()->endOfMonth();

                $context['stats']['active_employees'] = DB::table('employees')
                    ->where('company_id', $company->id)->where('status', 'active')->count();

                $context['stats']['departments'] = DB::table('departments')
                    ->where('company_id', $company->id)->count();

                $context['stats']['expenses_this_month'] = '₦' . number_format(
                    DB::table('expenses')
                        ->where('company_id', $company->id)
                        ->whereBetween('expense_date', [$from, $to])
                        ->whereNotIn('status', ['rejected'])->sum('amount'), 2
                );

                $context['stats']['pending_invoices'] = DB::table('invoices')
                    ->where('company_id', $company->id)
                    ->whereIn('status', ['sent', 'overdue'])->count();

                $context['stats']['outstanding_invoice_value'] = '₦' . number_format(
                    DB::table('invoices')
                        ->where('company_id', $company->id)
                        ->whereIn('status', ['sent', 'partial', 'overdue'])->sum('total_amount'), 2
                );

                $context['stats']['active_loans'] = DB::table('intercompany_loans')
                    ->where('borrower_company_id', $company->id)->where('status', 'active')->count();

                try {
                    $context['stats']['total_assets'] = '₦' . number_format(
                        DB::table('company_assets')
                            ->where('company_id', $company->id)->where('status', 'active')->sum('current_value'), 2
                    );
                } catch (\Exception $e) {}
            }
        } else {
            $context['company'] = ['name' => 'Sarkin Mota Group', 'industry' => 'Holding Company'];
            $context['stats']['total_companies']    = DB::table('companies')->count();
            $context['stats']['total_active_employees'] = DB::table('employees')->where('status', 'active')->count();
            $context['stats']['active_loans']       = DB::table('intercompany_loans')->where('status', 'active')->count();
            $context['stats']['pending_loans']      = DB::table('intercompany_loans')->where('status', 'pending')->count();
            $context['stats']['total_sweep_processed'] = '₦' . number_format(
                DB::table('profit_sweep_transactions')
                    ->whereIn('status', ['completed', 'processed'])->sum('actual_amount'), 2
            );
        }

        return $context;
    }

    private function buildSystemPrompt(array $context, ?string $searchResult): string
    {
        $company  = $context['company']['name'] ?? 'Sarkin Mota Group';
        $industry = $context['company']['industry'] ?? 'General';
        $role     = $context['user_role'];

        $statsText = '';
        foreach ($context['stats'] as $key => $val) {
            $label      = ucwords(str_replace('_', ' ', $key));
            $statsText .= "  • {$label}: {$val}\n";
        }

        $searchSection = $searchResult
            ? "\n\nWEB SEARCH RESULTS (supplement your answer with these):\n{$searchResult}\n"
            : '';

        return <<<PROMPT
You are Sarkin Mota AI — the intelligent business assistant embedded in the Sarkin Mota Group management platform for {$company}.

You are speaking with {$context['user_name']} ({$role}).

COMPANY: {$company} | INDUSTRY: {$industry}

LIVE DATA SNAPSHOT:
{$statsText}
YOUR ROLE:
- Answer questions about this company's data, operations, finances, HR, and performance.
- Give actionable business insights and recommendations based on the data above.
- Help with strategy, compliance, finance, HR, and operational questions.
- For external topics (market trends, benchmarks, news), use any web search results provided.

GUIDELINES:
- Be concise, professional, and data-driven.
- Use bullet points and short paragraphs for clarity.
- If specific data is unavailable, say so honestly — never fabricate numbers.
- Only reference data for {$company} unless the user is a Super Admin asking group-wide questions.
- Always respond as "Sarkin Mota AI".{$searchSection}
PROMPT;
    }

    private function needsWebSearch(string $message): bool
    {
        $keywords = ['market', 'trend', 'industry', 'benchmark', 'news', 'price', 'exchange rate',
                     'regulation', 'law', 'latest', 'current', 'today', 'how to', 'what is', 'search'];
        $lower    = strtolower($message);
        foreach ($keywords as $kw) {
            if (str_contains($lower, $kw)) return true;
        }
        return false;
    }

    private function webSearch(string $query): ?string
    {
        $apiKey = env('SERPAPI_KEY');
        if (!$apiKey) return null;

        try {
            $response = Http::timeout(8)->get('https://serpapi.com/search.json', [
                'q'       => $query,
                'api_key' => $apiKey,
                'num'     => 4,
                'hl'      => 'en',
            ]);

            if ($response->successful()) {
                $results = $response->json('organic_results', []);
                $text    = '';
                foreach (array_slice($results, 0, 4) as $r) {
                    $text .= "• {$r['title']}: {$r['snippet']}\n";
                }
                return $text ?: null;
            }
        } catch (\Exception $e) {}

        return null;
    }
}
