<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\SupportTicket;
use App\Models\TicketMessage;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class SupportController extends Controller
{
    public function index(Request $request)
    {
        $tickets = SupportTicket::where('user_id', $request->user()->id)
            ->with('lastMessage')
            ->latest()
            ->paginate(15);

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'subject' => ['required', 'string', 'max:255'],
            'category' => ['required', Rule::in(['general', 'payments', 'technical', 'account', 'bonuses', 'responsible_gaming', 'other'])],
            'message' => ['required', 'string', 'max:5000'],
        ]);

        $user = $request->user();

        $ticket = SupportTicket::create([
            'user_id' => $user->id,
            'subject' => $data['subject'],
            'category' => $data['category'],
            'status' => 'open',
            'priority' => 'normal',
        ]);

        TicketMessage::create([
            'ticket_id' => $ticket->id,
            'sender_id' => $user->id,
            'is_admin' => false,
            'message' => $data['message'],
        ]);

        AuditLog::record('ticket_created', $user->id, "Support ticket created: {$ticket->reference}", ['ticket_id' => $ticket->id, 'category' => $data['category']]);

        return response()->json(['message' => 'Ticket submitted.', 'ticket' => [
            'id' => $ticket->id,
            'reference' => $ticket->reference,
            'subject' => $ticket->subject,
            'status' => $ticket->status,
            'created_at' => $ticket->created_at,
        ]], 201);
    }

    public function show(Request $request, SupportTicket $ticket)
    {
        if ($ticket->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Not found.'], 404);
        }

        return response()->json([
            'ticket' => $ticket,
            'messages' => $ticket->messages()->orderBy('created_at')->get()->map(fn($m) => [
                'id' => $m->id,
                'is_admin' => $m->is_admin,
                'message' => $m->message,
                'attachments' => $m->attachments,
                'created_at' => $m->created_at,
            ]),
        ]);
    }

    public function reply(Request $request, SupportTicket $ticket)
    {
        if ($ticket->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Not found.'], 404);
        }

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

        $data = $request->validate([
            'message' => ['required', 'string', 'max:5000'],
        ]);

        $msg = TicketMessage::create([
            'ticket_id' => $ticket->id,
            'sender_id' => $request->user()->id,
            'is_admin' => false,
            'message' => $data['message'],
        ]);

        $ticket->update(['status' => 'open']);

        return response()->json(['message' => 'Reply sent.', 'id' => $msg->id]);
    }
}
