<?php

namespace App\Http\Controllers;

use App\Models\SupportReply;
use App\Models\SupportTicket;
use App\Services\SupportNotificationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class SupportController extends Controller
{
    public function create(Request $request): View
    {
        return view('support.create', [
            'categories' => SupportTicket::categories(),
            'priorities' => SupportTicket::priorities(),
            'user' => $request->user(),
        ]);
    }

    public function store(Request $request, SupportNotificationService $notifications): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'subject' => ['required', 'string', 'max:255'],
            'category' => ['required', Rule::in(array_keys(SupportTicket::categories()))],
            'priority' => ['required', Rule::in(array_keys(SupportTicket::priorities()))],
            'message' => ['required', 'string', 'min:10', 'max:5000'],
        ]);

        $ticket = SupportTicket::create($data + [
            'user_id' => $request->user()?->id,
            'status' => SupportTicket::STATUS_OPEN,
        ]);

        $notifications->ticketCreated($ticket);
        $request->session()->put('support.created_ticket_id', $ticket->id);

        return redirect()->route('support.success', $ticket);
    }

    public function success(Request $request, SupportTicket $ticket): View
    {
        abort_unless(
            (int) $request->session()->get('support.created_ticket_id') === $ticket->id
                || ($request->user() && $ticket->user_id === $request->user()->id),
            403
        );

        return view('support.success', compact('ticket'));
    }

    public function myTickets(Request $request): View
    {
        return view('support.my-tickets', [
            'tickets' => $request->user()
                ->supportTickets()
                ->latest()
                ->paginate(12),
        ]);
    }

    public function show(Request $request, SupportTicket $ticket): View
    {
        $this->authorizeTicketOwner($request, $ticket);

        return view('support.show', [
            'ticket' => $ticket->load(['replies.user', 'replies.admin']),
        ]);
    }

    public function reply(Request $request, SupportTicket $ticket): RedirectResponse
    {
        $this->authorizeTicketOwner($request, $ticket);

        if ($ticket->status === SupportTicket::STATUS_CLOSED) {
            return back()->with('error', 'This ticket is closed and cannot receive new replies.');
        }

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

        SupportReply::create([
            'ticket_id' => $ticket->id,
            'user_id' => $request->user()->id,
            'message' => $data['message'],
        ]);

        $ticket->update([
            'status' => SupportTicket::STATUS_PENDING,
        ]);

        return back()->with('success', 'Your reply was added successfully.');
    }

    private function authorizeTicketOwner(Request $request, SupportTicket $ticket): void
    {
        abort_unless($request->user() && $ticket->user_id === $request->user()->id, 403);
    }
}
