<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use App\Models\SupportMessage;
use App\Models\Setting;
use Illuminate\Http\Request;

class SupportTicketController extends Controller
{
    public function index(Request $request)
    {
        $currencySymbol = Setting::where('key', 'currency_symbol')->value('value') ?? '$';

        $query = SupportTicket::with(['user', 'order']);

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('subject', 'like', '%' . $search . '%')
                    ->orWhere('id', $search)
                    ->orWhereHas('user', function ($q2) use ($search) {
                        $q2->where('name', 'like', '%' . $search . '%')
                            ->orWhere('email', 'like', '%' . $search . '%');
                    });
            });
        }

        $tickets = $query->orderByDesc('last_message_at')->orderByDesc('id')->paginate(12);

        return view('admin.support_tickets.index', compact('tickets', 'currencySymbol'));
    }

    public function show($id)
    {
        $currencySymbol = Setting::where('key', 'currency_symbol')->value('value') ?? '$';

        $ticket = SupportTicket::with([
            'user',
            'order',
            'order.items.product',
            'messages.user',
        ])->findOrFail($id);

        return view('admin.support_tickets.show', compact('ticket', 'currencySymbol'));
    }

    public function reply(Request $request, $id)
    {
        $ticket = SupportTicket::findOrFail($id);

        $validated = $request->validate([
            'message' => 'required|string|max:5000',
            'status' => 'nullable|in:open,pending,closed',
        ]);

        SupportMessage::create([
            'support_ticket_id' => $ticket->id,
            'user_id' => null,
            'is_admin' => true,
            'message' => $validated['message'],
        ]);

        $ticket->last_message_at = now();
        if (!empty($validated['status'])) {
            $ticket->status = $validated['status'];
        }
        $ticket->save();

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

    public function updateStatus(Request $request, $id)
    {
        $ticket = SupportTicket::findOrFail($id);

        $validated = $request->validate([
            'status' => 'required|in:open,pending,closed',
        ]);

        $ticket->status = $validated['status'];
        $ticket->save();

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

