<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Event;
use App\Models\EventParticipant;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class EventController extends Controller
{
    /**
     * Display a listing of all events.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $upcomingEvents = Event::upcoming()->where('type', 'public')->with('organizer')->withCount('participants')->get();
        $ongoingEvents = Event::ongoing()->with('organizer')->withCount('participants')->get();
        
        $userId = Auth::id();
        $myEvents = Event::where('user_id', $userId)->with('organizer')->withCount('participants')->get();
        
        return view('front_end.pages.events.all_events', compact('upcomingEvents', 'ongoingEvents', 'myEvents'));
    }
    
    /**
     * Display a listing of events created by the authenticated user.
     *
     * @return \Illuminate\Http\Response
     */
    public function myEvents()
    {
        return view('front_end.pages.events.my_events');
    }
    
    /**
     * Show the form for creating a new event.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('front_end.pages.events.create_event');
    }
    
    /**
     * Store a newly created event in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // All the store logic is in the API controller
        // This method redirects to the API endpoint
        // The frontend JS handles the form submission directly to the API
        
        return redirect()->route('events.show', ['slug' => 'new-event']); // Placeholder, actual redirect happens via JS
    }
    
    /**
     * Display the specified event.
     *
     * @param  string  $slug
     * @return \Illuminate\Http\Response
     */
    public function show($slug)
    {
        $event = Event::with(['organizer', 'participants.user'])
            ->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 = false;
        $isUserGoing = false;
        $isHost = false;
        
        if (Auth::check()) {
            $userId = Auth::id();
            
            $isUserInterested = EventParticipant::where('event_id', $event->id)
                ->where('user_id', $userId)
                ->where('status', 'interested')
                ->exists();
                
            $isUserGoing = EventParticipant::where('event_id', $event->id)
                ->where('user_id', $userId)
                ->where('status', 'going')
                ->exists();
                
            $isHost = $event->user_id === $userId;
        }
        
        $participants = EventParticipant::with('user')
            ->where('event_id', $event->id)
            ->where('status', 'going')
            ->get();
            
        $interestedUsers = EventParticipant::with('user')
            ->where('event_id', $event->id)
            ->where('status', 'interested')
            ->get();
        
        return view('front_end.pages.events.event_detail', compact(
            'event', 
            'interestedCount', 
            'goingCount', 
            'isUserInterested', 
            'isUserGoing',
            'isHost',
            'participants',
            'interestedUsers'
        ));
    }
    
    /**
     * Show the form for editing the specified event.
     *
     * @param  string  $slug
     * @return \Illuminate\Http\Response
     */
    public function edit($slug)
    {
        $event = Event::where('slug', $slug)->firstOrFail();
        
        // Check if user is authorized to edit
        if (Auth::id() !== $event->user_id) {
            return redirect()->route('events.show', $event->slug)
                ->with('error', 'You are not authorized to edit this event.');
        }
        
        return view('front_end.pages.events.edit_event', compact('event'));
    }
    
    /**
     * Update the specified event in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $slug
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $slug)
    {
        // Update logic is in the API controller
        // This is a placeholder for web routes
        
        return redirect()->route('events.show', $slug)
            ->with('success', 'Event updated successfully.');
    }
    
    /**
     * Remove the specified event from storage.
     *
     * @param  string  $slug
     * @return \Illuminate\Http\Response
     */
    public function destroy($slug)
    {
        // Delete logic is in the API controller
        // This is a placeholder for web routes
        
        return redirect()->route('events.index')
            ->with('success', 'Event deleted successfully.');
    }
    
    /**
     * Show events by category.
     *
     * @param  string  $category
     * @return \Illuminate\Http\Response
     */
    public function byCategory($category)
    {
        $events = Event::where('category', $category)
            ->where('type', 'public')
            ->with('organizer')
            ->withCount('participants')
            ->paginate(12);
            
        return view('front_end.pages.events.category', compact('events', 'category'));
    }
    
    /**
     * Show events that the user is attending.
     *
     * @return \Illuminate\Http\Response
     */
    public function attending()
    {
        $userId = Auth::id();
        
        $events = Event::whereHas('participants', function($query) use ($userId) {
                $query->where('user_id', $userId)
                    ->where('status', 'going');
            })
            ->with('organizer')
            ->withCount('participants')
            ->paginate(12);
            
        return view('front_end.pages.events.attending', compact('events'));
    }
    
    /**
     * Show events that the user is interested in.
     *
     * @return \Illuminate\Http\Response
     */
    public function interested()
    {
        $userId = Auth::id();
        
        $events = Event::whereHas('participants', function($query) use ($userId) {
                $query->where('user_id', $userId)
                    ->where('status', 'interested');
            })
            ->with('organizer')
            ->withCount('participants')
            ->paginate(12);
            
        return view('front_end.pages.events.interested', compact('events'));
    }
}
