<?php

namespace App\Http\Controllers;

use App\Models\SupportTicket;
use App\Services\AuditLogService;
use Illuminate\Http\Request;

class AdminSupportTicketController extends Controller
{
    public function index(Request $request)
    {
        $status = (string) $request->query('status', '');
        $priority = (string) $request->query('priority', '');
        $query = trim((string) $request->query('q', ''));

        return view('admin.support-tickets.index', [
            'tickets' => SupportTicket::with('user')
                ->when($query !== '', function ($builder) use ($query) {
                    $builder->where(function ($nested) use ($query) {
                        $nested
                            ->where('ticket_number', 'like', "%{$query}%")
                            ->orWhere('subject', 'like', "%{$query}%")
                            ->orWhereHas('user', fn ($user) => $user
                                ->where('name', 'like', "%{$query}%")
                                ->orWhere('display_name', 'like', "%{$query}%")
                                ->orWhere('email', 'like', "%{$query}%"));
                    });
                })
                ->when($status, fn ($query) => $query->where('status', $status))
                ->when($priority, fn ($query) => $query->where('priority', $priority))
                ->latest('last_activity_at')
                ->paginate(20)
                ->withQueryString(),
            'summary' => [
                'total' => SupportTicket::count(),
                'open' => SupportTicket::where('status', 'open')->count(),
                'pending_customer' => SupportTicket::where('status', 'pending_customer')->count(),
                'resolved' => SupportTicket::where('status', 'resolved')->count(),
                'closed' => SupportTicket::where('status', 'closed')->count(),
                'high' => SupportTicket::where('priority', 'high')->count(),
            ],
            'status' => $status,
            'priority' => $priority,
            'query' => $query,
        ]);
    }

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

    public function update(Request $request, SupportTicket $supportTicket, AuditLogService $audit)
    {
        $payload = $request->validate([
            'status' => ['required', 'in:open,pending_customer,resolved,closed'],
            'priority' => ['required', 'in:low,normal,high'],
            'last_message' => ['nullable', 'string', 'max:2000'],
        ]);

        if (filled($payload['last_message'] ?? null)) {
            $supportTicket->messages()->create([
                'sender_user_id' => $request->user()->id,
                'sender_type' => 'admin',
                'body' => $payload['last_message'],
            ]);
        }

        $payload['last_activity_at'] = now();
        $supportTicket->update($payload);
        $audit->record('admin.support_ticket_updated', $supportTicket, [
            'ticket_number' => $supportTicket->ticket_number,
            'status' => $supportTicket->status,
            'priority' => $supportTicket->priority,
        ]);

        return back()->with('status', 'تم تحديث التذكرة.');
    }
}
