<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
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 SupportTicketController extends Controller
{
    public function index(Request $request): View
    {
        $tickets = SupportTicket::query()
            ->with('user')
            ->when($request->filled('search'), function ($query) use ($request): void {
                $search = $request->string('search');
                $query->where(function ($query) use ($search): void {
                    $query->where('subject', 'like', "%{$search}%")
                        ->orWhere('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%")
                        ->orWhere('message', 'like', "%{$search}%");
                });
            })
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->status))
            ->when($request->filled('category'), fn ($query) => $query->where('category', $request->category))
            ->when($request->filled('priority'), fn ($query) => $query->where('priority', $request->priority))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('admin.support.index', [
            'tickets' => $tickets,
            'statuses' => SupportTicket::statuses(),
            'categories' => SupportTicket::categories(),
            'priorities' => SupportTicket::priorities(),
            'totalTickets' => SupportTicket::count(),
            'openTickets' => SupportTicket::where('status', SupportTicket::STATUS_OPEN)->count(),
            'urgentTickets' => SupportTicket::where('priority', SupportTicket::PRIORITY_URGENT)->count(),
        ]);
    }

    public function show(SupportTicket $ticket): View
    {
        return view('admin.support.show', [
            'ticket' => $ticket->load(['user', 'replies.user', 'replies.admin']),
            'statuses' => SupportTicket::statuses(),
        ]);
    }

    public function reply(Request $request, SupportTicket $ticket, SupportNotificationService $notifications): RedirectResponse
    {
        $data = $request->validate([
            'message' => ['required', 'string', 'min:3', 'max:5000'],
        ]);

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

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

        $notifications->adminReplied($ticket, $reply);

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

    public function updateStatus(Request $request, SupportTicket $ticket): RedirectResponse
    {
        $data = $request->validate([
            'status' => ['required', Rule::in(array_keys(SupportTicket::statuses()))],
        ]);

        $ticket->update($data);

        return back()->with('success', 'Ticket status updated successfully.');
    }

    public function close(SupportTicket $ticket): RedirectResponse
    {
        $ticket->update([
            'status' => SupportTicket::STATUS_CLOSED,
        ]);

        return back()->with('success', 'Ticket closed successfully.');
    }

    public function destroy(SupportTicket $ticket): RedirectResponse
    {
        $ticket->delete();

        return redirect()
            ->route('admin.support.index')
            ->with('success', 'Ticket deleted successfully.');
    }
}
