<?php

namespace App\Http\Controllers;

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

class EventController extends Controller
{
    public function index()
    {
        $events = Event::where('event_date', '>=', now()->toDateString())
            ->orderBy('event_date', 'asc')
            ->get();
            
        return view('pages.events', compact('events'));
    }

    public function create()
    {
        return view('pages.event-create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'location' => 'nullable|string|max:255',
            'event_date' => 'required|date',
            'event_time' => 'nullable',
            'image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:5120',
        ]);

        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('events', 'public');
        }

        Event::create([
            'title' => $request->title,
            'description' => $request->description,
            'location' => $request->location,
            'event_date' => $request->event_date,
            'event_time' => $request->event_time,
            'image_path' => $imagePath,
        ]);

        \Illuminate\Support\Facades\Log::info('Event created: ' . $request->title);

        return redirect()->route('events')->with('success', 'Event created successfully.');
    }

    public function destroy(Event $event)
    {
        if ($event->image_path) {
            \Illuminate\Support\Facades\Storage::disk('public')->delete($event->image_path);
        }

        $event->delete();

        return redirect()->route('events')->with('success', 'Event deleted successfully.');
    }
}
