<?php

namespace App\Http\Controllers\Admin;

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

class SupportTicketController extends Controller
{
    public function index()
    {
        $tickets = SupportTicket::with('user')->latest('last_reply_at')->paginate(20);
        return view('admin.support_tickets.index', compact('tickets'));
    }

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

    public function update(Request $request, SupportTicket $supportTicket)
    {
        if ($request->has('message')) {
            // It's a reply
             $validated = $request->validate([
                'message' => 'required|string',
            ]);

            TicketMessage::create([
                'ticket_id' => $supportTicket->id,
                'admin_id' => Auth::guard('admin')->id(),
                'message' => $validated['message'],
                'is_admin_reply' => true,
            ]);

            $supportTicket->update([
                'status' => 'in_progress',
                'last_reply_by' => 'admin',
                'last_reply_at' => now(),
            ]);

             return back()->with('success', 'پاسخ شما ارسال شد.');
        } else {
            // It's a status update
             $validated = $request->validate([
                'status' => 'required|in:open,in_progress,resolved,closed',
                'priority' => 'required|in:low,medium,high',
            ]);

            $supportTicket->update($validated);
             return back()->with('success', 'وضعیت تیکت بروزرسانی شد.');
        }
    }

    public function destroy(SupportTicket $supportTicket)
    {
        $supportTicket->delete();
        return redirect()->route('admin.support-tickets.index')->with('success', 'تیکت حذف شد.');
    }
}
