<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;

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

    public function updateEmail(Request $request): RedirectResponse
    {
        $validator = \Validator::make($request->all(), [
            'current_password' => ['required', 'current_password'],
            'email'            => ['required', 'email', 'max:255', 'unique:users,email,' . auth()->id()],
        ], [
            'current_password.current_password' => 'Kata laluan semasa tidak betul.',
            'email.unique'                       => 'Alamat emel ini sudah digunakan.',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator, 'email')->withInput();
        }

        auth()->user()->update(['email' => $request->email]);

        return back()->with('email_success', 'Alamat emel berjaya dikemaskini.');
    }

    public function updatePassword(Request $request): RedirectResponse
    {
        $validator = \Validator::make($request->all(), [
            'current_password' => ['required', 'current_password'],
            'password'         => ['required', 'confirmed', Password::min(8)],
        ], [
            'current_password.current_password' => 'Kata laluan semasa tidak betul.',
            'password.min'                       => 'Kata laluan baru mestilah sekurang-kurangnya 8 aksara.',
            'password.confirmed'                 => 'Pengesahan kata laluan tidak sepadan.',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator, 'password')->withInput();
        }

        auth()->user()->update(['password' => Hash::make($request->password)]);

        Auth::login(auth()->user());

        return back()->with('password_success', 'Kata laluan berjaya ditukar.');
    }
}
