<?php

namespace App\Http\Controllers\User;

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

class SupportTicketController extends Controller
{
    public function index()
    {
        $tickets = auth()->user()->tickets()->latest('last_reply_at')->paginate(10);
        return view('user.support', compact('tickets'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'subject' => ['required', 'string', 'max:140'],
            'category' => ['required', 'in:general,offerwall,cashout,account,bug'],
            'priority' => ['required', 'in:low,normal,high'],
            'message' => ['required', 'string', 'max:3000'],
        ]);

        $ticket = auth()->user()->tickets()->create([
            'subject' => $data['subject'],
            'category' => $data['category'],
            'priority' => $data['priority'],
            'status' => 'open',
            'last_reply_at' => now(),
        ]);

        $ticket->messages()->create([
            'user_id' => auth()->id(),
            'message' => $data['message'],
        ]);

        return redirect()->route('user.tickets.show', $ticket)->with('success', 'Ticket created.');
    }

    public function show(SupportTicket $ticket)
    {
        abort_unless($ticket->user_id === auth()->id(), 403);
        $ticket->load('messages.user');
        return view('user.ticket-view', compact('ticket'));
    }

    public function reply(Request $request, SupportTicket $ticket)
    {
        abort_unless($ticket->user_id === auth()->id(), 403);
        $data = $request->validate(['message' => ['required', 'string', 'max:3000']]);

        $ticket->messages()->create([
            'user_id' => auth()->id(),
            'message' => $data['message'],
        ]);

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

        return redirect()->route('user.tickets.show', $ticket)->with('success', 'Reply added.');
    }
}
