<?php
namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Department;
use App\Models\AgentGroup;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{
    public function index() {
        abort_unless(auth()->user()->can('users.index'), 403);
        $departments = Department::active()->orderBy('name')->get();
        $roles = Role::orderBy('name')->get();
        return view('users.index', compact('departments', 'roles'));
    }

    public function create() {
        abort_unless(auth()->user()->can('users.create'), 403);
        $departments = Department::active()->orderBy('name')->get();
        $roles = Role::orderBy('name')->get();
        $groups = AgentGroup::active()->orderBy('name')->get();
        return view('users.create', compact('departments', 'roles', 'groups'));
    }

    public function store(Request $request) {
        abort_unless(auth()->user()->can('users.create'), 403);
        $data = $request->validate([
            'name'          => 'required|string|max:255',
            'email'         => 'required|email|unique:users',
            'password'      => 'required|min:8|confirmed',
            'phone'         => 'nullable|string|max:20',
            'extension'     => 'nullable|string|max:10',
            'position'      => 'nullable|string|max:100',
            'location'      => 'nullable|string|max:100',
            'department_id' => 'nullable|exists:departments,id',
            'role'          => 'required|exists:roles,name',
            'is_active'     => 'boolean',
        ]);
        $user = User::create($data);
        $user->assignRole($data['role']);
        return redirect()->route('usuarios.index')->with('success', 'Usuario creado correctamente.');
    }

    public function edit(User $user) {
        abort_unless(auth()->user()->can('users.edit'), 403);
        $departments = Department::active()->orderBy('name')->get();
        $roles = Role::orderBy('name')->get();
        $groups = AgentGroup::active()->orderBy('name')->get();
        return view('users.edit', compact('user', 'departments', 'roles', 'groups'));
    }

    public function update(Request $request, User $user) {
        abort_unless(auth()->user()->can('users.edit'), 403);
        $data = $request->validate([
            'name'          => 'required|string|max:255',
            'email'         => 'required|email|unique:users,email,' . $user->id,
            'password'      => 'nullable|min:8|confirmed',
            'phone'         => 'nullable|string|max:20',
            'extension'     => 'nullable|string|max:10',
            'position'      => 'nullable|string|max:100',
            'location'      => 'nullable|string|max:100',
            'department_id' => 'nullable|exists:departments,id',
            'role'          => 'required|exists:roles,name',
            'is_active'     => 'boolean',
        ]);
        if (empty($data['password'])) unset($data['password']);
        $user->update($data);
        $user->syncRoles([$data['role']]);
        return redirect()->route('usuarios.index')->with('success', 'Usuario actualizado.');
    }

    public function destroy(User $user) {
        abort_unless(auth()->user()->can('users.delete'), 403);
        if ($user->id === auth()->id()) {
            return back()->with('error', 'No puedes eliminar tu propio usuario.');
        }
        $user->delete();
        return redirect()->route('usuarios.index')->with('success', 'Usuario eliminado.');
    }

    public function toggleStatus(User $user) {
        abort_unless(auth()->user()->can('users.edit'), 403);
        $user->update(['is_active' => !$user->is_active]);
        return back()->with('success', 'Estado actualizado.');
    }
}
