<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\User;
use App\Models\AuditLog;
use Illuminate\Http\Request;

class LeadAdminController extends Controller
{
    public function index(Request $request)
    {
        $query = Lead::with('assignee', 'vehicle', 'auctionVehicle');

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

        $leads = $query->orderBy('created_at', 'desc')->paginate(15)->withQueryString();
        $staffMembers = User::whereIn('role', ['super_admin', 'admin', 'sales_manager', 'auction_manager'])->get();

        $stats = [
            'new' => Lead::where('status', 'new')->count(),
            'contacted' => Lead::where('status', 'contacted')->count(),
            'interested' => Lead::where('status', 'interested')->count(),
            'converted' => Lead::where('status', 'converted')->count(),
        ];

        return view('admin.leads.index', compact('leads', 'staffMembers', 'stats'));
    }

    public function update(Request $request, string $id)
    {
        $lead = Lead::findOrFail($id);

        $validated = $request->validate([
            'status' => 'required|in:new,contacted,interested,follow_up,converted,lost',
            'assigned_to' => 'nullable|exists:users,id',
            'sales_notes' => 'nullable|string|max:2000',
        ]);

        $lead->update(array_merge($validated, [
            'last_contacted_at' => now(),
        ]));

        AuditLog::record('admin_updated_lead', $lead);

        return back()->with('success', 'Lead status and sales notes updated.');
    }
}
