<?php

namespace App\Http\Controllers\Api;

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

class SupportTicketController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $tickets = SupportTicket::with(['order', 'messages' => function ($q) {
            $q->latest();
        }])
            ->where('user_id', $user->id)
            ->orderByDesc('last_message_at')
            ->orderByDesc('id')
            ->get()
            ->map(function (SupportTicket $ticket) {
                $latest = $ticket->messages->sortByDesc('created_at')->first();
                return [
                    'id' => $ticket->id,
                    'subject' => $ticket->subject,
                    'status' => $ticket->status,
                    'priority' => $ticket->priority,
                    'order_id' => $ticket->order_id,
                    'order_number' => optional($ticket->order)->order_number,
                    'created_at' => $ticket->created_at,
                    'last_message_at' => $ticket->last_message_at,
                    'last_message_preview' => $latest ? mb_substr($latest->message, 0, 120) : null,
                    'last_message_is_admin' => $latest ? $latest->is_admin : null,
                ];
            });

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

    public function show(Request $request, $id)
    {
        $user = $request->user();

        $ticket = SupportTicket::with(['order', 'messages' => function ($q) {
            $q->orderBy('created_at', 'asc');
        }])
            ->where('user_id', $user->id)
            ->findOrFail($id);

        return response()->json([
            'status' => 'success',
            'data' => $ticket,
        ]);
    }

    public function store(Request $request)
    {
        $user = $request->user();

        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'message' => 'required|string|max:5000',
            'order_id' => 'nullable|integer|exists:orders,id',
        ]);

        $ticket = SupportTicket::create([
            'user_id' => $user->id,
            'order_id' => $validated['order_id'] ?? null,
            'subject' => $validated['subject'],
            'status' => 'open',
            'priority' => null,
            'last_message_at' => now(),
        ]);

        $message = SupportMessage::create([
            'support_ticket_id' => $ticket->id,
            'user_id' => $user->id,
            'is_admin' => false,
            'message' => $validated['message'],
        ]);

        $ticket->setRelation('messages', collect([$message]));

        return response()->json([
            'status' => 'success',
            'data' => $ticket,
        ], 201);
    }

    public function reply(Request $request, $id)
    {
        $user = $request->user();

        $ticket = SupportTicket::where('user_id', $user->id)->findOrFail($id);

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

        $message = SupportMessage::create([
            'support_ticket_id' => $ticket->id,
            'user_id' => $user->id,
            'is_admin' => false,
            'message' => $validated['message'],
        ]);

        $ticket->last_message_at = now();
        if ($ticket->status === 'closed') {
            $ticket->status = 'open';
        }
        $ticket->save();

        return response()->json([
            'status' => 'success',
            'data' => $message,
        ], 201);
    }
}

