<?php

namespace App\Http\Middleware;
use app\Modals\Setting;
use app\Modals\Activity;
use Closure;
use Carbon\Carbon;

class StudentUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      $user = \Auth::user();
      if(!$user->hasRole('Student'))
      {
        return redirect()->route('user.logout');
      }
      else
      {
        $set = Setting::first();
        $activity = Activity::where('user_id',$user->id)->orderBy('created_at' , 'DESC')->first();
        $logtime = $activity->created_at;
        $outtime = (int) $set->student_time;
        $curr_time = Carbon::now();
        $comptime = $logtime->addMinutes($outtime);


        if($comptime < $curr_time)
        {
          $user = \Auth::user();
          $activity = new Activity();
          $activity->user_id = $user->id;
          $activity->activity_time = $comptime;
          $activity->activity_type = "logout";
          $activity->activity_method = "system";
          $activity->save();
          return redirect()->route('user.logout2');
        }
        else
        {
          return $next($request);
        }
    }
    }
}
