<?php

namespace App\Http\Controllers;

use App\Models\MexcoOrganisation;
use App\Models\MexcoSupportTicket;
use App\Models\MeetupEvent;
use App\Models\MeetupSuperAdmin;
use App\Services\AuditService;
use App\Services\SupportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MexcoSuperAdminSupportController extends Controller
{
    public function __construct(
        private SupportService $support,
        private AuditService $audit,
    ) {}

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

        $tickets = MexcoSupportTicket::query()
            ->with(['organisation', 'event', 'assignee'])
            ->when($status, fn ($q) => $q->where('status', $status))
            ->when($priority, fn ($q) => $q->where('priority', $priority))
            ->orderByDesc('created_at')
            ->get();

        $stats = $this->support->dashboardStats();

        return view('super-admin.support.index', compact('tickets', 'stats', 'status', 'priority'));
    }

    public function create(): View
    {
        return view('super-admin.support.form', [
            'ticket' => null,
            'organisations' => MexcoOrganisation::query()->orderBy('name')->get(),
            'events' => MeetupEvent::query()->orderBy('name')->get(),
            'admins' => MeetupSuperAdmin::query()->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'organisation_id' => 'nullable|exists:mexco_organisations,id',
            'event_id' => 'nullable|exists:meetup_events,id',
            'contact_name' => 'nullable|string|max:255',
            'contact_email' => 'nullable|email|max:255',
            'subject' => 'required|string|max:255',
            'description' => 'required|string',
            'priority' => 'required|in:low,normal,high,urgent',
            'assigned_admin_id' => 'nullable|exists:meetup_super_admins,id',
        ]);

        $ticket = $this->support->createTicket($data);

        $this->audit->log('support.ticket_created', MexcoSupportTicket::class, (string) $ticket->id, null, [
            'ticket_number' => $ticket->ticket_number,
            'subject' => $ticket->subject,
        ]);

        return redirect()->route('mexco.super.support.show', $ticket)
            ->with('success', 'Support ticket '.$ticket->ticket_number.' created.');
    }

    public function show(MexcoSupportTicket $ticket): View
    {
        $ticket->load(['organisation', 'event', 'assignee', 'messages']);
        $admins = MeetupSuperAdmin::query()->orderBy('name')->get();

        return view('super-admin.support.show', compact('ticket', 'admins'));
    }

    public function updateStatus(Request $request, MexcoSupportTicket $ticket): RedirectResponse
    {
        $data = $request->validate([
            'status' => 'required|string',
            'assigned_admin_id' => 'nullable|exists:meetup_super_admins,id',
        ]);

        $old = ['status' => $ticket->status];
        if ($data['assigned_admin_id']) {
            $ticket->update(['assigned_admin_id' => $data['assigned_admin_id']]);
        }

        $this->support->updateStatus($ticket, $data['status'], session('meetup_super_admin_id'));

        $this->audit->log('support.status_changed', MexcoSupportTicket::class, (string) $ticket->id, $old, [
            'status' => $data['status'],
        ]);

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

    public function reply(Request $request, MexcoSupportTicket $ticket): RedirectResponse
    {
        $data = $request->validate(['body' => 'required|string|max:5000']);

        $this->support->addReply($ticket, $data['body'], 'admin', session('meetup_super_admin_id'));

        return back()->with('success', 'Reply added.');
    }
}
