<?php

namespace App\Http\Controllers;

use App\Models\SupportTicket;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SupportTicketController extends Controller
{
    public function show(Request $request, SupportTicket $supportTicket)
    {
        abort_unless($supportTicket->user_id === $request->user()->id || $request->user()->isAdmin(), 403);

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

    public function store(Request $request)
    {
        $payload = $request->validate([
            'subject' => ['required', 'string', 'max:180'],
            'priority' => ['required', 'in:low,normal,high'],
            'message' => ['required', 'string', 'max:2000'],
        ]);

        $ticket = SupportTicket::create([
            'uuid' => (string) Str::uuid(),
            'user_id' => $request->user()->id,
            'ticket_number' => 'TCK-'.now()->format('ymd').'-'.strtoupper(Str::random(5)),
            'subject' => $payload['subject'],
            'priority' => $payload['priority'],
            'status' => 'open',
            'last_message' => $payload['message'],
            'last_activity_at' => now(),
        ]);

        $ticket->messages()->create([
            'sender_user_id' => $request->user()->id,
            'sender_type' => 'customer',
            'body' => $payload['message'],
        ]);

        return back()->with('status', 'تم فتح تذكرة الدعم وسيتم الرد عليك قريبًا.');
    }

    public function reply(Request $request, SupportTicket $supportTicket)
    {
        abort_unless($supportTicket->user_id === $request->user()->id, 403);

        if (in_array($supportTicket->status, ['resolved', 'closed'], true)) {
            return back()->withErrors(['ticket' => 'لا يمكن الرد على تذكرة مغلقة أو محلولة.']);
        }

        $payload = $request->validate([
            'message' => ['required', 'string', 'max:2000'],
        ]);

        $supportTicket->messages()->create([
            'sender_user_id' => $request->user()->id,
            'sender_type' => 'customer',
            'body' => $payload['message'],
        ]);

        $supportTicket->update([
            'status' => 'open',
            'last_message' => $payload['message'],
            'last_activity_at' => now(),
        ]);

        return back()->with('status', 'تم إرسال ردك للدعم.');
    }
}
