<?php

namespace Modules\VetPortal\Http\Controllers\Portal;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (Auth::guard('pet_owner')->check()) {
            return redirect()->route('vp.portal.dashboard');
        }
        return view('vetPortal::portal.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string',
        ]);

        $credentials = [
            'email'    => strtolower(trim($request->email)),
            'password' => $request->password,
        ];

        if (Auth::guard('pet_owner')->attempt($credentials, $request->boolean('remember'))) {
            $account = Auth::guard('pet_owner')->user();

            if (!$account->enabled) {
                Auth::guard('pet_owner')->logout();
                return back()->withErrors(['email' => 'This account is disabled. Please contact the clinic.'])->withInput();
            }

            $settings = \Modules\VetPortal\Entities\VpPortalSetting::forBusiness($account->business_id);
            if (!$settings->enabled) {
                Auth::guard('pet_owner')->logout();
                return back()->withErrors(['email' => 'The portal is currently unavailable. Please contact the clinic.'])->withInput();
            }

            $account->forceFill(['last_login_at' => now()])->save();
            $request->session()->regenerate();

            return redirect()->intended(route('vp.portal.dashboard'));
        }

        return back()->withErrors(['email' => 'Incorrect email or password.'])->withInput();
    }

    public function logout(Request $request)
    {
        Auth::guard('pet_owner')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('vp.portal.login');
    }
}
