// REPLACE THIS METHOD in app/Http/Controllers/Api/ExpertTicketController.php // Replace lines 29-69 public function index(Request $request) { $userId = $request->user()->id; // Optimized query: Only load necessary relationships and use counts $tickets = ExpertTicket::where('user_id', $userId) ->with([ 'cv:id,title', 'expert:id,name,avatar' ]) ->withCount([ 'drafts', 'messages as unread_messages_count' => function ($query) use ($userId) { $query->where('sender_id', '!=', $userId) ->where('is_read', false); } ]) ->select([ 'id', 'ticket_number', 'cv_id', 'user_id', 'expert_id', 'status', 'priority', 'eta', 'notes', 'assigned_at', 'completed_at', 'created_at' ]) ->latest() ->paginate(15); return response()->json([ 'success' => true, 'data' => $tickets->map(function ($ticket) { // Get latest draft status efficiently $latestDraft = $ticket->drafts_count > 0 ? ExpertDraft::where('ticket_id', $ticket->id) ->select('status') ->latest() ->first() : null; // Check if review exists efficiently $hasReview = ExpertReview::where('ticket_id', $ticket->id)->exists(); return [ 'id' => $ticket->id, 'ticket_number' => $ticket->ticket_number, 'cv_id' => $ticket->cv_id, 'cv_title' => $ticket->cv?->title, 'status' => $ticket->status, 'priority' => $ticket->priority, 'expert' => $ticket->expert ? [ 'id' => $ticket->expert->id, 'name' => $ticket->expert->name, 'avatar' => $ticket->expert->avatar, ] : null, 'eta' => $ticket->eta, 'notes' => $ticket->notes, 'unread_messages' => $ticket->unread_messages_count, 'draft_count' => $ticket->drafts_count, 'latest_draft_status' => $latestDraft?->status, 'has_review' => $hasReview, 'assigned_at' => $ticket->assigned_at, 'completed_at' => $ticket->completed_at, 'created_at' => $ticket->created_at, ]; }), 'pagination' => [ 'total' => $tickets->total(), 'per_page' => $tickets->perPage(), 'current_page' => $tickets->currentPage(), 'last_page' => $tickets->lastPage(), ], ]); }