<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class UserPasswordController extends Controller
{
    /**
     * Muestra el formulario para cambiar la contraseña de un usuario
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function showChangePasswordForm(Request $request)
    {
        $user = User::findOrFail($request->id);
        
        // Verificar permisos
        if (!Auth::user()->isAbleTo('edit-user') && Auth::id() !== $user->id) {
            return redirect('/admin/not-authorized');
        }
        
        return view('admin.users.change-password', [
            'user' => $user
        ]);
    }
    
    /**
     * Procesa el cambio de contraseña
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function changePassword(Request $request)
    {
        $user = User::findOrFail($request->id);
        
        // Verificar permisos
        if (!Auth::user()->isAbleTo('edit-user') && Auth::id() !== $user->id) {
            return redirect('/admin/not-authorized');
        }
        
        // Validar la entrada
        $validator = Validator::make($request->all(), [
            'password' => 'required|min:8|confirmed',
        ]);
        
        if ($validator->fails()) {
            return redirect()
                ->route('users.change-password', ['id' => $user->id])
                ->withErrors($validator)
                ->withInput();
        }
        
        // Actualizar la contraseña
        $user->password = Hash::make($request->password);
        $user->save();
        
        return redirect('/admin/view-users')
            ->with('success', 'La contraseña del usuario ha sido actualizada correctamente.');
    }
}
