<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Event\Models\Event;
use App\Domain\Event\Models\EventRegistration;
use App\Domain\Event\Services\EventRegistrationService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EventController extends Controller
{
    public function show(string $uuid): JsonResponse
    {
        $event = Event::where('uuid', $uuid)
            ->published()
            ->with(['cover', 'gallery'])
            ->firstOrFail();

        return response()->json([
            'data' => [
                'uuid' => $event->uuid,
                'title' => $event->title,
                'title_en' => $event->title_en,
                'description' => $event->description,
                'type' => $event->type->value,
                'status' => $event->status->value,
                'location_type' => $event->location_type->value,
                'location_name' => $event->location_name,
                'location_address' => $event->location_address,
                'starts_at' => $event->starts_at?->toIso8601String(),
                'ends_at' => $event->ends_at?->toIso8601String(),
                'is_registration_open' => $event->isRegistrationOpen(),
                'spots_remaining' => $event->spotsRemaining(),
                'max_capacity' => $event->max_capacity,
                'registrations_count' => $event->registrations_count,
                'cover_url' => $event->cover?->url ?? null,
                'gallery' => $event->gallery->map(fn ($m) => [
                    'url' => $m->url,
                    'caption' => $m->caption ?? null,
                ]),
                'form_fields' => $event->form_fields ?? [],
                'registration_opens_at' => $event->registration_opens_at?->toIso8601String(),
                'registration_closes_at' => $event->registration_closes_at?->toIso8601String(),
            ],
        ]);
    }

    public function register(string $uuid, Request $request, EventRegistrationService $service): JsonResponse
    {
        $event = Event::where('uuid', $uuid)->published()->firstOrFail();

        if (!$event->isRegistrationOpen()) {
            return response()->json([
                'error' => 'registration_closed',
                'message' => 'التسجيل في هذه الفعالية مغلق حالياً',
            ], 422);
        }

        $user = $request->user();

        $existing = EventRegistration::where('event_id', $event->id)
            ->where('person_id', $user->person_id)
            ->whereNotIn('status', ['cancelled'])
            ->first();

        if ($existing) {
            return response()->json([
                'error' => 'already_registered',
                'message' => 'أنت مسجل بالفعل في هذه الفعالية',
                'registration_number' => $existing->registration_number,
            ], 422);
        }

        $request->validate([
            'form_data' => 'nullable|array',
        ]);

        try {
            $registration = $service->register($event, $request->form_data ?? [], [
                'person_id' => $user->person_id,
                'registrant_name' => $user->name_ar ?? $user->name,
                'registrant_phone' => $user->phone,
                'registrant_email' => $user->email,
                'ip_address' => $request->ip(),
                'source' => 'mobile_app',
            ]);

            return response()->json([
                'success' => true,
                'message' => 'تم التسجيل بنجاح',
                'data' => [
                    'registration_number' => $registration->registration_number,
                    'status' => $registration->status->value,
                ],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'error' => 'registration_failed',
                'message' => $e->getMessage() ?: 'فشل في التسجيل، يرجى المحاولة لاحقاً',
            ], 422);
        }
    }

    public function myRegistrations(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->person_id) {
            return response()->json(['data' => []]);
        }

        $registrations = EventRegistration::where('person_id', $user->person_id)
            ->with(['event:id,uuid,title,title_en,starts_at,ends_at,status'])
            ->orderByDesc('created_at')
            ->paginate(15);

        return response()->json([
            'data' => $registrations->map(fn ($r) => [
                'registration_number' => $r->registration_number,
                'status' => $r->status->value,
                'event' => $r->event ? [
                    'uuid' => $r->event->uuid,
                    'title' => $r->event->title,
                    'title_en' => $r->event->title_en,
                    'starts_at' => $r->event->starts_at?->toIso8601String(),
                    'ends_at' => $r->event->ends_at?->toIso8601String(),
                ] : null,
                'registered_at' => $r->created_at?->toIso8601String(),
                'confirmed_at' => $r->confirmed_at?->toIso8601String(),
            ]),
            'meta' => [
                'current_page' => $registrations->currentPage(),
                'last_page' => $registrations->lastPage(),
                'per_page' => $registrations->perPage(),
                'total' => $registrations->total(),
            ],
        ]);
    }
}
