<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Crypt;

class LicenseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (config('app.license.disabled')) {
            return $next($request);
        }
        if (config('app.license.key', false)) {
            $licenseDomain = Arr::last(explode('|', Crypt::decrypt(env('APP_LICENSE_KEY'))[0]));
            // site url without protocol and www
            $pureSiteUrl = strpos($_SERVER['HTTP_HOST'], 'www.') !== false ? substr($_SERVER['HTTP_HOST'], 4) : $_SERVER['HTTP_HOST'];
            if (strpos($licenseDomain, $pureSiteUrl) === false) {
                abort(403, 'CHECK LICENSE PLEASE!');
            }
        } else {
            return redirect()->route('setup.view', ['step' => 1]);
        }

        return $next($request);
    }
}
