<?php

namespace App\Http\Controllers\authentications;

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

class ForgotPasswordBasic extends Controller
{
  public function index()
  {
    return view('content.authentications.auth-forgot-password-basic');
  }

  public function sendResetLink(Request $request)
  {
    $request->validate(['email' => 'required|email']);

    $status = Password::sendResetLink(
      $request->only('email')
    );

    return $status === Password::RESET_LINK_SENT
      ? back()->with(['status' => __($status)])
      : back()->withErrors(['email' => __($status)]);
  }

  public function resetPassword(Request $request, string $token)
  {
    if (!isset($request->password)) {
      $email = $request->email;
      return view("content.authentications.auth-set-new-password", compact("token", "email"));
    }

    $request['token'] = $token;

    $request->validate([
      'token' => 'required',
      'email' => 'required|email',
      'password' => 'required|min:1|confirmed',
    ]);

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

        $user->save();
      }
    );

    return $status != ""
      ? redirect()->route("auth-login-basic")->with(['status' => __($status)])
      : back()->withErrors(['email' => [__($status)]]);
  }
}
