<?php
namespace App\Http\Controllers;

use App\Models\AgentGroup;
use App\Models\User;
use Illuminate\Http\Request;

class AgentGroupController extends Controller
{
    public function index() {
        abort_unless(auth()->user()->can('agent_groups.index'), 403);
        $groups = AgentGroup::with('users')->orderBy('name')->get();
        return view('agent-groups.index', compact('groups'));
    }

    public function create() {
        abort_unless(auth()->user()->can('agent_groups.create'), 403);
        $agents = User::active()->agents()->orderBy('name')->get();
        return view('agent-groups.create', compact('agents'));
    }

    public function store(Request $request) {
        abort_unless(auth()->user()->can('agent_groups.create'), 403);
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'auto_assign' => 'boolean',
            'active'      => 'boolean',
            'users'       => 'nullable|array',
            'users.*'     => 'exists:users,id',
        ]);
        $group = AgentGroup::create($data);
        if (!empty($data['users'])) {
            $group->users()->sync($data['users']);
        }
        return redirect()->route('grupos-agentes.index')->with('success', 'Grupo creado.');
    }

    public function edit(AgentGroup $agentGroup) {
        abort_unless(auth()->user()->can('agent_groups.edit'), 403);
        $agents = User::active()->agents()->orderBy('name')->get();
        return view('agent-groups.edit', compact('agentGroup', 'agents'));
    }

    public function update(Request $request, AgentGroup $agentGroup) {
        abort_unless(auth()->user()->can('agent_groups.edit'), 403);
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'auto_assign' => 'boolean',
            'active'      => 'boolean',
            'users'       => 'nullable|array',
            'users.*'     => 'exists:users,id',
        ]);
        $agentGroup->update($data);
        $agentGroup->users()->sync($data['users'] ?? []);
        return redirect()->route('grupos-agentes.index')->with('success', 'Grupo actualizado.');
    }

    public function destroy(AgentGroup $agentGroup) {
        abort_unless(auth()->user()->can('agent_groups.delete'), 403);
        $agentGroup->delete();
        return redirect()->route('grupos-agentes.index')->with('success', 'Grupo eliminado.');
    }
}
