<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\Meeting;
use App\Models\Opportunity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class LeadController extends Controller
{
    public function index(Request $request): View
    {
        $query = Lead::with(['assignedConsultant', 'affiliate'])->latest();

        if ($request->user()->isAffiliate()) {
            $query->where('affiliate_user_id', $request->user()->id);
        } elseif ($request->user()->isResident()) {
            $query->where('owner_user_id', $request->user()->id);
        }

        return view('app.leads.index', [
            'leads' => $query->paginate(15),
        ]);
    }

    public function show(Request $request, Lead $lead): View
    {
        Gate::authorize('view-lead', $lead);

        $opportunity = Opportunity::where('lead_id', $lead->id)->latest()->first();
        $meetings = collect();

        if ($opportunity) {
            $meetings = Meeting::where('opportunity_id', $opportunity->id)->latest()->get();
        }

        return view('app.leads.show', [
            'lead' => $lead,
            'opportunity' => $opportunity,
            'meetings' => $meetings,
        ]);
    }
}
