<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password as PasswordRule;
use Illuminate\Support\Facades\Password;

class ResetPasswordController extends Controller
{
    public function create(string $token)
    {
        return view('pages.user.auth.reset-password', compact('token'));
    }

    public function store(Request $request)
    {
        // Validate input
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => ['required', 'confirmed', PasswordRule::defaults()],
        ]);

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

                $user->save();

                event(new PasswordReset($user));
            }
        );

        if ($status === Password::PASSWORD_RESET) {
            // Success: redirect to login with green toast
            return redirect()->route('login')->with([
                'message' => 'Your password has been reset successfully!',
                'type' => 'success',
            ]);
        } else {
            // Error: redirect back with red toast
            return redirect()->back()->with([
                'message' => __($status),
                'type' => 'error',
            ]);
        }
    }
}
