<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Company;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Hash;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = auth()->user()->hasRole('super-admin')
            ? User::all()
            : User::where('company_id', auth()->user()->company_id)->get();

        return view('users.index', compact('users'));
    }

 public function create()
{   
      $companies = auth()->user()->hasRole('super-admin')
            ? Company::where('activo', true)->get()
            : Company::where('id', auth()->user()->company_id)->get();

    /*$roles = Role::all();*/
    /*$roles = Role::whereNotIn('name', ['super-admin', 'admin-empresa'])->get();*/
    $roles = auth()->user()->hasRole('super-admin')
    ? Role::all()
    : Role::whereNotIn('name', ['super-admin', 'admin-empresa'])->get();

    return view('users.create', compact('companies', 'roles'));
}

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|min:6',
        'company_id' => 'required|exists:companies,id',
        'role' => 'required|exists:roles,name',
    ]);

    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
        'company_id' => $request->company_id,
    ]);

    // Asignar rol con Spatie
    $user->assignRole($request->role);

    return redirect()->route('users.index')
        ->with('success', 'Usuario creado correctamente.');
}
    public function show(User $user) {}
   public function edit(User $user)
{
      $companies = auth()->user()->hasRole('super-admin')
            ? Company::where('activo', true)->get()
            : Company::where('id', auth()->user()->company_id)->get();
            
    $roles = Role::all();

    return view('users.edit', compact('user', 'companies', 'roles'));
}
public function update(Request $request, User $user)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email,' . $user->id,
        'company_id' => 'required|exists:companies,id',
        'role' => 'required|exists:roles,name',
        'password' => 'nullable|min:6',
    ]);

    $oldData = $user->toArray();
    $oldRoles = $user->getRoleNames()->toArray();

    $data = [
        'name' => $request->name,
        'email' => $request->email,
        'company_id' => $request->company_id,
    ];

    if ($request->filled('password')) {
        $data['password'] = Hash::make($request->password);
    }

    $user->update($data);

    // Sincroniza rol (quita el anterior y asigna el nuevo)
    $user->syncRoles([$request->role]);

    $newData = $user->fresh()->toArray();
    $newRoles = $user->getRoleNames()->toArray();

    // 🔐 Auditoría coherente con tu sistema
    audit_log(
        'updated',
        'users',
        $user,
        [
            'user' => $oldData,
            'roles' => $oldRoles
        ],
        [
            'user' => $newData,
            'roles' => $newRoles
        ]
    );

    return redirect()->route('users.index')
        ->with('success', 'Usuario actualizado correctamente.');
}
  public function destroy(User $user)
{
    $deletedData = [
        'user' => $user->toArray(),
        'roles' => $user->getRoleNames()->toArray(),
        'company_id' => $user->company_id,
    ];

    $user->delete();

    // 🔐 Auditoría consistente con tu sistema
    audit_log(
        'deleted',
        'users',
        $user,
        $deletedData,
        null,
        "Usuario eliminado"
    );

    return redirect()->route('users.index')
        ->with('success', 'Usuario eliminado correctamente.');
}
}
