<?php

namespace App\Http\Controllers\Customer;

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

class SupportController extends Controller
{
    public function index()
    {
        $tickets = Auth::user()->tickets()->with('comments.author')->latest()->paginate(15);

        return view('customer.support.index', compact('tickets'));
    }

    public function show($id)
    {
        $ticket = Auth::user()->tickets()->with('comments.author')->findOrFail($id);

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'description' => 'required|string',
            'priority' => 'nullable|in:LOW,MEDIUM,HIGH,URGENT',
        ]);
        Auth::user()->tickets()->create(array_merge($validated, [
            'status' => 'OPEN',
            'ticket_number' => 'TKT-'.now()->format('Ymd').'-'.strtoupper(\Illuminate\Support\Str::random(6)),
        ]));

        return back()->with('success', 'تم إنشاء تذكرة الدعم بنجاح.');
    }

    public function comment(Request $request, $id)
    {
        $ticket = Auth::user()->tickets()->findOrFail($id);
        $validated = $request->validate(['content' => 'required|string']);
        $ticket->comments()->create([
            'author_id' => Auth::id(),
            'content' => $validated['content'],
        ]);

        return back()->with('success', 'تم إضافة التعليق.');
    }
}
