<?php

namespace App\Http\Controllers;

use App\Models\Development;
use App\Models\Lot;
use App\Models\Prospect;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

/**
 * Turns a visitor's interest into a prospect in the CRM.
 *
 * The portal is the top of the funnel, so a person who picks a lot on the plan
 * arrives at the sales desk already attached to that lot and that project.
 */
class PortalLeadController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'project' => ['required', 'string', 'max:180'],
            'lot_id' => ['nullable', 'integer'],
            'name' => ['required', 'string', 'max:140'],
            'phone' => ['required', 'string', 'max:40'],
            'email' => ['nullable', 'email', 'max:180'],
            'message' => ['nullable', 'string', 'max:1000'],
            'consent' => ['accepted'],
            // Left empty by people and filled by bots.
            'website' => ['nullable', 'size:0'],
        ], [
            'name.required' => 'Necesitamos tu nombre para contactarte.',
            'phone.required' => 'Déjanos un teléfono o WhatsApp.',
            'consent.accepted' => 'Necesitamos tu autorización para contactarte.',
        ]);

        $development = Development::query()
            ->where('slug', $validated['project'])
            ->where('published', true)
            ->first();

        if ($development === null) {
            throw ValidationException::withMessages([
                'project' => 'Este desarrollo ya no está disponible.',
            ]);
        }

        $lot = $this->lotFor($development, $validated['lot_id'] ?? null);

        DB::transaction(function () use ($development, $lot, $validated): void {
            $prospect = Prospect::query()->create([
                'name' => $validated['name'],
                'email' => $validated['email'] ?? null,
                'phone' => $validated['phone'],
                'source' => 'portal',
                'stage' => 'nuevo',
                'development_id' => $development->id,
                'lot_id' => $lot?->id,
                'budget' => $lot?->price > 0 ? $lot->price : null,
                'notes' => $validated['message'] ?? null,
            ]);

            $prospect->interactions()->create([
                'channel' => 'nota',
                'stage_to' => 'nuevo',
                'summary' => $lot === null
                    ? "Solicitud de información desde el portal ({$development->name})."
                    : sprintf(
                        'Solicitud desde el portal por el lote %s L-%s de %s.',
                        $lot->block ?? 'sin manzana',
                        $lot->lot_number,
                        $development->name,
                    ),
            ]);
        });

        return back()->with('toast', [
            'type' => 'success',
            'message' => 'Recibimos tu solicitud. Un asesor te contactará en breve.',
        ]);
    }

    /** Only a lot that belongs to the requested project may be attached. */
    private function lotFor(Development $development, ?int $lotId): ?Lot
    {
        if ($lotId === null) {
            return null;
        }

        return $development->lots()->whereKey($lotId)->first();
    }
}
