<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use Illuminate\Http\Request;

class LeadController extends Controller
{
    public function index(Request $request)
    {
        $query = Lead::query();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('area', 'like', "%{$search}%");
            });
        }

        $allLeads = $query->orderBy('created_at', 'desc')->get();

        $pipelineValue = $allLeads->sum('mrr_projected');
        $inFunnelCount = $allLeads->count();
        $hotLeadsCount = $allLeads->whereIn('status', ['Qualified', 'Site survey'])->count();
        $convertedCount = $allLeads->where('status', 'Converted')->count();
        $conversionRate = $inFunnelCount > 0 ? round(($convertedCount / $inFunnelCount) * 100, 1) : 0;

        $leadsByStatus = [
            'New' => $allLeads->where('status', 'New'),
            'Contacted' => $allLeads->where('status', 'Contacted'),
            'Qualified' => $allLeads->where('status', 'Qualified'),
            'Site survey' => $allLeads->where('status', 'Site survey'),
            'Converted' => $allLeads->where('status', 'Converted'),
        ];

        return view('admin.leads.index', compact(
            'allLeads',
            'leadsByStatus',
            'pipelineValue',
            'inFunnelCount',
            'hotLeadsCount',
            'conversionRate'
        ));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:50',
            'email' => 'nullable|email',
            'address' => 'nullable|string',
            'area' => 'nullable|string',
            'plan_interested' => 'nullable|string',
            'mrr_projected' => 'nullable|numeric|min:0',
            'status' => 'required|in:New,Contacted,Qualified,Site survey,Converted',
        ]);

        Lead::create($validated);

        return redirect()->route('admin.leads.index')->with('success', 'New sales lead added to pipeline!');
    }

    public function updateStatus(Request $request, Lead $lead)
    {
        $lead->update(['status' => $request->status]);
        return redirect()->route('admin.leads.index')->with('success', "Lead status moved to {$request->status}");
    }
}
