<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SupportTicketsController extends Controller
{
    public function index(Request $request)
    {
        $tickets = SupportTicket::with('user')
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->input('status')))
            ->when($request->filled('search'), function ($query) use ($request) {
                $search = $request->input('search');
                $query->where(function ($nested) use ($search) {
                    $nested->where('subject', 'like', "%{$search}%")
                        ->orWhereHas('user', fn ($user) => $user->where('username', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%"));
                });
            })
            ->orderByRaw("case when status = 'open' then 0 when status = 'pending' then 1 else 2 end")
            ->latest('last_reply_at')
            ->paginate(15)
            ->withQueryString();

        $stats = [
            'open' => SupportTicket::where('status', 'open')->count(),
            'pending' => SupportTicket::where('status', 'pending')->count(),
            'closed' => SupportTicket::where('status', 'closed')->count(),
            'total' => SupportTicket::count(),
        ];

        return view('admin.tickets', compact('tickets', 'stats'));
    }

    public function show(SupportTicket $ticket)
    {
        $ticket->load(['user', 'messages.user']);
        return view('admin.ticket-view', compact('ticket'));
    }

    public function reply(Request $request, SupportTicket $ticket)
    {
        $data = $request->validate([
            'message' => ['required', 'string', 'max:3000'],
            'status' => ['required', 'in:open,pending,closed'],
        ]);

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

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

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

    public function bulk(Request $request)
    {
        $data = $request->validate([
            'ids' => ['required', 'array', 'min:1'],
            'ids.*' => ['integer', 'exists:support_tickets,id'],
            'action' => ['required', 'in:open,pending,close,delete'],
        ]);

        $count = DB::transaction(function () use ($data) {
            $query = SupportTicket::whereIn('id', $data['ids']);

            if ($data['action'] === 'delete') {
                return $query->delete();
            }

            return $query->update([
                'status' => $data['action'] === 'close' ? 'closed' : $data['action'],
                'last_reply_at' => now(),
            ]);
        });

        return back()->with('success', "Bulk action applied to {$count} ticket(s).");
    }
}
