<?php

namespace Core\System\Updates;

use Core\App\Models\Settings;
use Core\System\License\LicenseStorage;
use Core\System\Version;

class InstalledItemsService
{
    public function all(): array
    {
        $items = [];
        $cache = \Core\System\License\LicenseStorage::getCache() ?: [];
        $mainProduct = trim((string)($cache['product'] ?? ''));
        if ($mainProduct === '') {
            $mainProduct = Version::product();
        }

        $settings = new Settings();
        $mainLicenseKey = trim((string)$settings->get('license_key', ''));

        $items[] = [
            'identifier' => 'core:' . strtolower($mainProduct),
            'name' => (string)($cache['product_name'] ?? $mainProduct),
            'kind' => 'core',
            'product' => $mainProduct,
            'plugin_slug' => null,
            'current_version' => Version::current(),
            'folder' => null,
            'license_key' => $mainLicenseKey,
        ];

        $pluginsBase = ROOT_PATH . '/plugins';
        if (is_dir($pluginsBase)) {
            $activeSlugs = $this->activePluginSlugs();
            foreach (glob($pluginsBase . '/*/plugin.json') as $manifestPath) {
                $manifest = json_decode((string) file_get_contents($manifestPath), true) ?: [];
                $slug = trim((string)($manifest['slug'] ?? ''));
                if ($slug === '' || $slug === 'safe-updater') continue;
                if (!empty($activeSlugs) && !in_array($slug, $activeSlugs, true)) continue;

                $folder = dirname($manifestPath);
                $items[] = [
                    'identifier' => 'plugin:' . $slug,
                    'name' => (string)($manifest['name'] ?? $slug),
                    'kind' => 'plugin',
                    'product' => $mainProduct,
                    'plugin_slug' => $slug,
                    'current_version' => (string)($manifest['version'] ?? '1.0.0'),
                    'folder' => $folder,
                    'license_key' => $this->detectPluginLicenseKey($folder),
                ];
            }
        }

        return $items;
    }

    public function find(string $identifier): ?array
    {
        foreach ($this->all() as $item) {
            if (($item['identifier'] ?? '') === $identifier) {
                return $item;
            }
        }
        return null;
    }

    private function activePluginSlugs(): array
    {
        try {
            $stmt = db()->query("SELECT slug FROM plugins WHERE is_active = 1");
            return $stmt->fetchAll(\PDO::FETCH_COLUMN) ?: [];
        } catch (\Throwable $e) {
            return [];
        }
    }

    private function detectPluginLicenseKey(string $folder): string
    {
        $table = $this->detectPluginSettingsTable($folder);
        if ($table === '') return '';

        try {
            $stmt = db()->query("SELECT license_key FROM `{$table}` LIMIT 1");
            return trim((string)$stmt->fetchColumn());
        } catch (\Throwable $e) {
            return '';
        }
    }

    private function detectPluginSettingsTable(string $folder): string
    {
        $it = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS)
        );

        foreach ($it as $file) {
            if (!$file->isFile() || strtolower($file->getExtension()) !== 'php') {
                continue;
            }

            $code = (string) @file_get_contents($file->getPathname());
            if ($code === '') continue;

            if (preg_match('/SELECT\s+license_key\s+FROM\s+`?([a-zA-Z0-9_]+)`?/i', $code, $m)) {
                return $m[1];
            }

            if (preg_match('/FROM\s+`?([a-zA-Z0-9_]+_settings)`?\s+LIMIT\s+1/i', $code, $m) && stripos($code, 'license_key') !== false) {
                return $m[1];
            }
        }
        return '';
    }
}
