<?php

namespace App\Http\Middleware;

use Closure;
use App\Helpers\Formatter;
use App\Helpers\Helpers;
use App\Http\Controllers\SendmsgController;
use App\Models\Device;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Route;

class WaVerified
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
    if (in_array(Route::currentRouteName(), ['user.leaveImpersonate'])) return $next($request);
    if (empty($request->user()->email_verified_at) && filter_var(Helpers::setting('waVerification'), FILTER_VALIDATE_BOOLEAN)) {
      $user = User::where('id', '=', $request->user()->id)->first();
      $adminSender = Device::where('user_id', 1)->where('status', '=', 'ONLINE')->value('sender');
      if (!empty($adminSender)) {
        $user->phone = Formatter::pf($request->user()->phone);
        $user->otp = rand(1111, 9999);
        $user->save();
        $msgtext = str_ireplace(['{name}', '{appurl}', '{appname}', '{otp}'], [$user->name, rtrim(config('app.url'), '/'), config('app.name'), $user->otp], __('_MsgOtpRegister'));
        $response = SendmsgController::sendMessage($user->phone, $msgtext, $adminSender);
  $res = is_string($response) ? json_decode($response) : $response;
        if (!empty($res->success) && $res->success == true) {
          return redirect()->route('user.verify')->with(['success_alert' => __('OTP code send to') . ' ' . $user->phone . ': ' . __('SUCCESS')]);
        } else {
          return redirect()->route('user.verify')->with(['danger_alert' => __('OTP code send to') . ' ' . $user->phone . ': ' . __('FAILED')]);
        }
      }
    }
    return $next($request);
  }
}
