<?php

namespace App\Http\Middleware;

use App\Models\MarketplacePurchase;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\Response;

class EnsurePluginActive
{
    public function handle(Request $request, Closure $next, string $plugin): Response
    {
        if (MarketplacePurchase::hasPurchased('plugin', $plugin)) {
            return $next($request);
        }
        if (in_array($plugin, config('cms.marketplace_only_plugins', []), true)) {
            abort(404, 'Plugin non activé.');
        }
        $customPath = config('cms.custom_plugins_path');
        if ($customPath && File::isDirectory($customPath)) {
            $pluginDir = $customPath.'/'.$plugin;
            if (File::isDirectory($pluginDir) && File::exists($pluginDir.'/plugin.json')) {
                $config = json_decode(File::get($pluginDir.'/plugin.json'), true);
                if ($config && ($config['source'] ?? '') === 'custom') {
                    return $next($request);
                }
            }
        }
        abort(404, 'Plugin non activé.');
    }
}
