<?php
namespace App\Http\Controllers;

use App\Models\TicketCategory;
use Illuminate\Http\Request;

class TicketCategoryController extends Controller
{
    public function index() {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $categories = TicketCategory::with(['parent','children'])->roots()->orderBy('order')->get();
        return view('admin.ticket-config.categories', compact('categories'));
    }
    public function store(Request $request) {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate(['name'=>'required','color'=>'nullable','parent_id'=>'nullable|exists:ticket_categories,id','active'=>'boolean','order'=>'integer']);
        TicketCategory::create($data);
        return back()->with('success','Categoría creada.');
    }
    public function update(Request $request, TicketCategory $ticketCategory) {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate(['name'=>'required','color'=>'nullable','parent_id'=>'nullable|exists:ticket_categories,id','active'=>'boolean','order'=>'integer']);
        $ticketCategory->update($data);
        return back()->with('success','Categoría actualizada.');
    }
    public function destroy(TicketCategory $ticketCategory) {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        if ($ticketCategory->tickets()->count() > 0) return back()->with('error','Tiene tickets asociados.');
        $ticketCategory->delete();
        return back()->with('success','Categoría eliminada.');
    }
}
