<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

class ProfileController extends Controller
{
    /**
     * Return current admin profile.
     */
    public function index(Request $request)
    {
        $u = $request->user();
        return response()->json([
            'id' => $u->id,
            'name' => $u->name,
            'email' => $u->email,
            'role' => $u->role,
        ]);
    }

    /**
     * Update name + email of current admin.
     */
    public function update(Request $request)
    {
        $u = $request->user();
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required', 'email', 'max:255',
                Rule::unique('users', 'email')->ignore($u->id),
            ],
        ]);

        $u->update($validated);

        return $this->index($request);
    }

    /**
     * Ubah password admin (butuh password lama).
     */
    public function updatePassword(Request $request)
    {
        $u = $request->user();
        $validated = $request->validate([
            'current_password' => ['required', 'string'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ], [
            'password.confirmed' => 'Konfirmasi password tidak cocok.',
            'password.min' => 'Password baru minimal 8 karakter.',
        ]);

        if (!Hash::check($validated['current_password'], $u->password)) {
            throw ValidationException::withMessages([
                'current_password' => ['Password saat ini salah.'],
            ]);
        }

        $u->update(['password' => Hash::make($validated['password'])]);

        return response()->json(['ok' => true, 'message' => 'Password berhasil diubah']);
    }
}
