<?php

namespace App\Http\Controllers\Api;

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

class SupportController extends Controller
{
    /** List all tickets belonging to the current organisation. */
    public function index(Request $request)
    {
        $org = $request->user()->organization;

        $tickets = SupportTicket::where('organization_id', $org->id)
            ->with(['creator:id,name'])
            ->withCount([
                'messages as unread_count' => function ($q) {
                    $q->where('is_platform_reply', true)->whereNull('read_by_org_at');
                },
            ])
            ->orderByDesc('last_message_at')
            ->get();

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

    /** Create a new support ticket with an initial message. */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'body'    => 'required|string|max:5000',
        ]);

        $org  = $request->user()->organization;
        $user = $request->user();

        $ticket = SupportTicket::create([
            'organization_id' => $org->id,
            'created_by'      => $user->id,
            'subject'         => $validated['subject'],
            'status'          => 'open',
            'last_message_at' => now(),
        ]);

        SupportMessage::create([
            'ticket_id'         => $ticket->id,
            'sender_id'         => $user->id,
            'is_platform_reply' => false,
            'body'              => $validated['body'],
            'read_by_org_at'    => now(), // sender has "read" their own message
        ]);

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

    /** Get a single ticket and all its messages; marks admin replies as read by org. */
    public function show(Request $request, SupportTicket $supportTicket)
    {
        $this->authorizeOrgTicket($request, $supportTicket);

        // Mark all unread admin replies as read
        SupportMessage::where('ticket_id', $supportTicket->id)
            ->where('is_platform_reply', true)
            ->whereNull('read_by_org_at')
            ->update(['read_by_org_at' => now()]);

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

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

    /** Add a reply from an org user to an existing ticket. */
    public function reply(Request $request, SupportTicket $supportTicket)
    {
        $this->authorizeOrgTicket($request, $supportTicket);

        if ($supportTicket->status === 'closed') {
            return response()->json(['message' => 'This ticket is closed. Please open a new ticket.'], 422);
        }

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

        $message = SupportMessage::create([
            'ticket_id'         => $supportTicket->id,
            'sender_id'         => $request->user()->id,
            'is_platform_reply' => false,
            'body'              => $validated['body'],
            'read_by_org_at'    => now(),
        ]);

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

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

    /** Close a ticket (org-initiated). */
    public function close(Request $request, SupportTicket $supportTicket)
    {
        $this->authorizeOrgTicket($request, $supportTicket);
        $supportTicket->update(['status' => 'closed']);
        return response()->json(['data' => $supportTicket]);
    }

    /** Total count of unread admin-reply messages across all org tickets. */
    public function unreadCount(Request $request)
    {
        $org   = $request->user()->organization;
        $count = SupportMessage::whereHas('ticket', fn($q) => $q->where('organization_id', $org->id))
            ->where('is_platform_reply', true)
            ->whereNull('read_by_org_at')
            ->count();

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

    // ── Helpers ──────────────────────────────────────────────────────────────

    private function authorizeOrgTicket(Request $request, SupportTicket $ticket): void
    {
        $orgId = $request->user()->organization?->id;
        if ($ticket->organization_id !== $orgId) {
            abort(403, 'Access denied.');
        }
    }
}
