<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Event;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EventController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'from' => 'required|date',
            'to' => 'required|date|after_or_equal:from',
        ]);

        $events = $request->user()->events()
            ->with('contacts')
            ->where(function ($q) use ($request) {
                $q->whereBetween('starts_at', [$request->from, $request->to])
                  ->orWhereBetween('ends_at', [$request->from, $request->to])
                  ->orWhere(function ($q2) use ($request) {
                      $q2->where('starts_at', '<=', $request->from)
                          ->where('ends_at', '>=', $request->to);
                  });
            })
            ->orderBy('starts_at')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $events,
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title'                => 'required|string|max:255',
            'starts_at'            => 'required_without:start_date|date',
            'ends_at'              => 'nullable|date|after_or_equal:starts_at',
            'start_date'           => 'required_without:starts_at|date',
            'end_date'             => 'nullable|date|after_or_equal:start_date',
            'is_all_day'           => 'boolean',
            'notes'                => 'nullable|string',
            'color'                => 'nullable|string|max:7',
            'reminders'              => 'nullable|array',
            'reminders.*.type'       => 'required|in:before,time_of_day,day_before,specific',
            'reminders.*.minutes'    => 'nullable|integer|min:1',
            'reminders.*.time'       => 'nullable|date_format:H:i',
            'reminders.*.datetime'   => 'nullable|date',
            'recurrence'             => 'nullable|in:daily,weekly,monthly,yearly',
            'recurrence_end_date'    => 'nullable|date',
            'attendee_ids'           => 'nullable|array',
            'attendee_ids.*'         => 'uuid|exists:contacts,id',
        ]);

        $event = $request->user()->events()->create($validated);
        $event->contacts()->sync($request->attendee_ids ?? []);

        return response()->json([
            'success' => true,
            'data' => $event->load('contacts'),
            'message' => 'Termin erstellt.',
        ], 201);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        $event = $request->user()->events()->findOrFail($id);

        $validated = $request->validate([
            'title'                => 'sometimes|string|max:255',
            'starts_at'            => 'sometimes|date',
            'ends_at'              => 'nullable|date|after_or_equal:starts_at',
            'start_date'           => 'sometimes|date',
            'end_date'             => 'nullable|date|after_or_equal:start_date',
            'is_all_day'           => 'boolean',
            'notes'                => 'nullable|string',
            'color'                => 'nullable|string|max:7',
            'reminders'              => 'nullable|array',
            'reminders.*.type'       => 'required|in:before,time_of_day,day_before,specific',
            'reminders.*.minutes'    => 'nullable|integer|min:1',
            'reminders.*.time'       => 'nullable|date_format:H:i',
            'reminders.*.datetime'   => 'nullable|date',
            'recurrence'             => 'nullable|in:daily,weekly,monthly,yearly',
            'recurrence_end_date'    => 'nullable|date',
            'attendee_ids'           => 'nullable|array',
            'attendee_ids.*'         => 'uuid|exists:contacts,id',
        ]);

        $event->update($validated);

        if ($request->has('attendee_ids')) {
            $event->contacts()->sync($request->attendee_ids ?? []);
        }

        return response()->json([
            'success' => true,
            'data' => $event->fresh()->load('contacts'),
            'message' => 'Termin aktualisiert.',
        ]);
    }

    public function destroy(Request $request, string $id): JsonResponse
    {
        $event = $request->user()->events()->findOrFail($id);
        $event->delete();

        return response()->json([
            'success' => true,
            'data' => null,
            'message' => 'Termin gelöscht.',
        ]);
    }
}
