<?php

namespace App\Http\Controllers\CounterManager\Auth;

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

class ResetPasswordController extends Controller
{
    public function showResetForm(Request $request, $token)
    {
        $pageTitle = "Reset Password";
        $email = session('fpass_email');
        $token = session()->has('token') ? session('token') : $token;
        $resetToken = CounterManagerPasswordReset::where('token', $token)->where('email', $email)->first();
        if (!$resetToken) {
            $notify[] = ['error', 'Invalid token'];
            return to_route('counter.manager.password.request')->withNotify($notify);
        }
        return view('counter_manager.auth.passwords.reset', compact('pageTitle', 'email', 'token'));
    }

    public function reset(Request $request)
    {
        $request->validate($this->rules());

        $reset = CounterManagerPasswordReset::where('token', $request->token)->orderBy('created_at', 'desc')->first();
        if (!$reset) {
            $notify[] = ['error', 'Invalid verification code'];
            return to_route('counter.manager.login')->withNotify($notify);
        }

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

        $userIpInfo = getIpInfo();
        $userBrowser = osBrowser();
        notify($counterManager, 'PASS_RESET_DONE', [
            'operating_system' => isset($userBrowser['os_platform']) ? $userBrowser['os_platform'] : '',
            'browser' => isset($userBrowser['browser']) ? $userBrowser['browser'] : '',
            'ip' => isset($userIpInfo['ip']) ? $userIpInfo['ip'] : '',
            'time' => isset($userIpInfo['time']) ? $userIpInfo['time'] : ''
        ], ['email']);

        $notify[] = ['success', 'Password changed successfully'];
        return to_route('counter.manager.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],
        ];
    }
}
