<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckContractStatus
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response) $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        // check contract status
        $contract = Auth::user()->contract;
        if ($contract) {
            if ($contract->in_use == 0) {
                abort(403, "Your contract has been deactivated. Contact your system administrator for the possible causes.");
            }
            if (Carbon::parse($contract->d_end)->isPast()) {
                abort(403, "Your contract has expired. Contact your system administrator for renewal.");
            }
        }
        return $next($request);
    }
}
