<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Services\Notification\NotificationDispatcher;
use Illuminate\Http\Request;

class LeadController extends Controller
{
    protected NotificationDispatcher $notifications;

    public function __construct(NotificationDispatcher $notifications)
    {
        $this->notifications = $notifications;
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:25',
            'email' => 'nullable|email|max:255',
            'interested_vehicle' => 'nullable|string|max:255',
            'vehicle_id' => 'nullable|exists:vehicles,id',
            'auction_vehicle_id' => 'nullable|exists:auction_vehicles,id',
            'budget_bdt' => 'nullable|numeric',
            'source' => 'nullable|string',
            'message' => 'nullable|string|max:2000',
        ]);

        $lead = Lead::create([
            'name' => $validated['name'],
            'phone' => $validated['phone'],
            'email' => $validated['email'] ?? null,
            'interested_vehicle' => $validated['interested_vehicle'] ?? null,
            'vehicle_id' => $validated['vehicle_id'] ?? null,
            'auction_vehicle_id' => $validated['auction_vehicle_id'] ?? null,
            'budget_bdt' => $validated['budget_bdt'] ?? null,
            'source' => $validated['source'] ?? 'website_contact',
            'message' => $validated['message'] ?? null,
            'status' => 'new',
        ]);

        // Notify sales managers in admin panel
        $this->notifications->notifyAdmins(
            'New Automotive Inquiry Received',
            "Inquiry from {$lead->name} ({$lead->phone}) for: " . ($lead->interested_vehicle ?? 'General Consultation'),
            route('admin.leads.index')
        );

        if ($request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Thank you! A MotoSolution sales advisor will contact you shortly.',
            ]);
        }

        return back()->with('success', 'Thank you! Your inquiry has been registered in our CRM. A dedicated MotoSolution executive will reach out to you.');
    }
}
