<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class PerfilController extends Controller
{
    public function __construct()
    {
        $this->middleware(['role:admin']);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('admin.perfil.index', ['usuario' => request()->user()]);
    }

    public function alterarSenhaForm()
    {
        return view('admin.perfil.alterar-senha');
    }

    public function updateSenha(Request $request)
    {
        $this->validate($request, [
            'senha_nova' => 'required|confirmed|min:8',
        ]);

        $user = $request->user();

        if (Hash::check($request->senha_atual, $user->password)) {
            $user->password = Hash::make($request->senha_nova);
            $user->save();

            return redirect()
                ->route('admin.perfil.index')
                ->with('status', 'Senha alterada com sucesso!');
        } else {
            return redirect()
                ->back()
                ->withErrors('Senha atual está inválida!');
        }
    }
}
