<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class LogoutArchivedUsers
{
    const ARCHIVED = 'archived';

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return Response|RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();
            $isArchived = null;
            if ($user->is_active) {
                if ($user->is_active == 2) {
                    $isArchived = self::ARCHIVED;
                }
            } elseif ($user->archived_status) {
                if ($user->archived_status == 1) {
                    $isArchived = self::ARCHIVED;
                }
            }
            if ($isArchived === self::ARCHIVED) {
                Auth::logout();
                $support = '<a href="' . route('support-ticket.index') . '" target="_blank">Contact Support</a>.';
                flash('Your profile has been archived. ' . $support);
            }
        }

        return $next($request);
    }
}
