<?php

namespace App\Http\Controllers\Vendor\Auth;

use App\Http\Controllers\Controller;
use App\Models\Vendor;
use App\Models\VendorPasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class ResetPasswordController extends Controller {
    public function showResetForm(Request $request, $token = null) {

        $email = session('fpass_email');
        $token = session()->has('token') ? session('token') : $token;
        if (VendorPasswordReset::where('token', $token)->where('email', $email)->count() != 1) {
            $notify[] = ['error', 'Invalid token'];
            return to_route('vendor.password.request')->withNotify($notify);
        }
        return view('vendor.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $email, 'pageTitle' => 'Reset Password']
        );
    }

    public function reset(Request $request) {
        $request->validate($this->rules());
        $reset = VendorPasswordReset::where('token', $request->token)->orderBy('created_at', 'desc')->first();
        if (!$reset) {
            $notify[] = ['error', 'Invalid verification code'];
            return to_route('vendor.login')->withNotify($notify);
        }

        $vendor           = Vendor::where('email', $reset->email)->first();
        $vendor->password = Hash::make($request->password);
        $vendor->save();

        $vendorIpInfo  = getIpInfo();
        $vendorBrowser = osBrowser();
        notify($vendor, 'PASS_RESET_DONE', [
            'operating_system' => @$vendorBrowser['os_platform'],
            'browser'          => @$vendorBrowser['browser'],
            'ip'               => @$vendorIpInfo['ip'],
            'time'             => @$vendorIpInfo['time'],
        ], ['email']);

        $notify[] = ['success', 'Password changed successfully'];
        return to_route('vendor.login')->withNotify($notify);
    }

    protected function rules() {
        $passwordValidation = Password::min(6);
        if (gs('secure_password')) {
            $passwordValidation = $passwordValidation->mixedCase()->numbers()->symbols()->uncompromised();
        }
        return [
            'token'    => 'required',
            'email'    => 'required|email',
            'password' => ['required', 'confirmed', $passwordValidation],
        ];
    }
}
