<?php

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\SupportReply;
use App\Models\SupportTicket;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    public function index(Request $request)
    {
        $query = SupportTicket::with(['tenant', 'reporter', 'assignee']);

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

        if ($request->filled('priority')) {
            $query->where('priority', $request->priority);
        }

        $tickets = $query->latest()->paginate(15);
        $openCount = SupportTicket::whereIn('status', ['open', 'in_progress'])->count();
        $urgentCount = SupportTicket::where('priority', 'urgent')->whereIn('status', ['open', 'in_progress'])->count();

        return view('platform.support.index', compact('tickets', 'openCount', 'urgentCount'));
    }

    public function show($id)
    {
        $ticket = SupportTicket::with(['tenant', 'reporter', 'assignee', 'replies.user'])->findOrFail($id);

        return view('platform.support.show', compact('ticket'));
    }

    public function reply(Request $request, $id)
    {
        $ticket = SupportTicket::findOrFail($id);
        $request->validate(['message' => 'required|string']);

        SupportReply::create([
            'ticket_id' => $ticket->id,
            'user_id' => auth()->id(),
            'message' => $request->message,
            'is_internal_note' => $request->boolean('is_internal_note'),
        ]);

        $ticket->update([
            'status' => $request->status ?? 'in_progress',
            'last_response_at' => now(),
        ]);

        AuditLog::record('support', 'support.reply_posted', $ticket);

        return back()->with('status', 'Response added to support ticket.');
    }
}
