<?php

namespace App\Http\Controllers;

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

class EventWebController extends Controller
{
    /**
     * Liste aller kommenden Veranstaltungen anzeigen
     */
    public function index(Request $request)
    {
        $from = $request->query('from') 
            ? Carbon::parse($request->query('from'))->startOfDay() 
            : now()->startOfDay();
        
        $to = $request->query('to') 
            ? Carbon::parse($request->query('to'))->endOfDay() 
            : now()->addMonths(3)->endOfDay();

        $query = Event::published()
            ->with(['source', 'location', 'occurrences' => function ($q) use ($from, $to) {
                $q->whereBetween('start_datetime', [$from, $to])
                  ->where('status', 'scheduled')
                  ->orderBy('start_datetime');
            }])
            ->whereHas('occurrences', function ($q) use ($from, $to) {
                $q->whereBetween('start_datetime', [$from, $to])
                  ->where('status', 'scheduled');
            });

        // Filter nach Kategorie
        if ($request->filled('category')) {
            $query->byCategory($request->query('category'));
        }

        // Filter nach Ort
        if ($request->filled('location')) {
            $query->byLocation($request->query('location'));
        }

        $events = $query->orderBy('title')->paginate(12);

        // Verfügbare Kategorien und Orte für Filterung
        $categories = Event::published()
            ->whereNotNull('category')
            ->distinct()
            ->pluck('category')
            ->sort()
            ->values();

        $locations = Event::published()
            ->whereNotNull('location_id')
            ->with('location')
            ->get()
            ->pluck('location.city')
            ->filter()
            ->unique()
            ->sort()
            ->values();

        return view('events', compact('events', 'categories', 'locations'));
    }

    /**
     * Detailseite einer einzelnen Veranstaltung anzeigen
     */
    public function show(Event $event)
    {
        // Lade alle Vorkommen der Veranstaltung
        $event->load('occurrences', 'source');

        // Veranstaltung muss veröffentlicht sein
        if (!$event->status || $event->status !== 'published') {
            abort(404);
        }

        return view('event-detail', compact('event'));
    }
}
