all(), [ 'name' => 'required|string|max:255', 'phone' => 'required|string|max:255', 'email' => 'sometimes|nullable|email|max:255', 'company' => 'sometimes|nullable|string|max:255', 'details' => 'sometimes|nullable|string', ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'message' => $validator->errors()->first(), 'errors' => $validator->errors(), ], 422); } $user = Auth::user(); $lead = new Lead(); $lead->first_name = $request->input('name'); $lead->phone = $request->input('phone'); $lead->email = $request->input('email'); $lead->lead_company = $request->input('company'); $lead->description = $request->input('details'); $lead->lead_source_id = $this->leadSourceId(); $lead->created_by = $user->id; $lead->company_id = $user->company_id; $lead->changeOwnerTo($user); $lead->save(); return response()->json([ 'success' => true, 'message' => 'Lead saved successfully.', 'today_count' => $this->todayLeadCount(), 'user_count' => $this->userLeadCount(), 'data' => $lead->only([ 'id', 'first_name', 'full_name', 'phone', 'email', 'lead_company', 'description', 'lead_source_id', 'owned_by_type', 'owned_by_id', 'created_at', ]), ]); } /** * Return today's lead counters straight from the database. */ public function count() { return response()->json([ 'success' => true, 'today_count' => $this->todayLeadCount(), 'user_count' => $this->userLeadCount(), ]); } /** * Resolve (or create) the "Techne Summit" lead source for the user's company. */ protected function leadSourceId(): ?int { $source = LeadSource::where('name', 'Techne Summit')->first(); if ($source) { return $source->id; } $source = LeadSource::create([ 'name' => 'Techne Summit', 'company_id' => Auth::user()->company_id, ]); return $source->id; } /** * All leads created today (within the current company scope). */ protected function todayLeadCount(): int { return Lead::where('lead_source_id', $this->leadSourceId()) ->count(); } /** * Leads created today by the authenticated user. */ protected function userLeadCount(): int { return Lead::where('lead_source_id', $this->leadSourceId()) ->where([ 'owned_by_type' => get_class(Auth::user()), 'owned_by_id' => Auth::id(), ]) ->count(); } }