<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index()
    {
        $carts = session()->get('cart', []);
        $cart = array_slice($carts, 0, 4);
        if($cart){
            $totalProducts = count($cart);
        }else{
            $totalProducts = 0;
        }
        $roles = Role::all();
        $datos = User::where('status', '<>', ['Eliminado'])->with('roles')->orderBy('id', 'asc')->get();
        return view('usuarios/index', compact('datos', 'roles', 'totalProducts', 'cart'));
    }
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'role' => 'required|exists:roles,name',
            'password' => ['required', 'string', 'min:6', 'confirmed'], // Esta regla verifica la confirmación de contraseña
        ]);
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
            'status' => "Activo",
        ]);
        $role = Role::findByName($request->input('role'));
        $user->assignRole($role);
        return redirect()->route('usuarios.index')->with('success', 'Registro creado con éxito');
    }
    public function update(Request $request,Users $proveedores, $id)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'role' => 'required',
        ]);
        $password = $request->post('password');
        if($password != ''){
            $request->validate([
                'password' => ['required', 'string', 'min:6', 'confirmed'],
            ]);
            $datos = users::where('id', $id)->first();
            $datos->password = bcrypt($request->input('password'));
            $datos->save();
        }
        $user = User::findOrFail($id);
        $user->update([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
        ]);
        // Obtén el nuevo rol por nombre
        $newRole = Role::findByName($request->input('role'));
        // Sincroniza los roles del usuario para reemplazar el rol anterior
        $user->syncRoles([$newRole]);
        return redirect()->route("usuarios.index")->with("success", "¡Editado exitosamente!");
    }
    public function activate(Request $request, $id)
    {
        $datos =Users::where('id', $id)->first();
        $datos->status = 'Activo';
        $datos->save();
        return redirect()->route("usuarios.index")->with("success", "¡Registro Activo!");
    }
    public function inactivate(Request $request, $id)
    {
        $datos =Users::where('id', $id)->first();
        $datos->status = 'Inactivo';
        $datos->save();
        return redirect()->route("usuarios.index")->with("success", "¡Registro Inactivo!");
    }
    public function delete(Request $request, $id)
    {
        $datos =Users::where('id', $id)->first();
        $datos->status = 'Eliminado';
        $datos->save();
        return redirect()->route("usuarios.index")->with("success", "¡Registro Eliminado!");
    }
}
