<?php

namespace App\Http\Controllers\Api;

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

class LeadController extends Controller
{
    public function store(Request $request)
    {
        try {
            // Validação
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'person_name' => 'required|string|max:255',
                'person_email' => 'nullable|email',
                'person_phone' => 'nullable|string',
                'lead_value' => 'nullable|numeric',
                'description' => 'nullable|string',
                'lead_pipeline_stage_id' => 'nullable|integer|exists:lead_pipeline_stages,id', // Nova validação
            ]);

            // Inicia transação
            DB::beginTransaction();

            // 1. Busca ou cria a pessoa
            $personId = null;
            
            if (!empty($validated['person_email'])) {
                // Busca pessoa existente pelo email
                $existingPerson = DB::table('persons')
                    ->where('emails', 'like', '%' . $validated['person_email'] . '%')
                    ->first();
                
                if ($existingPerson) {
                    $personId = $existingPerson->id;
                }
            }

            // Se não encontrou pessoa, cria uma nova
            if (!$personId) {
                $personEmails = !empty($validated['person_email']) 
                    ? json_encode([['value' => $validated['person_email'], 'label' => 'work']])
                    : json_encode([]);
                
                $personPhones = !empty($validated['person_phone'])
                    ? json_encode([['value' => $validated['person_phone'], 'label' => 'work']])
                    : json_encode([]);

                $personId = DB::table('persons')->insertGetId([
                    'name' => $validated['person_name'],
                    'emails' => $personEmails,
                    'contact_numbers' => $personPhones,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            // 2. Cria o lead
            $leadId = DB::table('leads')->insertGetId([
                'title' => $validated['title'],
                'description' => $validated['description'] ?? '',
                'lead_value' => $validated['lead_value'] ?? 0,
                'status' => 1,
                'person_id' => $personId,
                'user_id' => 1,
                'lead_pipeline_id' => 1,
                'lead_pipeline_stage_id' => $validated['lead_pipeline_stage_id'] ?? 1, // Usa o valor enviado ou padrão (2)
                'lead_source_id' => 1,
                'lead_type_id' => 1,
                'expected_close_date' => null,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            // Commit da transação
            DB::commit();

            // Busca o lead criado com a pessoa
            $lead = DB::table('leads')
                ->join('persons', 'leads.person_id', '=', 'persons.id')
                ->where('leads.id', $leadId)
                ->select('leads.*', 'persons.name as person_name', 'persons.emails as person_emails')
                ->first();

            return response()->json([
                'success' => true,
                'message' => 'Lead criado com sucesso',
                'data' => [
                    'lead_id' => $lead->id,
                    'title' => $lead->title,
                    'person_id' => $personId,
                    'person_name' => $lead->person_name,
                    'lead_value' => $lead->lead_value,
                    'lead_pipeline_stage_id' => $lead->lead_pipeline_stage_id,
                ]
            ], 201);

        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Erro de validação',
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            DB::rollBack();
            
            \Log::error('Erro ao criar lead via API', [
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Erro ao criar lead',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function index()
    {
        try {
            $leads = DB::table('leads')
                ->join('persons', 'leads.person_id', '=', 'persons.id')
                ->select(
                    'leads.id',
                    'leads.title',
                    'leads.lead_value',
                    'leads.created_at',
                    'persons.name as person_name',
                    'persons.emails as person_emails'
                )
                ->orderBy('leads.created_at', 'desc')
                ->limit(50)
                ->get();
            
            return response()->json([
                'success' => true,
                'count' => $leads->count(),
                'data' => $leads
            ], 200);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Erro ao listar leads: ' . $e->getMessage()
            ], 500);
        }
    }
}
