<?php

namespace App\Services;

use App\Models\MarketplacePurchase;
use Illuminate\Support\Facades\File;

class PluginService
{
    protected string $pluginsPath;

    public function __construct()
    {
        $this->pluginsPath = base_path('plugins');
    }

    public function getInstalledPlugins(): array
    {
        $plugins = [];

        // Plugins core (dans plugins/)
        if (File::isDirectory($this->pluginsPath)) {
            foreach (File::directories($this->pluginsPath) as $dir) {
                $configPath = $dir.'/plugin.json';
                if (File::exists($configPath)) {
                    $config = json_decode(File::get($configPath), true);
                    if ($config) {
                        $slug = $config['slug'] ?? basename($dir);
                        $plugins[] = array_merge($config, [
                            'path' => basename($dir),
                            'is_active' => MarketplacePurchase::hasPurchased('plugin', $slug),
                            'source' => $config['source'] ?? 'core',
                        ]);
                    }
                }
            }
        }

        // Plugins personnalisés (dans content/plugins/)
        $customPath = config('cms.custom_plugins_path');
        $marketplaceSlugs = array_column(config('marketplace_catalog.plugins', []), 'slug');
        if ($customPath && File::isDirectory($customPath)) {
            foreach (File::directories($customPath) as $dir) {
                $configPath = $dir.'/plugin.json';
                if (File::exists($configPath)) {
                    $config = json_decode(File::get($configPath), true);
                    if ($config) {
                        $slug = $config['slug'] ?? basename($dir);
                        $isMarketplaceSlug = in_array($slug, $marketplaceSlugs, true);
                        $plugins[] = array_merge($config, [
                            'path' => basename($dir),
                            'is_active' => $isMarketplaceSlug ? MarketplacePurchase::hasPurchased('plugin', $slug) : true,
                            'source' => $config['source'] ?? 'custom',
                        ]);
                    }
                }
            }
        }

        return $plugins;
    }

    /**
     * Retourne les types de sections fournis par les plugins achetés/activés.
     */
    public function getPluginSectionTypes(): array
    {
        $types = [];
        $activePlugins = MarketplacePurchase::where('item_type', 'plugin')
            ->where('is_active', true)
            ->where('admin_enabled', true)
            ->pluck('item_slug')
            ->toArray();

        $pathsToScan = array_filter([
            $this->pluginsPath,
            config('cms.custom_plugins_path'),
        ], fn ($p) => $p && File::isDirectory($p));

        foreach ($pathsToScan as $basePath) {
            foreach (File::directories($basePath) as $dir) {
                $configPath = $dir.'/plugin.json';
                if (! File::exists($configPath)) {
                    continue;
                }
                $config = json_decode(File::get($configPath), true);
                if (! $config) {
                    continue;
                }
                $slug = $config['slug'] ?? basename($dir);
                $isCustom = ($config['source'] ?? '') === 'custom';
                $isMarketplaceSlug = in_array($slug, array_column(config('marketplace_catalog.plugins', []), 'slug'), true);
                $hasAccess = in_array($slug, $activePlugins, true);
                if ($isCustom && $isMarketplaceSlug && ! $hasAccess) {
                    continue;
                }
                if (! $isCustom && ! $hasAccess) {
                    continue;
                }
                $sections = $config['sections'] ?? [];
                foreach ($sections as $type => $info) {
                    $types[$type] = [
                        'label' => $info['label'] ?? ucfirst($type),
                        'icon' => $info['icon'] ?? '◆',
                        'plugin' => $slug,
                    ];
                }
            }
        }
        return $types;
    }
}
