<?php

namespace App\Http\Controllers;

use App\Models\MeetupEvent;
use App\Models\MexcoNotificationLog;
use App\Models\MexcoNotificationTemplate;
use App\Models\MexcoOrganisation;
use App\Models\MexcoOrganiserNotice;
use App\Services\OrganiserNoticeService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MexcoSuperAdminNotificationController extends Controller
{
    public function __construct(private OrganiserNoticeService $notices) {}

    public function index(): View
    {
        $templates = MexcoNotificationTemplate::query()->orderBy('code')->get();
        $recentLogs = MexcoNotificationLog::query()
            ->with('template')
            ->orderByDesc('created_at')
            ->limit(20)
            ->get();
        $organiserNotices = MexcoOrganiserNotice::query()
            ->with(['organisation', 'event', 'creator'])
            ->orderByDesc('published_at')
            ->limit(20)
            ->get();
        $organisations = MexcoOrganisation::query()->orderBy('name')->get(['id', 'name']);
        $events = MeetupEvent::query()->orderBy('name')->get(['id', 'name', 'event_name', 'short_name']);

        return view('super-admin.notifications.index', compact(
            'templates',
            'recentLogs',
            'organiserNotices',
            'organisations',
            'events',
        ));
    }

    public function storeOrganiserNotice(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'title' => 'required|string|max:180',
            'body' => 'required|string|max:5000',
            'audience' => 'required|in:all,organisation,event',
            'organisation_id' => 'nullable|integer|exists:mexco_organisations,id',
            'event_id' => 'nullable|string|exists:meetup_events,id',
        ]);

        if ($data['audience'] === 'organisation' && empty($data['organisation_id'])) {
            return back()->withInput()->with('error', 'Choose an organisation for this notice.');
        }

        if ($data['audience'] === 'event' && empty($data['event_id'])) {
            return back()->withInput()->with('error', 'Choose an event for this notice.');
        }

        if ($data['audience'] === 'all') {
            $data['organisation_id'] = null;
            $data['event_id'] = null;
        } elseif ($data['audience'] === 'organisation') {
            $data['event_id'] = null;
        } else {
            $data['organisation_id'] = null;
        }

        $adminId = $request->session()->get('meetup_super_admin_id');
        $this->notices->publish($data, $adminId ? (int) $adminId : null);

        return redirect()->route('mexco.super.notifications')
            ->with('success', 'Notice sent to organiser inboxes.');
    }

    public function logs(Request $request): View
    {
        $status = $request->input('status', '');

        $logs = MexcoNotificationLog::query()
            ->with('template')
            ->when($status, fn ($q) => $q->where('status', $status))
            ->orderByDesc('created_at')
            ->paginate(50);

        return view('super-admin.notifications.logs', compact('logs', 'status'));
    }

    public function edit(MexcoNotificationTemplate $template): View
    {
        return view('super-admin.notifications.form', compact('template'));
    }

    public function update(Request $request, MexcoNotificationTemplate $template): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'is_active' => 'nullable|boolean',
        ]);

        $template->update([
            'name' => $data['name'],
            'subject' => $data['subject'],
            'body' => $data['body'],
            'is_active' => $request->boolean('is_active'),
        ]);

        return redirect()->route('mexco.super.notifications')
            ->with('success', 'Template updated.');
    }
}
