<?php

namespace App\Http\Controllers\CounterManager\Auth;

use App\Http\Controllers\Controller;
use App\Models\CounterManager;
use App\Models\CounterManagerPasswordReset;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ForgotPasswordController extends Controller
{
    public function showLinkRequestForm()
    {
        $pageTitle = 'Account Recovery';
        return view('counter_manager.auth.passwords.email', compact('pageTitle'));
    }

    public function sendResetCodeEmail(Request $request)
    {
        $request->validate([
            'value' => 'required',
        ]);

        if (!verifyCaptcha()) {
            $notify[] = ['error', 'Invalid captcha provided'];
            return back()->withNotify($notify);
        }

        $fieldType = $this->findFieldType();
        $counterManager = CounterManager::where($fieldType, $request->value)->first();
        if (!$counterManager) {
            $notify[] = ['error', 'The account could not be found'];
            return back()->withNotify($notify);
        }

        CounterManagerPasswordReset::where('email', $counterManager->email)->delete();
        $code = verificationCode(6);
        $passwordReset             = new CounterManagerPasswordReset();
        $passwordReset->email      = $counterManager->email;
        $passwordReset->token      = $code;
        $passwordReset->created_at = Carbon::now();
        $passwordReset->save();

        $ownerIpInfo  = getIpInfo();
        $ownerBrowser = osBrowser();

        notify($counterManager, 'PASS_RESET_CODE', [
            'code'             => $code,
            'operating_system' => isset($ownerBrowser['os_platform']) ? $ownerBrowser['os_platform'] : '',
            'browser' => isset($ownerBrowser['browser']) ? $ownerBrowser['browser'] : '',
            'ip' => isset($ownerIpInfo['ip']) ? $ownerIpInfo['ip'] : '',
            'time' => isset($ownerIpInfo['time']) ? $ownerIpInfo['time'] : ''
        ], ['email']);

        $email = $counterManager->email;
        session()->put('pass_res_mail', $email);

        $notify[] = ['success', 'Password reset email sent successfully'];
        return to_route('counter.manager.password.code.verify')->withNotify($notify);
    }

    public function codeVerify()
    {
        $pageTitle = 'Verify Code';
        $email = session()->get('pass_res_mail');
        if (!$email) {
            $notify[] = ['error', 'Oops! session expired'];
            return to_route('counter.manager.password.reset')->withNotify($notify);
        }
        return view('counter_manager.auth.passwords.code_verify', compact('pageTitle', 'email'));
    }

    public function verifyCode(Request $request)
    {
        $request->validate([
            'code'  => 'required',
            'email' => 'required'
        ]);
        $code =  str_replace(' ', '', $request->code);

        $CounterManagerPasswordReset = CounterManagerPasswordReset::where('token', $code)->where('email', $request->email)->first();
        if (!$CounterManagerPasswordReset) {
            $notify[] = ['error', 'Verification code doesn\'t match'];
            return to_route('counter.manager.password.request')->withNotify($notify);
        }
        session()->flash('fpass_email', $request->email);

        $notify[] = ['success', 'You can change your password'];
        return to_route('counter.manager.password.reset', $code)->withNotify($notify);
    }

    public function findFieldType()
    {
        $input = request()->input('value');

        $fieldType = filter_var($input, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        request()->merge([$fieldType => $input]);
        return $fieldType;
    }
}
