<?php

namespace App\Http\Controllers;

use App\Models\Event;
use App\Models\EventReservation;
use Illuminate\Http\Request;

class EventController extends Controller
{
    /**
     * Display a listing of upcoming events.
     */
    public function index(Request $request)
    {
        $query = Event::where('status', 'upcoming')
            ->where('event_date', '>=', now());

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Filter by type
        if ($request->filled('type') && $request->type !== 'all') {
            $query->where('type', $request->type);
        }

        $events = $query->orderBy('event_date', 'asc')->paginate(12);

        return view('events.index', compact('events'));
    }

    /**
     * Display the specified event.
     */
    public function show(Event $event)
    {
        $event->load('reservations');
        return view('events.show', compact('event'));
    }

    /**
     * Make a reservation for an event.
     */
    public function reserve(Request $request, Event $event)
    {
        // Check if user is authenticated
        if (!auth()->check()) {
            return redirect()->route('login')
                ->with('error', 'Please login to make a reservation.');
        }

        // Check if event is upcoming
        if ($event->status !== 'upcoming') {
            return back()->with('error', 'This event is not available for reservation.');
        }

        // Check if event date has passed
        if ($event->event_date < now()->toDateString()) {
            return back()->with('error', 'This event has already passed.');
        }

        // Validate number of guests
        $validated = $request->validate([
            'number_of_guests' => ['required', 'integer', 'min:1'],
        ]);

        $numberOfGuests = $validated['number_of_guests'];

        // Check if user already has a reservation
        $existingReservation = $event->reservations()
            ->where('user_id', auth()->id())
            ->wherePivot('status', 'confirmed')
            ->first();

        if ($existingReservation) {
            return back()->with('error', 'You already have a reservation for this event.');
        }

        // Check if enough spots available
        if ($event->availableSpots() < $numberOfGuests) {
            return back()->with('error', 'Not enough available spots for ' . $numberOfGuests . ' guests.');
        }

        // Create reservation
        $event->reservations()->attach(auth()->id(), [
            'number_of_guests' => $numberOfGuests,
            'status' => 'confirmed',
        ]);

        return back()->with('success', 'Reservation confirmed! We look forward to seeing you.');
    }

    /**
     * Cancel a reservation.
     */
    public function cancelReservation(Event $event)
    {
        $reservation = $event->reservations()
            ->where('user_id', auth()->id())
            ->wherePivot('status', 'confirmed')
            ->first();

        if (!$reservation) {
            return back()->with('error', 'No active reservation found.');
        }

        // Update reservation status
        $event->reservations()->updateExistingPivot(auth()->id(), [
            'status' => 'cancelled',
        ]);

        return back()->with('success', 'Reservation cancelled successfully.');
    }

    /**
     * Display user's reservations.
     */
    public function myReservations()
    {
        $reservations = EventReservation::with('event')
            ->where('user_id', auth()->id())
            ->where('status', 'confirmed')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('events.my-reservations', compact('reservations'));
    }
}
