<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Support\PasswordPolicy;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class NewPasswordController extends Controller
{
    /**
     * Display the password reset view.
     */
    public function create(Request $request): View
    {
        $dealer = null;

        $email = $request->email;
        if (is_string($email) && $email !== '') {
            $user = User::whereRaw('lower(email) = ?', [strtolower($email)])->first();
            if ($user && $user->dealer_id) {
                $dealer = \App\Models\Dealer::find($user->dealer_id);
            }
        }

        return view('auth.reset-password', [
            'request' => $request,
            'passwordHint' => PasswordPolicy::hintText(),
            'dealer' => $dealer,
        ]);
    }

    /**
     * Handle an incoming new password request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'token' => ['required'],
            'email' => ['required', 'email'],
            'password' => array_merge(PasswordPolicy::rules(), ['confirmed']),
        ], PasswordPolicy::messages());

        $user = User::where('email', $request->email)->first();
        if ($user && $user->isSamePassword($request->password)) {
            throw ValidationException::withMessages([
                'password' => 'Your new password must be different from your current password.',
            ]);
        }

        // Here we will attempt to reset the user's password. If it is successful we
        // will update the password on an actual user model and persist it to the
        // database. Otherwise we will parse the error and return the response.
        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user) use ($request) {
                $user->forceFill([
                    'password' => Hash::make($request->password),
                    'remember_token' => Str::random(60),
                ])->save();

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

        // If the password was successfully reset, we will redirect the user back to
        // the application's home authenticated view. If there is an error we can
        // redirect them back to where they came from with their error message.
        if ($status == Password::PASSWORD_RESET) {
            $loginRoute = $this->dealerLoginRouteFromEmail($request->email);

            return redirect($loginRoute)->with('status', __($status));
        }

        return back()
            ->withInput($request->only('email'))
            ->withErrors(['email' => __($status)]);
    }

    private function dealerLoginRouteFromEmail(string $email): string
    {
        $user = User::whereRaw('lower(email) = ?', [strtolower($email)])->first();
        if ($user && $user->dealer_id) {
            $dealerCode = \App\Models\Dealer::query()
                ->where('id', $user->dealer_id)
                ->value('code');

            if (is_string($dealerCode) && $dealerCode !== '') {
                return route('dealer.login.show', ['code' => $dealerCode]);
            }
        }

        return route('login');
    }
}
