<?php

namespace App\Http\Controllers;

use App\Jobs\GenerateSurveyInsights;
use App\Mail\AdminNewLeadMail;
use App\Mail\SurveyCompletedMail;
use App\Models\Lead;
use App\Models\SurveyResponse;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;

class SurveyController extends Controller
{
    public function show()
    {
        return view('frontend.survey');
    }

    /**
     * Survey бөглөж дуусгасан үед хадгалах.
     */
    public function submit(Request $request)
    {
        $data = $request->validate([
            'email'           => 'required|email|max:255',
            'name'            => 'nullable|string|max:255',
            'phone'           => 'nullable|string|max:50',
            'biz_name'        => 'nullable|string|max:255',
            'responses'       => 'required|array',
        ]);

        // Upsert lead
        $lead = Lead::updateOrCreate(
            ['email' => $data['email']],
            [
                'name'          => $data['name'] ?? null,
                'phone'         => $data['phone'] ?? null,
                'business_name' => $data['biz_name'] ?? null,
                'source'        => 'survey',
                'status'        => 'new',
            ]
        );

        $r = $data['responses'];
        $tier = $this->recommendTier($r);

        $survey = SurveyResponse::create([
            'lead_id'          => $lead->id,
            'email'            => $data['email'],
            'biz_name'         => $r['bizName'] ?? null,
            'biz_type'         => $r['bizType'] ?? null,
            'biz_age'          => $r['bizAge'] ?? null,
            'revenue'          => $r['revenue'] ?? null,
            'channels'         => $r['channels'] ?? [],
            'pain_point'       => $r['painPoint'] ?? null,
            'persona_gender'   => $r['personaGender'] ?? null,
            'persona_age'      => $r['personaAge'] ?? null,
            'persona_income'   => $r['personaIncome'] ?? null,
            'persona_time'     => $r['personaTime'] ?? null,
            'persona_why'      => $r['personaWhy'] ?? null,
            'brand_words'      => $r['brandWords'] ?? [],
            'brand_voice'      => $r['brandVoice'] ?? null,
            'brand_color'      => $r['brandColor'] ?? null,
            'brand_statement'  => $r['brandStatement'] ?? null,
            'has_time'         => ($r['hasTime'] ?? null) === 'yes',
            'has_team'         => $r['hasTeam'] ?? null,
            'marketing_budget' => $r['marketingBudget'] ?? null,
            'recommended_tier' => $tier,
            'raw_responses'    => $r,
            'completed_at'     => now(),
        ]);

        // Dispatch Claude AI insights generation
        if (config('services.claude.api_key')) {
            GenerateSurveyInsights::dispatch($survey);
        } else {
            $survey->update(['ai_status' => 'failed']);
        }

        // Email-уудыг queue-д явуулна
        try {
            Mail::to($lead->email)->queue(new SurveyCompletedMail($lead, $survey));
            Mail::to(config('mail.admin_email', 'info@nsma.mn'))->queue(new AdminNewLeadMail($lead));
        } catch (\Exception $e) {
            \Log::warning('Failed to queue survey email: ' . $e->getMessage());
        }

        return response()->json([
            'ok' => true,
            'survey_id' => $survey->id,
            'recommended_tier' => $tier,
            'ai_enabled' => (bool) config('services.claude.api_key'),
            'message' => 'Танай оношлогооны тайлан бэлэн боллоо. AI insights 30-60 секундад нэмэгдэнэ.',
        ]);
    }

    /**
     * AI insights-ыг polling-ээр шалгах endpoint.
     */
    public function insights(int $id)
    {
        $survey = \App\Models\SurveyResponse::findOrFail($id);

        return response()->json([
            'status' => $survey->ai_status,
            'data' => $survey->ai_status === 'completed' ? [
                'strategic_diagnosis' => $survey->ai_strategic_diagnosis,
                'customer_narrative'  => $survey->ai_customer_narrative,
                'action_plan_30day'   => $survey->ai_action_plan_30day,
                'content_ideas'       => $survey->ai_content_ideas,
                'brand_voice_sample'  => $survey->ai_brand_voice_sample,
            ] : null,
        ]);
    }

    protected function recommendTier(array $r): string
    {
        $tier = 'lite';

        if (($r['hasTime'] ?? null) === 'no' && ($r['hasTeam'] ?? null) !== 'solo') {
            $tier = 'standard';
        }
        if (in_array($r['marketingBudget'] ?? null, ['5-20m', '20m+']) ||
            ($r['hasTeam'] ?? null) === 'large') {
            $tier = 'pro';
        }
        return $tier;
    }
}
