<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\SupportMessage;
use App\Models\SupportTicket;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    /** List all tickets across all organisations, newest activity first. */
    public function index(Request $request)
    {
        $query = SupportTicket::with(['organization:id,name', 'creator:id,name'])
            ->withCount([
                'messages as unread_count' => function ($q) {
                    $q->where('is_platform_reply', false)->whereNull('read_by_admin_at');
                },
            ])
            ->orderByDesc('last_message_at');

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }

        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('subject', 'like', "%{$search}%")
                  ->orWhereHas('organization', fn($o) => $o->where('name', 'like', "%{$search}%"));
            });
        }

        $tickets = $query->paginate(30);

        return response()->json($tickets);
    }

    /** Get a single ticket + all messages; marks org messages as read by admin. */
    public function show(SupportTicket $supportTicket)
    {
        // Mark all unread org messages as read by admin
        SupportMessage::where('ticket_id', $supportTicket->id)
            ->where('is_platform_reply', false)
            ->whereNull('read_by_admin_at')
            ->update(['read_by_admin_at' => now()]);

        $supportTicket->load(['organization:id,name', 'creator:id,name', 'messages.sender:id,name']);

        return response()->json(['data' => $supportTicket]);
    }

    /** Send a reply from the platform admin. */
    public function reply(Request $request, SupportTicket $supportTicket)
    {
        if ($supportTicket->status === 'closed') {
            return response()->json(['message' => 'Ticket is closed.'], 422);
        }

        $validated = $request->validate(['body' => 'required|string|max:5000']);

        $message = SupportMessage::create([
            'ticket_id'         => $supportTicket->id,
            'sender_id'         => $request->user()->id,
            'is_platform_reply' => true,
            'body'              => $validated['body'],
            'read_by_admin_at'  => now(), // sender has read their own
        ]);

        $supportTicket->update(['last_message_at' => now(), 'status' => 'in_progress']);

        return response()->json(['data' => $message->load('sender:id,name')], 201);
    }

    /** Change ticket status (open / in_progress / closed). */
    public function updateStatus(Request $request, SupportTicket $supportTicket)
    {
        $validated = $request->validate([
            'status' => 'required|in:open,in_progress,closed',
        ]);

        $supportTicket->update(['status' => $validated['status']]);

        return response()->json(['data' => $supportTicket]);
    }

    /** Total unread count: org messages not yet seen by admin. */
    public function unreadCount()
    {
        $count = SupportMessage::where('is_platform_reply', false)
            ->whereNull('read_by_admin_at')
            ->count();

        return response()->json(['count' => $count]);
    }

    /** Quick summary stats for the inbox header. */
    public function stats()
    {
        return response()->json([
            'total'       => SupportTicket::count(),
            'open'        => SupportTicket::where('status', 'open')->count(),
            'in_progress' => SupportTicket::where('status', 'in_progress')->count(),
            'closed'      => SupportTicket::where('status', 'closed')->count(),
            'unread'      => SupportMessage::where('is_platform_reply', false)->whereNull('read_by_admin_at')->count(),
        ]);
    }
}
