<?php

namespace App\Http\Controllers\Admin\Event;

use App\Http\Controllers\Controller;
use App\Models\Event;
use App\Models\EventClaim;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class EventController extends Controller
{
    /**
     * Display event management page
     */
    public function index(Request $request)
    {
        $perPage = $request->input('per_page', 10);
        
        $events = Event::with('creator')
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);

        // Add additional data to each event
        $events->getCollection()->transform(function ($event) {
            $event->current_registrations = Event::getCurrentRegistrationCount();
            $event->milestone_reached = $event->isMilestoneReached();
            $event->milestone_user_id = $event->getMilestoneUserId();
            $event->claims_count = EventClaim::where('event_id', $event->id)
                ->whereNotNull('claimed_at')
                ->count();
            return $event;
        });

        $masks = $this->getMasksForSelect();

        return Inertia::render('admin/event/index', [
            'events' => $events,
            'currentRegistrationCount' => Event::getCurrentRegistrationCount(),
            'masks' => $masks,
        ]);
    }

    /**
     * Store a new event
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string|in:registration',
            'milestone' => 'required|integer|min:1',
            'min_level' => 'nullable|integer|min:1|max:150',
            'item_id' => 'required|integer|min:1',
            'item_name' => 'required|string|max:255',
            'item_count' => 'required|integer|min:1',
            'protect_type' => 'nullable|integer',
            'octet' => 'nullable|string',
            'mask' => 'nullable|integer',
            'mail_title' => 'nullable|string|max:255',
            'mail_message' => 'nullable|string',
            'is_active' => 'boolean',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $validated['created_by'] = Auth::user()->ID;
        $validated['is_active'] = $request->boolean('is_active', true);

        Event::create($validated);

        return back()->with('success', 'Event created successfully.');
    }

    /**
     * Update an event
     */
    public function update(Request $request, int $id)
    {
        $event = Event::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string|in:registration',
            'milestone' => 'required|integer|min:1',
            'min_level' => 'nullable|integer|min:1|max:150',
            'item_id' => 'required|integer|min:1',
            'item_name' => 'required|string|max:255',
            'item_count' => 'required|integer|min:1',
            'protect_type' => 'nullable|integer',
            'octet' => 'nullable|string',
            'mask' => 'nullable|integer',
            'mail_title' => 'nullable|string|max:255',
            'mail_message' => 'nullable|string',
            'is_active' => 'boolean',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $validated['is_active'] = $request->boolean('is_active', true);

        $event->update($validated);

        return back()->with('success', 'Event updated successfully.');
    }

    /**
     * Delete an event
     */
    public function destroy(int $id)
    {
        $event = Event::findOrFail($id);
        $event->delete();

        return back()->with('success', 'Event deleted successfully.');
    }

    /**
     * Toggle event active status
     */
    public function toggleStatus(int $id)
    {
        $event = Event::findOrFail($id);
        $event->is_active = !$event->is_active;
        $event->save();

        return back()->with('success', 'Event status updated.');
    }

    /**
     * View claims for an event
     */
    public function claims(Request $request)
    {
        $eventId = $request->input('event_id');
        $perPage = $request->input('per_page', 20);

        $query = EventClaim::with(['event', 'user'])
            ->whereNotNull('claimed_at')
            ->orderBy('claimed_at', 'desc');

        if ($eventId) {
            $query->where('event_id', $eventId);
        }

        $claims = $query->paginate($perPage);

        $events = Event::orderBy('name')->get(['id', 'name']);

        return Inertia::render('admin/event/claims', [
            'claims' => $claims,
            'events' => $events,
            'filters' => [
                'event_id' => $eventId,
                'per_page' => $perPage,
            ],
        ]);
    }

    /**
     * Get masks formatted for select dropdown
     */
    private function getMasksForSelect()
    {
        $masks = config('masks');
        $formatted = [];

        foreach ($masks as $key => $value) {
            if (is_array($value)) {
                // Group
                $formatted[] = [
                    'label' => $key,
                    'options' => array_map(function($k, $v) {
                        return ['value' => $k, 'label' => $v];
                    }, array_keys($value), $value)
                ];
            } else {
                // Single option
                $formatted[] = [
                    'value' => $key,
                    'label' => $value
                ];
            }
        }

        return $formatted;
    }
}
