<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ReplyTemplate;
use App\Models\TicketCategory;
use Illuminate\Http\Request;

class ReplyTemplateController extends Controller
{
    private function auth(): void {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']), 403);
    }

    public function index()
    {
        $this->auth();
        $templates = ReplyTemplate::with('category')->latest()->paginate(20);
        return view('admin.reply-templates.index', compact('templates'));
    }

    public function store(Request $request)
    {
        $this->auth();
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'shortcut'    => 'nullable|string|max:50|unique:reply_templates,shortcut',
            'body'        => 'required|string',
            'category_id' => 'nullable|exists:ticket_categories,id',
        ]);
        ReplyTemplate::create($data);
        return back()->with('success', 'Plantilla creada.');
    }

    public function update(Request $request, ReplyTemplate $replyTemplate)
    {
        $this->auth();
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'shortcut'    => 'nullable|string|max:50|unique:reply_templates,shortcut,'.$replyTemplate->id,
            'body'        => 'required|string',
            'category_id' => 'nullable|exists:ticket_categories,id',
            'active'      => 'boolean',
        ]);
        $data['active'] = $request->boolean('active');
        $replyTemplate->update($data);
        return back()->with('success', 'Plantilla actualizada.');
    }

    public function destroy(ReplyTemplate $replyTemplate)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $replyTemplate->delete();
        return back()->with('success', 'Plantilla eliminada.');
    }

    // API: obtener plantillas para insertar en ticket
    public function api(Request $request)
    {
        $this->auth();
        $q = $request->input('q','');
        $templates = ReplyTemplate::active()
            ->when($q, fn($query) => $query->where('name','like',"%{$q}%")
                ->orWhere('shortcut','like',"%{$q}%"))
            ->limit(10)->get(['id','name','shortcut','body']);
        return response()->json($templates);
    }
}
