<?php

namespace App\Http\Controllers\Website;

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

class ProfileUpdateController extends Controller
{
    public function index()
    {
        return view('website.app.profile-update');
    }

    public function update(Request $request)
    {
        $userById = User::where('id', $request->input('id'))->first();

        $userById['name'] = $request->input('name');
        $userById['username'] = $request->input('username');
        $userById->save();

        toast('Data user berhasil diubah!', 'success');
        return redirect()->route('profile.index');
    }

    public function updatePassword(Request $request)
    {
        // Validasi input
        $request->validate([
            'oldpasswordInput' => 'required',
            'newpasswordInput' => 'required|min:6',
            'confirmpasswordInput' => 'required|min:6',
        ]);

        // Ambil user yang sedang login
        $userById = User::find($request->input('user_id'));
        // dd($userById);

        // Cek apakah old password sesuai dengan yang ada di database
        if (!Hash::check($request->oldpasswordInput, $userById->password)) {
            toast('Gagal, password terdahulu tidak sesuai!', 'error');
            return redirect()->back();
        } else {
            if ($request->input('newpasswordInput') == $request->input('confirmpasswordInput')) {
                // Jika sesuai, update password dengan hash baru
                $userById->password = Hash::make($request->newpasswordInput);
                $userById->save();
                toast('Password anda berhasil diubah!', 'success');
                return redirect()->route('profile.index');
            } else {
                toast('Gagal, konfirmasi password tidak sesuai dengan password baru!', 'error');
                return redirect()->back();
            }
        }
    }
}
