<?php

namespace App\Http\Controllers;

use App\Mail\UserActivationMail;
use App\Rules\Mobile;
use App\User;
use App\Verification;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Matthewbdaly\SMS\Client;
use Matthewbdaly\SMS\Drivers\MeliPayamak;
use Plugins\Sms\Contracts\SmsDriverInterface;

class VerificationController extends Controller
{

    public function showResendActivationView()
    {
        return view('auth.emailResend');
    }

    public function resendActivationEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users'
        ]);

        $user = User::where('email', $request->email)->first();

        $verifications = Verification::where([
            ['user_id', $user->id],
            ['created_at', '>=', Carbon::now()->subMinutes(15)],
            ['type', 'email'],
        ])->get();

        if (count($verifications) >= 1) {
            return redirect()->back()->withErrors(['error' => 'تعدا دفعات مجاز ارسال لینک به پایان رسیده است.لطفا 15 دقیقه بعد مجددا تلاش کنید']);
        }

        $verification = Verification::create([
            'user_id' => $user->id,
            'type' => 'email',
            'ip' => $request->ip(),
            'token' => Verification::createEmailToken()
        ]);

        Mail::to($request->email)->send(new UserActivationMail($user, $verification->token, $verification->id));
        return redirect()->back()->with('success', 'انجام شد');
    }

    public function showMobileVerificationView()
    {
        return view('auth.verifyMobile');
    }

    public function verifyUserEmail($id, $token)
    {
        $verification = Verification::where(['id' => $id, 'token' => $token, 'type' => 'email'])->first();
        if (!$verification) {
            return view('auth.verifyEmail', ['error' => 'کد تایید نامعتبر میباشد']);
        } elseif ($verification->created_at < Carbon::now()->subMinutes(15)) {
            return view('auth.verifyEmail', ['error' => 'کد تایید منقضی شده است']);
        } elseif ($verification->is_used) {
            return view('auth.verifyEmail', ['error' => 'کد تایید قبلا استفاده شده است']);
        } else {
            $verification->update(['is_used' => true]);
            $user = User::find($verification->user_id);
            $user->email_verified_at = Carbon::now();
            $user->save();
            return view('auth.verifyEmail', ['success' => 'ایمیل شما با موفقیت تایید شد']);
        }
    }

    public function verifyUserMobile(Request $request)
    {
        $request->validate([
            'mobile' => ['required', new Mobile(), 'exists:users'],
            'verificationCode' => 'required|digits:6'
        ]);

        $user = User::where('mobile', $request->mobile)->first();

        $verification = Verification::where([
            ['type', 'sms'],
            ['user_id', $user->id],
            ['token', $request->verificationCode],
        ])->first();

        if (!$verification) {
            return redirect()->back()->withInput()->withErrors(['error' => 'اطلاعات ارسال شده نامعتبر میباشد']);
        }
        if ($verification->created_at < Carbon::now()->subMinutes(15)) {
            return redirect()->back()->withInput()->withErrors(['error' => 'کد تایید منقضی شده است']);
        } elseif ($verification->is_used) {
            return redirect()->back()->withInput()->withErrors(['error' => 'کد تایید قبلا استفاده شده است']);
        } else {
            $verification->update(['is_used' => true]);
            $user->mobile_verified_at = Carbon::now();
            $user->save();
            return redirect()->route('login')->with('success', 'شماره موبایل شما با موفقیت تایید شد اکنون میتوانید وارد وبسایت شوید');
        }
    }

    public function resendMobileCode(Request $request)
    {
        $request->validate([
            'mobile' => ['required', new Mobile(), 'exists:users']
        ]);

        $user = User::where('mobile', $request->mobile)->first();

        $verifications = Verification::where([
            ['type', 'sms'],
            ['created_at', '>=', Carbon::now()->subMinutes(2)],
            ['user_id', $user->id]
        ])->get();

        if (count($verifications) >= 1) {
            return response()->json(
                [
                    'status' => 'fail',
                    'msg' => 'تعدا دفعات مجاز پیامک کد تایید به پایان رسیده است.لطفا 2 دقیقه بعد مجددا تلاش کنید'
                ]
            );
        }

        $verification = Verification::create([
            'user_id' => $user->id,
            'type' => 'sms',
            'ip' => $request->ip(),
            'token' => Verification::createMobileToken()
        ]);

        $smsSettings = json_decode(getConfig("sms_settings"), true);
        $activeDriver = $smsSettings["active_driver"];
        $driverSettings = $smsSettings['drivers'][$activeDriver];
        $driver = config('sms.map.' . $activeDriver);
        /** @var SmsDriverInterface $driverInstance */
        $driverInstance = new $driver();
        $shouldSendByPatterns = $driverInstance->shouldSendByPattern($driverSettings);

        if ($shouldSendByPatterns) {
            $res = sms()
                ->via($activeDriver)
                ->pattern('userRegister')
                ->data([
                    'code' => $verification->token,
                ])
                ->to([$request->mobile])
                ->send();
        } else {
            sms()->via($activeDriver)->to($request->mobile)->text('کد تایید شما : ' . $verification->token)->send();
        }

        return response()->json(['status' => 'success', 'msg' => 'کد تایید مجددا پیامک شد.']);
    }
}
