<?php

namespace App\Http\Controllers;

use App\Models\MexcoOrganisation;
use App\Models\MexcoOrganisationUser;
use App\Models\MeetupEvent;
use App\Services\OrganisationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MexcoSuperAdminOrganiserController extends Controller
{
    public function __construct(private OrganisationService $organisations) {}

    public function index(Request $request): View
    {
        $q = strtolower(trim($request->input('q', '')));

        $organisers = MexcoOrganisationUser::query()
            ->with(['organisation', 'assignedEvents'])
            ->when($q, fn ($query) => $query->where(function ($sub) use ($q) {
                $sub->where('name', 'like', "%{$q}%")
                    ->orWhere('email', 'like', "%{$q}%");
            }))
            ->orderBy('name')
            ->get();

        return view('super-admin.organisers.index', compact('organisers', 'q'));
    }

    public function create(): View
    {
        return view('super-admin.organisers.form', [
            'organiser' => null,
            'organisations' => MexcoOrganisation::query()->where('status', 'active')->orderBy('name')->get(),
            'events' => MeetupEvent::query()->with('organisation')->orderBy('name')->get(),
            'roles' => MexcoOrganisationUser::roles(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'organisation_id' => 'required|exists:mexco_organisations,id',
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|string|min:6|confirmed',
            'role' => 'required|in:'.implode(',', array_keys(MexcoOrganisationUser::roles())),
            'status' => 'required|in:active,suspended,invited',
            'event_ids' => 'nullable|array',
            'event_ids.*' => 'string|exists:meetup_events,id',
        ]);

        $organisation = MexcoOrganisation::query()->findOrFail($data['organisation_id']);
        $user = $this->organisations->createOrganiser($organisation, $data);

        return redirect()->route('mexco.super.organisers.index')
            ->with('success', 'Organiser '.$user->name.' created.');
    }

    public function edit(MexcoOrganisationUser $organiser): View
    {
        $organiser->load(['organisation', 'assignedEvents']);

        return view('super-admin.organisers.form', [
            'organiser' => $organiser,
            'organisations' => MexcoOrganisation::query()->orderBy('name')->get(),
            'events' => MeetupEvent::query()
                ->where('organisation_id', $organiser->organisation_id)
                ->orderBy('name')
                ->get(),
            'roles' => MexcoOrganisationUser::roles(),
        ]);
    }

    public function update(Request $request, MexcoOrganisationUser $organiser): RedirectResponse
    {
        $data = $request->validate([
            'organisation_id' => 'required|exists:mexco_organisations,id',
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:mexco_organisation_users,email,'.$organiser->id,
            'password' => 'nullable|string|min:6|confirmed',
            'role' => 'required|in:'.implode(',', array_keys(MexcoOrganisationUser::roles())),
            'status' => 'required|in:active,suspended,invited',
            'event_ids' => 'nullable|array',
            'event_ids.*' => 'string|exists:meetup_events,id',
        ]);

        if ($data['organisation_id'] != $organiser->organisation_id) {
            $organiser->update(['organisation_id' => $data['organisation_id']]);
            $organiser = $organiser->fresh();
        }

        $this->organisations->updateOrganiser($organiser, $data);

        return redirect()->route('mexco.super.organisers.index')
            ->with('success', 'Organiser updated.');
    }
}
