<?php

declare(strict_types=1);

namespace App\Http\Controllers\Account;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use App\Models\TicketReply;
use App\Models\User;
use App\Notifications\TicketCreatedNotification;
use App\Notifications\TicketCustomerReplyNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
use Inertia\Inertia;
use Inertia\Response;

class TicketController extends Controller
{
    public function index(Request $request): Response
    {
        $tickets = SupportTicket::query()
            ->where('user_id', $request->user()->id)
            ->latest('updated_at')
            ->paginate(15)
            ->withQueryString();

        return Inertia::render('Tickets/Index', [
            'tickets' => $tickets,
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Tickets/Create');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'subject' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string', 'min:10', 'max:5000'],
            'priority' => ['required', 'in:low,medium,high,urgent'],
            'department' => ['required', 'in:billing,technical,sales,general'],
        ]);

        $ticket = SupportTicket::query()->create([
            'user_id' => $request->user()->id,
            'subject' => $validated['subject'],
            'status' => 'open',
            'priority' => $validated['priority'],
            'department' => $validated['department'],
            'last_reply_at' => now(),
        ]);

        TicketReply::query()->create([
            'ticket_id' => $ticket->id,
            'user_id' => $request->user()->id,
            'body' => $validated['message'],
            'is_staff_reply' => false,
        ]);

        // Notify all admins about the new ticket
        $admins = User::role('admin')->get();
        Notification::send($admins, new TicketCreatedNotification($ticket));

        return redirect()->route('account.tickets.show', $ticket)
            ->with('success', 'Support ticket created successfully.');
    }

    public function show(Request $request, SupportTicket $ticket): Response
    {
        abort_unless($ticket->user_id === $request->user()->id, 403);

        $ticket->load(['replies.user:id,name,email', 'user:id,name,email']);

        return Inertia::render('Tickets/Show', [
            'ticket' => $ticket,
        ]);
    }

    public function reply(Request $request, SupportTicket $ticket): RedirectResponse
    {
        abort_unless($ticket->user_id === $request->user()->id, 403);
        abort_if($ticket->status === 'closed', 403, 'Cannot reply to a closed ticket.');

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

        $reply = TicketReply::query()->create([
            'ticket_id' => $ticket->id,
            'user_id' => $request->user()->id,
            'body' => $validated['body'],
            'is_staff_reply' => false,
        ]);

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

        // Notify all admins about the customer reply
        $admins = User::role('admin')->get();
        Notification::send($admins, new TicketCustomerReplyNotification($ticket, $reply));

        return redirect()->back()->with('success', 'Reply added successfully.');
    }

    public function close(Request $request, SupportTicket $ticket): RedirectResponse
    {
        abort_unless($ticket->user_id === $request->user()->id, 403);

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

        return redirect()->back()->with('success', 'Ticket has been closed.');
    }
}
