<?php

namespace App\Http\Controllers;

use App\Models\Event;
use App\Models\EventParticipant;
use App\Models\Post;
use App\Models\PostMedia;
use App\Http\Resources\EventResource;
use App\Http\Resources\EventDetailResource;
use App\Http\Resources\UserShortResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Carbon\Carbon;

class EventController extends Controller
{
    public function addEvent(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|min:3|max:100',
            'description' => 'nullable|string|max:500',
            'location' => 'required|string',
            'start_datetime' => 'required|date',
            'end_datetime' => 'required|date|after:start_datetime',
            'cover_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'event_url' => 'nullable|url',
            'privacy' => 'required|in:public,private,friends',
            'category' => 'required|in:social,business,education,entertainment,other',
            'allow_guests' => 'sometimes|boolean',
            'require_approval' => 'sometimes|boolean',
            'max_participants' => 'nullable|integer|min:1',
        ]);

        $slug = Str::slug($request->title);
        $existingEvent = Event::where('slug', $slug)->first();
        if ($existingEvent) {
            $slug .= '-' . uniqid();
        }

        // Parse the datetime fields
        $startDatetime = Carbon::parse($request->start_datetime);
        $endDatetime = Carbon::parse($request->end_datetime);

        $eventData = [
            'user_id' => Auth::id(),
            'name' => $request->title,
            'slug' => $slug,
            'description' => $request->description,
            'location' => $request->location,
            'start_date' => $startDatetime->toDateString(),
            'start_time' => $startDatetime->toTimeString(),
            'end_date' => $endDatetime->toDateString(),
            'end_time' => $endDatetime->toTimeString(),
            'event_url' => $request->event_url,
            'type' => $request->privacy ?? 'public',
            'category' => $request->category,
            'allow_guests' => $request->allow_guests ? true : false,
            'require_approval' => $request->require_approval ? true : false,
            'max_participants' => $request->max_participants,
            'event_status' => 'active',
        ];

        if ($request->hasFile('cover_image')) {
            $eventData['cover_image'] = storeMedia($request->file('cover_image'), 'event_covers');
        }

        $event = Event::create($eventData);

        // Auto-register the creator as 'going'
        EventParticipant::create([
            'event_id' => $event->id,
            'user_id' => Auth::id(),
            'event_status' => 'going',
            'is_host' => true
        ]);

        // Create a post for the event
        $this->createEventPost($event, $request);

        // Return web or API response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => __('Api.event_created_successfully'),
                'data' => new EventResource($event),
            ], 200);
        }

        return redirect()->route('events.show', $event->slug)
            ->with('success', __('Api.event_created_successfully'));
    }

    /**
     * Create a post for the event that will appear in the newsfeed
     */
    private function createEventPost($event, $request)
    {
        // Convert privacy level from event to post privacy
        $privacyLevel = $this->convertPrivacyToLevel($request->privacy);

        // Create post text with event details
        $postText = $this->generateEventPostText($event);

        // Create the post
        $post = Post::create([
            'post_type' => 'event',
            'user_id' => Auth::id(),
            'privacy_level' => $privacyLevel,
            'post_text' => $postText,
            'location' => $event->location,
            'media_type' => $request->hasFile('cover_image') ? 1 : 0, // 1 for image, 0 for none
            'event_id' => $event->id,
            'post_category' => 'event',
            'status' => 1, // Active
            'ip_address' => $request->ip(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Add cover image as media if exists
        if ($request->hasFile('cover_image')) {
            PostMedia::create([
                'post_id' => $post->id,
                'user_id' => Auth::id(),
                'image_or_video' => 1, // 1 for image
                'media_path' => $event->cover_image,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        return $post;
    }

    /**
     * Convert event privacy to post privacy level
     */
    private function convertPrivacyToLevel($privacy)
    {
        switch ($privacy) {
            case 'public':
                return 1; // Public
            case 'friends':
                return 2; // Friends only
            case 'private':
                return 3; // Only me
            default:
                return 1; // Default to public
        }
    }

    /**
     * Generate post text for the event
     */
    private function generateEventPostText($event)
    {
        $startDate = Carbon::parse($event->start_date)->format('F j, Y');
        $startTime = Carbon::parse($event->start_time)->format('g:i A');
        $endTime = Carbon::parse($event->end_time)->format('g:i A');

        $postText = "🎉 I'm hosting an event: {$event->name}\n\n";
        $postText .= "📅 Date: {$startDate}\n";
        $postText .= "🕐 Time: {$startTime} - {$endTime}\n";
        $postText .= "📍 Location: {$event->location}\n";

        if ($event->description) {
            $postText .= "\n📝 {$event->description}\n";
        }

        $postText .= "\n#event #{$event->category}";

        return $postText;
    }

    /**
     * Update the post associated with the event
     */
    private function updateEventPost($event, $request)
    {
        // Find the associated post
        $post = Post::where('event_id', $event->id)->first();

        if (!$post) {
            return;
        }

        // Update post text with new event details
        $postText = $this->generateEventPostText($event);

        // Update privacy level if changed
        $privacyLevel = $request->has('privacy') ? $this->convertPrivacyToLevel($request->privacy) : $post->privacy_level;

        // Update post data
        $postData = [
            'post_text' => $postText,
            'location' => $event->location,
            'privacy_level' => $privacyLevel,
            'updated_at' => now(),
        ];

        $post->update($postData);

        // Update media if cover image changed
        if ($request->hasFile('cover_image')) {
            // Remove old media
            PostMedia::where('post_id', $post->id)->delete();

            // Add new cover image as media
            PostMedia::create([
                'post_id' => $post->id,
                'user_id' => Auth::id(),
                'image_or_video' => 1, // 1 for image
                'media_path' => $event->cover_image,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    public function getEvents(Request $request)
    {
        $request->validate([
            'limit' => 'nullable|integer|min:1|max:50',
            'search' => 'nullable|max:100',
            'date_search' => 'nullable|date',
            'filter' => 'nullable|in:events,interested,going,myevents',
            'category' => 'nullable|in:social,business,education,entertainment,other',
            'timeframe' => 'nullable|in:upcoming,ongoing,past',
            'isMe' => 'nullable|boolean',
        ]);

        $userId = Auth::id();
        $limit = $request->input('limit', 10);

        // Search and Date Range
        $search = $request->input('search', null);
        $dateRange = $request->input('date_search', null);
        $category = $request->input('category', null);

        $query = Event::with(['organizer:id,name,avatar', 'participants'])
            ->orderBy('start_date', 'asc');

        // Search functionality
        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhere('location', 'like', "%{$search}%");
            });
        }
        $query->where('end_date', '>=', Carbon::now());
        // Date filtering
        if ($dateRange) {
            $startDate = Carbon::parse($dateRange)->startOfDay();
            $endDate = Carbon::parse($dateRange)->endOfDay();
            $query->whereBetween('start_date', [$startDate, $endDate]);
        }

        // Category filtering
        if ($category) {
            $query->where('category', $category);
        }

        // Filter options
        if ($request->has('filter')) {
            switch ($request->filter) {
                case 'events':
                    $query->where('end_date', '>=', now());
                    break;
                case 'interested':
                    $query->whereHas('participants', function ($q) use ($userId) {
                        $q->where('user_id', $userId)->where('status', 'interested');
                    });
                    break;
                case 'going':
                    $query->whereHas('participants', function ($q) use ($userId) {
                        $q->where('user_id', $userId)->where('status', 'going');
                    });
                    break;
                case 'myevents':
                    $query->where('user_id', $userId);
                    break;
            }
        }

        // Filter by user's own events or not
        if ($request->has('isMe')) {
            if ($request->boolean('isMe')) {
                $query->where('user_id', $userId);
            } else {
                // For "all events" but not including private events unless the user is a participant
                $query->where(function ($q) use ($userId) {
                    $q->where('type', 'public')
                        ->orWhereHas('participants', function ($q2) use ($userId) {
                            $q2->where('user_id', $userId);
                        });
                });
            }
        }

        // Time-based filtering (upcoming, ongoing, past)
        if ($request->has('timeframe')) {
            $today = Carbon::today();
            switch ($request->timeframe) {
                case 'upcoming':
                    $query->where('start_date', '>', $today);
                    break;
                case 'ongoing':
                    $query->where('start_date', '<=', $today)
                        ->where('end_date', '>=', $today);
                    break;
                case 'past':
                    $query->where('end_date', '<', $today);
                    break;
            }
        }

        $events = $query->paginate($limit);

        // Return API response
        return response()->json([
            'status' => 200,
            'message' => __('Api.data_fetched'),
            'data' => EventResource::collection($events),
            'pagination' => [
                'total' => $events->total(),
                'per_page' => $events->perPage(),
                'current_page' => $events->currentPage(),
                'last_page' => $events->lastPage(),
                'total_pages' => $events->lastPage(),
                'from' => $events->firstItem(),
                'to' => $events->lastItem()
            ]
        ], 200);
    }

    public function getEventDetail(Request $request, $slug)
    {
        // Check if the slug is actually a numeric ID
        if (is_numeric($slug)) {
            // Fetch the category by ID first
            $eventDetail = Event::find($slug);
            if ($eventDetail) {
                // If found, use its slug instead
                $slug = $eventDetail->slug;
            }
        }


        $event = Event::with([
            'organizer',
            'participants.user',
            'participants' => function ($q) {
                $q->where('status', 'going');
            }
        ])->where('slug', $slug)->firstOrFail();

        $interestedCount = EventParticipant::where('event_id', $event->id)
            ->where('status', 'interested')
            ->count();

        $goingCount = EventParticipant::where('event_id', $event->id)
            ->where('status', 'going')
            ->count();

        $isUserInterested = EventParticipant::where('event_id', $event->id)
            ->where('user_id', Auth::id())
            ->where('status', 'interested')
            ->exists();

        $isUserGoing = EventParticipant::where('event_id', $event->id)
            ->where('user_id', Auth::id())
            ->where('status', 'going')
            ->exists();

        $isHost = $event->user_id === Auth::id();

        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => __('Api.data_fetched'),
                'data' => new EventDetailResource($event),
            ]);
        }

        return view('front_end.pages.events.event_detail', compact(
            'event',
            'interestedCount',
            'goingCount',
            'isUserInterested',
            'isUserGoing',
            'isHost'
        ));
    }

    public function createInterest(Request $request)
    {
        $request->validate(['event_id' => 'required|exists:events,id']);
        $userId = Auth::id();
        $eventId = $request->event_id;

        $existing = EventParticipant::where([
            'event_id' => $eventId,
            'user_id' => $userId
        ])->first();

        if ($existing) {
            if ($existing->status === 'interested') {
                $existing->delete();
                return response()->json([
                    'message' => __('Api.unmarked_interest'),
                    'event_status' => 'removed'
                ], 200);
            } else {
                $existing->status = 'interested';
                $existing->save();
                return response()->json([
                    'message' => __('Api.marked_as_interested'),
                    'event_status' => 'interested'
                ], 200);
            }
        }

        EventParticipant::create([
            'event_id' => $eventId,
            'user_id' => $userId,
            'event_status' => 'interested'
        ]);

        return response()->json([
            'message' => __('Api.marked_as_interested'),
            'event_status' => 'interested'
        ], 200);
    }

    public function gotoEvent(Request $request)
    {
        $request->validate(['event_id' => 'required|exists:events,id']);
        $userId = Auth::id();
        $eventId = $request->event_id;

        $existing = EventParticipant::where([
            'event_id' => $eventId,
            'user_id' => $userId
        ])->first();

        if ($existing) {
            if ($existing->status === 'going') {
                $existing->delete();
                return response()->json([
                    'message' => __('Api.unmarked_going'),
                    'event_status' => 'removed'
                ], 200);
            } else {
                $existing->status = 'going';
                $existing->save();
                return response()->json([
                    'message' => __('Api.marked_as_going'),
                    'event_status' => 'going'
                ], 200);
            }
        }

        EventParticipant::create([
            'event_id' => $eventId,
            'user_id' => $userId,
            'event_status' => 'going'
        ]);

        return response()->json([
            'message' => __('Api.marked_as_going'),
            'event_status' => 'going'
        ], 200);
    }

    public function joinEvent(Request $request)
    {
        $request->validate(['event_id' => 'required|exists:events,id']);
        $userId = Auth::id();
        $eventId = $request->event_id;

        $event = Event::findOrFail($eventId);
        $existing = EventParticipant::where([
            'event_id' => $eventId,
            'user_id' => $userId
        ])->first();

        // Check if event has reached maximum participants
        if ($event->max_participants) {
            $currentParticipants = EventParticipant::where('event_id', $eventId)
                ->where('status', 'going')
                ->count();

            if ($currentParticipants >= $event->max_participants && !$existing) {
                return response()->json([
                    'message' => __('Api.event_full'),
                    'status' => 400
                ], 400);
            }
        }

        if ($existing) {
            $existing->delete();
            return response()->json([
                'message' => __('Api.unjoined_event'),
                'status' => 200,
                'event_status' => 'removed'
            ], 200);
        }

        $participant = EventParticipant::create([
            'event_id' => $eventId,
            'user_id' => $userId,
            'event_status' => 'going'
        ]);

        // If the event requires approval, set the participant's status accordingly
        if ($event->require_approval) {
            $participant->approved = false;
            $participant->save();

            // Notify event owner of pending approval
            // This would call a notification service or method

            return response()->json([
                'message' => __('Api.joined_event_pending_approval'),
                'status' => 200,
                'event_status' => 'pending'
            ], 200);
        }

        return response()->json([
            'message' => __('Api.joined_event'),
            'status' => 200,
            'event_status' => 'joined'
        ], 200);
    }

    public function deleteEvent(Request $request)
    {
        $request->validate(['event_id' => 'required|exists:events,id']);
        $eventId = $request->event_id;
        $eventModel = new Event;
        $event = $eventModel->findOrFail($eventId);

        if ($event->user_id !== Auth::id()) {
            return response()->json(['message' => __('Api.unauthorized_action')], 403);
        }
        $eventModel->deleteEvent($event);
        return response()->json(['status' => 200, 'message' => __('Api.event_deleted_successfully')], 200);
    }

    public function updateEvent(Request $request)
    {
        $request->validate([
            'event_id' => 'required|exists:events,id',
            'title' => 'sometimes|string|min:3|max:100',
            'description' => 'nullable|string|max:500',
            'location' => 'sometimes|string',
            'start_datetime' => 'sometimes|date',
            'end_datetime' => 'sometimes|date|after:start_datetime',
            'cover_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'event_url' => 'nullable|url',
            'privacy' => 'sometimes|in:public,private,friends',
            'category' => 'sometimes|in:social,business,education,entertainment,other',
            'allow_guests' => 'sometimes|boolean',
            'require_approval' => 'sometimes|boolean',
            'max_participants' => 'nullable|integer|min:1',
            'event_status' => 'sometimes|in:active,cancelled,postponed',
        ]);

        $event = Event::findOrFail($request->event_id);

        if ($event->user_id !== Auth::id()) {
            return response()->json(['message' => __('Api.unauthorized_action')], 403);
        }

        $updateData = [];

        // Only update fields that are present in the request
        if ($request->has('title')) {
            $updateData['name'] = $request->title;

            // Update slug if title changes
            if ($event->name !== $request->title) {
                $slug = Str::slug($request->title);
                $existingEvent = Event::where('slug', $slug)
                    ->where('id', '!=', $event->id)
                    ->first();

                if ($existingEvent) {
                    $slug .= '-' . uniqid();
                }

                $updateData['slug'] = $slug;
            }
        }

        if ($request->has('description')) $updateData['description'] = $request->description;
        if ($request->has('location')) $updateData['location'] = $request->location;
        if ($request->has('event_url')) $updateData['event_url'] = $request->event_url;
        if ($request->has('privacy')) $updateData['type'] = $request->privacy;
        if ($request->has('category')) $updateData['category'] = $request->category;
        if ($request->has('allow_guests')) $updateData['allow_guests'] = $request->allow_guests;
        if ($request->has('require_approval')) $updateData['require_approval'] = $request->require_approval;
        if ($request->has('max_participants')) $updateData['max_participants'] = $request->max_participants;
        if ($request->has('status')) $updateData['status'] = $request->status;

        // Handle datetime fields
        if ($request->has('start_datetime')) {
            $startDatetime = Carbon::parse($request->start_datetime);
            $updateData['start_date'] = $startDatetime->toDateString();
            $updateData['start_time'] = $startDatetime->toTimeString();
        }

        if ($request->has('end_datetime')) {
            $endDatetime = Carbon::parse($request->end_datetime);
            $updateData['end_date'] = $endDatetime->toDateString();
            $updateData['end_time'] = $endDatetime->toTimeString();
        }

        // Handle cover image
        if ($request->hasFile('cover_image')) {
            $updateData['cover_image'] = storeMedia($request->file('cover_image'), 'event_covers');
        }

        $event->update($updateData);

        // Update the associated post
        $this->updateEventPost($event, $request);

        return response()->json([
            'status' => 200,
            'message' => __('Api.event_updated_successfully'),
            'data' => new EventResource($event)
        ], 200);
    }

    /**
     * Get participants for a specific event.
     *
     * @param  int  $eventId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEventParticipants($eventId)
    {
        $event = Event::with('participants.user')->find($eventId); // Eager load participants and their users

        if (!$event) {
            return response()->json([
                'status' => 404,
                'message' => __('Api.event_not_found'),
                'data' => null,
            ], 404);
        }

        // Get participants with user information
        $participants = $event->participants;

        return response()->json([
            'status' => 200,
            'message' => __('Api.participants_fetched_successfully'),
            'data' => [
                'event' => new EventResource($event), // Use EventResource for event details
                'participants' => UserShortResource::collection($participants->pluck('user')), // Use UserShortResource for participant information
            ],
        ]);
    }

    public function approveParticipant(Request $request)
    {
        $request->validate([
            'participant_id' => 'required|exists:event_participants,id',
        ]);

        $participant = EventParticipant::findOrFail($request->participant_id);
        $event = Event::findOrFail($participant->event_id);

        // Only the event owner can approve participants
        if ($event->user_id !== Auth::id()) {
            return response()->json(['message' => __('Api.unauthorized_action')], 403);
        }

        $participant->approved = true;
        $participant->save();

        // Notify the participant that they've been approved
        // This would call a notification service

        return response()->json([
            'message' => __('Api.participant_approved'),
            'status' => 200
        ]);
    }

    public function rejectParticipant(Request $request)
    {
        $request->validate([
            'participant_id' => 'required|exists:event_participants,id',
        ]);

        $participant = EventParticipant::findOrFail($request->participant_id);
        $event = Event::findOrFail($participant->event_id);

        // Only the event owner can reject participants
        if ($event->user_id !== Auth::id()) {
            return response()->json(['message' => __('Api.unauthorized_action')], 403);
        }

        $participant->delete();

        // Notify the participant that they've been rejected
        // This would call a notification service

        return response()->json([
            'message' => __('Api.participant_rejected'),
            'status' => 200
        ]);
    }

    public function getEventsByCategory(Request $request, $category)
    {
        $request->validate([
            'limit' => 'sometimes|integer|min:1|max:50',
        ]);

        $limit = $request->input('limit', 10);

        $events = Event::where('category', $category)
            ->where('type', 'public')
            ->where('end_date', '>=', now())
            ->orderBy('start_date', 'asc')
            ->paginate($limit);

        return response()->json([
            'status' => 200,
            'message' => __('Api.data_fetched'),
            'data' => EventResource::collection($events),
            'pagination' => [
                'total' => $events->total(),
                'per_page' => $events->perPage(),
                'current_page' => $events->currentPage(),
                'last_page' => $events->lastPage(),
            ]
        ]);
    }

    public function getUpcomingEvents(Request $request)
    {
        $request->validate([
            'limit' => 'sometimes|integer|min:1|max:20',
            'days' => 'sometimes|integer|min:1|max:30',
        ]);

        $limit = $request->input('limit', 5);
        $days = $request->input('days', 7);

        $endDate = Carbon::now()->addDays($days);

        $events = Event::where('type', 'public')
            ->where('start_date', '>=', Carbon::now())
            ->where('start_date', '<=', $endDate)
            ->orderBy('start_date', 'asc')
            ->limit($limit)
            ->get();

        return response()->json([
            'status' => 200,
            'message' => __('Api.data_fetched'),
            'data' => EventResource::collection($events),
        ]);
    }

    /**
     * Get events created by the authenticated user
     */
    public function getMyEvents(Request $request)
    {
        $request->validate([
            'limit' => 'nullable|integer|min:1|max:50',
            'search' => 'nullable|max:100',
            'timeframe' => 'nullable|in:upcoming,ongoing,past',
            'category' => 'nullable|in:social,business,education,entertainment,other',
        ]);

        $userId = Auth::id();
        $limit = $request->input('limit', 10);

        $query = Event::with(['participants'])
            ->where('user_id', $userId)
            ->orderBy('created_at', 'desc');

        // Apply search if provided
        if ($request->has('search')) {

            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhere('location', 'like', "%{$search}%");
            });
        }

        // Apply category filter if provided
        if ($request->has('category')) {
            $query->where('category', $request->input('category'));
        }

        // Apply time-based filtering if provided
        if ($request->has('timeframe')) {
            $today = Carbon::today();
            switch ($request->timeframe) {
                case 'upcoming':
                    $query->where('start_date', '>', $today);
                    break;
                case 'ongoing':
                    $query->where('start_date', '<=', $today)
                        ->where('end_date', '>=', $today);
                    break;
                case 'past':
                    $query->where('end_date', '<', $today);
                    break;
            }
        }

        $events = $query->paginate($limit);

        return response()->json([
            'status' => 200,
            'message' => __('Api.data_fetched'),
            'data' => EventResource::collection($events),
            'pagination' => [
                'total' => $events->total(),
                'per_page' => $events->perPage(),
                'current_page' => $events->currentPage(),
                'last_page' => $events->lastPage(),
                'total_pages' => $events->lastPage(),
                'from' => $events->firstItem(),
                'to' => $events->lastItem()
            ]
        ], 200);
    }

    /**
     * Get events that the authenticated user has shown interest in
     */
    public function getInterestedEvents(Request $request)
    {
        $request->validate([
            'limit' => 'nullable|integer|min:1|max:50',
            'search' => 'nullable|max:100',
            'timeframe' => 'nullable|in:upcoming,ongoing,past',
            'category' => 'nullable|in:social,business,education,entertainment,other',
        ]);

        $userId = Auth::id();
        $limit = $request->input('limit', 10);

        $query = Event::with(['organizer:id,name,avatar', 'participants'])
            ->whereHas('participants', function ($q) use ($userId) {
                $q->where('user_id', $userId)->where('status', 'interested');
            })
            ->orderBy('start_date', 'asc');

        // Apply search if provided
        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhere('location', 'like', "%{$search}%");
            });
        }

        // Apply category filter if provided
        if ($request->has('category')) {
            $query->where('category', $request->input('category'));
        }

        // Apply time-based filtering if provided
        if ($request->has('timeframe')) {
            $today = Carbon::today();
            switch ($request->timeframe) {
                case 'upcoming':
                    $query->where('start_date', '>', $today);
                    break;
                case 'ongoing':
                    $query->where('start_date', '<=', $today)
                        ->where('end_date', '>=', $today);
                    break;
                case 'past':
                    $query->where('end_date', '<', $today);
                    break;
            }
        }

        $events = $query->paginate($limit);

        return response()->json([
            'status' => 200,
            'message' => __('Api.data_fetched'),
            'data' => EventResource::collection($events),
            'pagination' => [
                'total' => $events->total(),
                'per_page' => $events->perPage(),
                'current_page' => $events->currentPage(),
                'last_page' => $events->lastPage(),
                'total_pages' => $events->lastPage(),
                'from' => $events->firstItem(),
                'to' => $events->lastItem()
            ]
        ], 200);
    }

    /**
     * Get suggested events for the authenticated user
     */
    public function getSuggestedEvents()
    {
        try {
            $userId = Auth::id();
            $today = Carbon::today();

            // Get upcoming events that the user hasn't shown interest in yet
            $suggestedEvents = Event::whereNotIn('id', function ($query) use ($userId) {
                $query->select('event_id')
                    ->from('event_participants')
                    ->where('user_id', $userId);
            })
                ->where('user_id', '!=', $userId) // Exclude user's own events
                ->where('start_date', '>=', $today) // Only upcoming events
                ->where('status', 'active') // Only active events
                ->withCount('participants')
                ->orderBy('start_date', 'asc')
                ->limit(5)
                ->get();

            return response()->json([
                'success' => true,
                'events' => $suggestedEvents->map(function ($event) {
                    return [
                        'id' => $event->id,
                        'title' => $event->name,
                        'cover_image' => $event->cover_image,
                        'start_date' => $event->start_date,
                        'location' => $event->location,
                        'participants_count' => $event->participants_count,
                        'category' => $event->category
                    ];
                })
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load suggested events'
            ], 500);
        }
    }
}
