<?php

namespace GriffinForms\Includes\Packages;

use GriffinForms\Config;
use GriffinForms\Traits\Singleton;

class PackageRegistry extends \GriffinForms\Format
{
    use Singleton;

    protected $packages = [];

    protected function setPackages()
    {
        $config = Config::getInstance();
        $core_bootstrap = plugin_basename($config->getRootPath() . 'griffinforms.php');

        $packages = [
            'core' => [
                'package_id' => 'core',
                'package_label_internal' => 'Core',
                'package_type' => 'core',
                'package_source' => 'griffinforms_first_party',
                'package_bootstrap_file' => $core_bootstrap,
                'package_version' => Config::VERSION,
                'minimum_core_version' => Config::VERSION,
                'declared_provider_surfaces' => [
                    'fields',
                    'workflows',
                    'menus',
                    'rest',
                    'libraries',
                    'ui_surfaces',
                ],
                'approval_status' => 'approved',
                'integrity_mode' => 'trusted_self',
                'supports_entitlement' => false,
                'supports_updates' => false,
            ],
            'pro' => [
                'package_id' => 'pro',
                'package_label_internal' => 'Pro',
                'package_type' => 'pro',
                'package_source' => 'griffinforms_internal',
                'package_bootstrap_file' => 'griffinforms-form-builder-pro/griffinforms-form-builder-pro.php',
                'package_version' => null,
                'minimum_core_version' => Config::VERSION,
                'declared_provider_surfaces' => [
                    'fields',
                    'workflows',
                    'menus',
                    'rest',
                    'libraries',
                    'ui_surfaces',
                ],
                'approval_status' => 'approved',
                'integrity_mode' => 'approved_unchecked',
                'supports_entitlement' => true,
                'supports_updates' => true,
            ],
        ];

        $packages = apply_filters('griffinforms_register_packages', $packages);
        $this->packages = is_array($packages) ? $packages : [];
    }

    public function getAll(): array
    {
        return $this->packages;
    }

    public function get(string $package_id): ?array
    {
        $package_id = sanitize_key($package_id);
        return $this->packages[$package_id] ?? null;
    }

    public function getByBootstrapFile(string $bootstrap_file): ?array
    {
        $bootstrap_file = plugin_basename($bootstrap_file);

        foreach ($this->packages as $package) {
            if (($package['package_bootstrap_file'] ?? '') === $bootstrap_file) {
                return $package;
            }
        }

        return null;
    }
}
