<?php

namespace App\Http\Controllers\Auth;

use App\Enum\AdminStatus;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AuthenticatedSessionController extends Controller
{
    public function create(): View
    {
        return view('auth.login', ['title' => 'Login Account']);
    }

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

        $credentials = [
            'email'     => $request->email,
            'password'  => $request->password
        ];

        $remember = $request->remember;

        if (auth('admin')->attempt($credentials, $remember)) {

            if (auth('admin')->user()->status == AdminStatus::INACTIVE->value) {
                Auth::guard('admin')->logout();
                return back()->withErrors(['email' => 'Your account is inactive. Please contact your administrator.']);
            }

            return redirect()->route('admin.dashboard');
        }
        if (auth('master')->attempt($credentials, $remember)) {
            return redirect()->route('master.dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function destroy()
    {
        Auth::guard('admin')->logout();

        Auth::guard('master')->logout();

        return redirect('/login');
    }
}
