<?php

namespace App\Http\Middleware;

use App\Licensing\Services\Lixvalid;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * License Middleware (LixMiddleware)
 * Protects admin routes while allowing frontend read-only access
 * Complies with Envato rules: graceful degradation, no kill switch
 */
class LixMiddleware
{
    public function __construct(
        private Lixvalid $lixvalid
    ) {}

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $type  'admin' or 'frontend'
     */
    public function handle(Request $request, Closure $next, string $type = 'admin'): Response
    {
        // Frontend routes are always accessible (read-only)
        if ($type === 'frontend') {
            return $next($request);
        }

        // Admin routes require valid license
        if ($type === 'admin') {
            $status = $this->lixvalid->getStatus();

            // If license is valid, allow access
            if ($status['valid'] === true && $status['can_use'] === true) {
                // Share license status with views
                view()->share('licenseStatus', $status);

                return $next($request);
            }

            // License invalid - show warning but allow access (graceful degradation)
            // This complies with Envato rules: no kill switch, no destructive behavior
            view()->share('licenseStatus', $status);
            view()->share('licenseWarning', true);

            // Still allow access but with warning banner
            return $next($request);
        }

        return $next($request);
    }
}
