<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AccountController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = auth()->user();


        return view('templates.account', [
            'user' => $user,
        ]);
    }

    public function update(Request $request)
    {
        $user = auth()->user();

        $user->fill($request->only('email'))->save();
        $user->user_data->fill($request->user_data)->save();
        if($request->new_password) {
            if(!Hash::check($request->password, $user->password)) return back()->with('status', 'La contraseña actual es incorrecta');

            $this->validate($request, [
                'new_password' => 'min:6|confirmed',
            ]);

            $user->fill([
                'password' => Hash::make($request->password)
            ])->save();
        }

        return back()->with('status', 'Tu cuenta ha sido actualizada');
    }
}
