<?php

namespace App\Http\Controllers\Auth;

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

class ResetPasswordController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Menampilkan form reset password
     */
    public function showResetForm(Request $request, $token = null)
    {
        return view('auth.reset_password')->with([
            'token' => $token,
            'email' => $request->email
        ]);
    }

    /**
     * Memproses reset password
     */
    public function reset(Request $request)
    {
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|confirmed',
        ], [
            'token.required' => 'Token reset password diperlukan.',
            'email.required' => 'Email wajib diisi.',
            'email.email' => 'Format email tidak valid.',
            'password.required' => 'Password wajib diisi.',
            'password.min' => 'Password minimal 8 karakter.',
            'password.confirmed' => 'Konfirmasi password tidak sesuai.',
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function (User $user, string $password) {
                $user->forceFill([
                    'password' => Hash::make($password)
                ])->setRememberToken(Str::random(60));

                $user->save();
            }
        );

        if ($status === Password::PASSWORD_RESET) {
            return redirect()->route('login')->with('status', 'Password berhasil direset! Silakan login dengan password baru Anda.');
        }

        return back()->withErrors(['email' => $this->getResetErrorMessage($status)]);
    }

    /**
     * Mendapatkan pesan error untuk reset password
     */
    private function getResetErrorMessage($status)
    {
        switch ($status) {
            case Password::INVALID_TOKEN:
                return 'Token reset password tidak valid.';
            case Password::INVALID_USER:
                return 'Email tidak ditemukan.';
            default:
                return 'Terjadi kesalahan saat mereset password.';
        }
    }
}