<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests\ProfileUpdateRequest;

class ProfileController extends Controller
{
    //menampilkan halaman edit profile
    public function edit($id){
        $profile = User::find($id);
        return view('profile.edit', compact('profile'));
    }

    //proses update halaman profile
    public function update(Request $request, $id)
        {
        $request->validate([
            'name' => ['required'],
            'email' => ['required'],
            'password' => ['nullable', 'string', 'min:8'],
            'nama_lengkap' => ['required'],
        ],
            [
                'name.required' => 'Kolom username wajib diisi.',
                'email.required' => 'Kolom email wajib diisi.',
                'password.min' => 'Password minimal 8 karakter.',
                'nama_lengkap.required' => 'Kolom nama lengkap wajib diisi.',
            ]
        );
        $user = User::findOrFail($id);
        $user->name = $request->name;
        $user->email = $request->email;
        if ($request->filled('password')) {
            $user->password = bcrypt($request->input('password'));
        }
        $user->nama_lengkap = $request->nama_lengkap;
        $user->email_verified_at = now();
        $user->save();
        return redirect()->route('profile.edit', $id)->with('success', 'Profil berhasil diedit.');
    }
}
