<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AuthStudent
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //check if user is logged in
        $student = auth()->guard('student')->user();

        //if not, redirect to student login page
        if (!$student) {
            return redirect()->route('student.login.index');
        }

        //check if session matches the one stored in database (prevent concurrent login)
        if ($student->session_id !== session()->getId()) {
            auth()->guard('student')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('student.login.index')
                ->with('error', 'Akun Anda telah login di perangkat lain. Silakan login kembali.');
        }

        //if user is logged in, continue to next middleware
        return $next($request);
    }
}