<?php
namespace App\Http\Controllers;

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

class DepartmentController extends Controller
{
    public function index() {
        abort_unless(auth()->user()->can('departments.index'), 403);
        $departments = Department::with(['parent', 'manager', 'children'])
            ->roots()->orderBy('order')->orderBy('name')->get();
        return view('departments.index', compact('departments'));
    }

    public function create() {
        abort_unless(auth()->user()->can('departments.create'), 403);
        $parents  = Department::active()->orderBy('name')->get();
        $managers = User::active()->orderBy('name')->get();
        return view('departments.create', compact('parents', 'managers'));
    }

    public function store(Request $request) {
        abort_unless(auth()->user()->can('departments.create'), 403);
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'color'       => 'nullable|string|max:7',
            'parent_id'   => 'nullable|exists:departments,id',
            'manager_id'  => 'nullable|exists:users,id',
            'active'      => 'boolean',
            'order'       => 'integer|min:0',
        ]);
        Department::create($data);
        return redirect()->route('departamentos.index')->with('success', 'Departamento creado.');
    }

    public function edit(Department $department) {
        abort_unless(auth()->user()->can('departments.edit'), 403);
        $parents  = Department::active()->where('id', '!=', $department->id)->orderBy('name')->get();
        $managers = User::active()->orderBy('name')->get();
        return view('departments.edit', compact('department', 'parents', 'managers'));
    }

    public function update(Request $request, Department $department) {
        abort_unless(auth()->user()->can('departments.edit'), 403);
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'color'       => 'nullable|string|max:7',
            'parent_id'   => 'nullable|exists:departments,id',
            'manager_id'  => 'nullable|exists:users,id',
            'active'      => 'boolean',
            'order'       => 'integer|min:0',
        ]);
        $department->update($data);
        return redirect()->route('departamentos.index')->with('success', 'Departamento actualizado.');
    }

    public function destroy(Department $department) {
        abort_unless(auth()->user()->can('departments.delete'), 403);
        if ($department->users()->count() > 0) {
            return back()->with('error', 'No se puede eliminar: tiene usuarios asignados.');
        }
        $department->delete();
        return redirect()->route('departamentos.index')->with('success', 'Departamento eliminado.');
    }
}
