<?php

namespace App\Http\Controllers;

use App\Models\ChatMessage;
use App\Models\ChatSession;
use App\Models\Lead;
use App\Models\LeadFormSubmission;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class LeadController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'chat_session_id' => ['required', 'integer', 'exists:chat_sessions,id'],
            'name' => ['required', 'string', 'max:120'],
            'phone' => ['required', 'string', 'max:30'],
            'facebook_page' => ['nullable', 'string', 'max:255'],
            'website' => ['nullable', 'string', 'max:255'],
            'pain_point' => ['required', 'string', 'max:3000'],
        ]);

        $session = ChatSession::findOrFail($validated['chat_session_id']);
        $normalizedPhone = $this->normalizePhone($validated['phone']);

        $form = LeadFormSubmission::create([
            'chat_session_id' => $session->id,
            'name' => $validated['name'],
            'phone' => $normalizedPhone,
            'facebook_page' => $validated['facebook_page'] ?? null,
            'website' => $validated['website'] ?? null,
            'pain_point' => $validated['pain_point'],
            'extra_data' => [
                'submitted_from' => 'sales_chat_form',
            ],
            'source' => 'chatbot-form',
            'ip_address' => $request->ip(),
            'user_agent' => Str::limit((string) $request->userAgent(), 1000, ''),
        ]);

        Lead::updateOrCreate(
            ['phone' => $normalizedPhone],
            [
                'name' => $validated['name'],
                'phone' => $normalizedPhone,
                'website' => $validated['website'] ?? null,
                'facebook_page' => $validated['facebook_page'] ?? null,
                'pain_point' => $validated['pain_point'],
                'source' => 'chatbot-form',
                'status' => 'submitted',
                'conversation_snapshot' => $session->messages()->whereIn('role', ['user', 'assistant'])->select('role', 'message', 'created_at')->get()->toArray(),
                'ip_address' => $request->ip(),
                'user_agent' => Str::limit((string) $request->userAgent(), 1000, ''),
            ]
        );

        $session->update([
            'phone' => $normalizedPhone,
            'lead_status' => 'submitted',
            'last_lead_prompt_at' => now(),
            'last_activity_at' => now(),
            'metadata' => array_merge($session->metadata ?? [], [
                'last_form_submission_id' => $form->id,
                'business_problem' => Str::limit($validated['pain_point'], 500),
            ]),
        ]);

        ChatMessage::create([
            'chat_session_id' => $session->id,
            'role' => 'system',
            'message' => 'Sales form submitted by visitor.',
            'meta' => ['form_submission_id' => $form->id],
        ]);

        return response()->json([
            'status' => 'ok',
            'id' => $form->id,
        ]);
    }

    private function normalizePhone(?string $phone): ?string
    {
        if (! filled($phone)) {
            return null;
        }

        $digits = preg_replace('/\D+/', '', $phone ?? '');

        if (str_starts_with($digits, '88') && strlen($digits) === 13) {
            $digits = substr($digits, 2);
        }

        return $digits ?: null;
    }
}
