<?php

namespace App\Http\Controllers;

use App\Mail\PropostaCalculadoraMail;
use App\Models\AuditLog;
use App\Models\Lead;
use App\Models\Proposta;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class LeadController extends Controller
{
    public function index(Request $request)
    {
        $query = Lead::with('proposta')->latest();

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $leads = $query->get();

        $stats = [
            'total'       => Lead::count(),
            'novos'       => Lead::where('status', 'Novo')->count(),
            'em_contato'  => Lead::where('status', 'Em contato')->count(),
            'convertidos' => Lead::where('status', 'Convertido')->count(),
        ];

        return view('pages.leads.index', [
            'leads'    => $leads,
            'stats'    => $stats,
            'statuses' => Lead::statuses(),
            'filtro'   => $request->status,
        ]);
    }

    public function simulador()
    {
        return view('pages.simulador');
    }

    public function storeSimulador(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'              => 'required|string|max:150',
            'email'             => 'required|email|max:150',
            'phone'             => 'nullable|string|max:20',
            'company'           => 'nullable|string|max:150',
            'situacao'          => 'required|string|max:50',
            'regime'            => 'nullable|string|max:100',
            'faturamento_faixa' => 'nullable|string|max:100',
            'funcionarios'      => 'nullable|string|max:50',
            'prolabore'         => 'nullable|string|max:50',
            'nf_mes'            => 'nullable|string|max:50',
            'complexidade'      => 'nullable|string|max:50',
            'fidelidade'        => 'nullable|string|max:50',
            'observacoes'       => 'nullable|string|max:1000',
        ]);

        $perfil = array_filter([
            'situacao'          => $data['situacao'],
            'regime'            => $data['regime'] ?? null,
            'faturamento_faixa' => $data['faturamento_faixa'] ?? null,
            'funcionarios'      => $data['funcionarios'] ?? null,
            'prolabore'         => $data['prolabore'] ?? null,
            'nf_mes'            => $data['nf_mes'] ?? null,
            'complexidade'      => $data['complexidade'] ?? null,
            'fidelidade'        => $data['fidelidade'] ?? null,
        ]);

        $lead = Lead::create([
            'name'             => $data['name'],
            'email'            => $data['email'],
            'phone'            => $data['phone'] ?? '',
            'company'          => $data['company'] ?? '',
            'status'           => 'Novo',
            'origem'           => 'simulador',
            'message'          => $data['observacoes'] ?? 'Solicitação via simulador de honorários.',
            'perfil_simulador' => $perfil,
        ]);

        AuditLog::record('lead.simulador', "Lead gerado via simulador por {$lead->name}", $lead);

        try {
            Mail::to(config('mail.from.address'))->send(new \App\Mail\NovoLeadMail($lead));
        } catch (\Throwable) {}

        return response()->json(['ok' => true]);
    }

    public function criarProposta(Request $request, Lead $lead): JsonResponse
    {
        $proposta = Proposta::create([
            'razao_social'        => $lead->company ?: $lead->name,
            'email'               => $lead->email,
            'telefone'            => $lead->phone,
            'regime_tributario'   => $lead->perfil_simulador['regime'] ?? '',
            'honorario_calculado' => 0,
            'honorario_final'     => 0,
            'detalhes'            => $lead->perfil_simulador ?? [],
            'observacoes'         => "Lead: {$lead->name} (#{$lead->id})\n" . ($lead->message ?? ''),
            'validade'            => now()->addDays(15)->toDateString(),
            'status'              => 'rascunho',
            'user_id'             => auth()->id(),
            'lead_id'             => $lead->id,
        ]);

        $lead->update(['status' => 'Qualificado']);

        AuditLog::record('proposta.criada', "Proposta criada a partir do lead #{$lead->id} ({$lead->name})", $proposta);

        return response()->json(['ok' => true, 'proposta_id' => $proposta->id]);
    }

    public function updateStatus(Request $request, Lead $lead): JsonResponse
    {
        $request->validate(['status' => 'required|in:' . implode(',', Lead::statuses())]);

        $lead->update([
            'status'        => $request->status,
            'observacoes'   => $request->observacoes ?? $lead->observacoes,
            'contactado_em' => $lead->contactado_em ?? ($request->status !== 'Novo' ? now() : null),
        ]);

        return response()->json(['ok' => true]);
    }

    public function destroy(Lead $lead): JsonResponse
    {
        $lead->delete();
        return response()->json(['ok' => true]);
    }

    public function storeCalcLead(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'     => 'required|string|max:150',
            'email'    => 'required|email|max:150',
            'phone'    => 'nullable|string|max:20',
            'company'  => 'nullable|string|max:150',
            'total'    => 'required|numeric|min:0',
            'situacao' => 'required|string|max:50',
            'snapshot' => 'nullable|string|max:2000',
        ]);

        $totalFmt = 'R$ ' . number_format($data['total'], 2, ',', '.');

        $lead = Lead::create([
            'name'        => $data['name'],
            'email'       => $data['email'],
            'phone'       => $data['phone'] ?? '',
            'company'     => $data['company'] ?? '',
            'status'      => 'Novo',
            'origem'      => 'calculadora',
            'message'     => "Estimativa calculada: {$totalFmt}/mês",
            'observacoes' => $data['snapshot'] ?? '',
        ]);

        try {
            Mail::to($lead->email)->send(new PropostaCalculadoraMail($lead, $data['total']));
        } catch (\Throwable) {}

        AuditLog::record('lead.calculadora', "Proposta solicitada via calculadora por {$lead->name}", $lead);

        return response()->json(['ok' => true]);
    }
}
