<?php

namespace App\Http\Controllers\Auth;

use Formatter;
use App\Helpers\Helpers;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SendmsgController;
use App\Models\Device;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;

class PasswordResetLinkController extends Controller
{
  /**
   * Display the password reset link request view.
   *
   * @return \Illuminate\View\View
   */
  public function create()
  {
    $adminSender = Device::where('user_id', 1)->where('status', '=', 'ONLINE')->value('sender');
    return view('auth.forgot-password', compact('adminSender'));
  }

  /**
   * Handle an incoming password reset link request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\RedirectResponse
   *
   * @throws \Illuminate\Validation\ValidationException
   */
  public function store(Request $request)
  {
    $request->validate([
      'email' => ['required', 'email'],
    ]);

    // We will send the password reset link to this user. Once we have attempted
    // to send the link, we will examine the response then see the message we
    // need to show to the user. Finally, we'll send out a proper response.
    $status = Password::sendResetLink($request->only('email'));

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

  public function wa(Request $request)
  {
    if (filter_var(Helpers::setting('waResetPassword'), FILTER_VALIDATE_BOOLEAN)) {
      $phone = Formatter::pf($request->phone);
      $user = User::where('phone', '=', $phone)->first();
      if (!empty($user)) {
        $code = base64_encode(mb_substr($user->password, -10));
        $url = url("/user-resetnow/$user->id/$code");
        $msgtext = str_ireplace(['{name}', '{appurl}', '{appname}'], [$user->name, rtrim(config('app.url'), '/'), config('app.name')], __('_MsgWaResetPassword'));
        $response = SendmsgController::sendMessage($phone, $msgtext . "\n\n--Reset link--\n" . $url . "\n--Reset link--", $request->adminSender);
        // sleep(5);
        // $response2 = SendmsgController::sendMessage($phone, $url, $request->adminSender);
        return redirect()->route('dashboard');
      } else {
        return redirect()
          ->back()
          ->with(['danger_alert' => __('Cannot find User')]);
      }
    } else {
      return redirect()->route('dashboard');
    }
  }
}
