<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    public function edit()
    {
        return view('profile.edit', [
            'user' => auth()->user(),
        ]);
    }

    public function update(Request $request)
    {
        $user = auth()->user();
        
        $request->validate([
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:users,username,' . $user->id,
            'new_password' => 'nullable|string|min:8|confirmed',
            'pin' => 'required|string',
        ]);

        if ($request->pin !== '220902') {
            return back()->withErrors(['pin' => 'PIN keamanan salah. Silakan hubungi pengembang jika lupa.'])->withInput();
        }

        $user->name = $request->name;
        $user->username = $request->username;

        if ($request->filled('new_password')) {
            $user->password = \Illuminate\Support\Facades\Hash::make($request->new_password);
        }

        $user->save();

        return back()->with('success', 'Profil, username, dan password berhasil diperbarui.');
    }
}
