<?php

namespace Formatrica;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Formatrica\Admin\Admin_Service_Provider;
use Formatrica\Assets\Assets_Service_Provider;
use Formatrica\Frontend\Frontend_Service_Provider;
use Formatrica\Registration\Registration_Service_Provider;
use Formatrica\REST\Rest_Service_Provider;
use Formatrica\Setup\Service_Locator;

/**
 * Main plugin orchestrator.
 */
final class Plugin
{
    private Service_Locator $services;

    public function __construct()
    {
        $this->services = new Service_Locator();
    }

    public function boot(): void
    {
        add_action('init', [$this, 'on_init'], 1); // Priority 1 to run early in init
        add_filter('plugin_row_meta', [$this, 'plugin_row_meta'], 10, 2);

        // Self-hosted Free updates (plan §3.3): the update client exists only
        // in the selfhost package (file excluded from wporg — wp.org owns its
        // updates — and from pro, which has its own Update_Service) and only
        // activates under the matching package stamp.
        if (
            defined('FORMATRICA_PACKAGE')
            && FORMATRICA_PACKAGE === 'selfhost'
            && class_exists(Distribution\Selfhost\Free_Update_Service::class)
        ) {
            Distribution\Selfhost\Free_Update_Service::register();
        }
    }

    /**
     * @param array<int, string> $meta
     * @return array<int, string>
     */
    public function plugin_row_meta(array $meta, string $file): array
    {
        if ($file !== plugin_basename(FORMATRICA_FILE)) {
            return $meta;
        }

        $meta[] = '<a href="https://docs.nexusplugins.com" target="_blank">' . esc_html__('Docs', 'formatrica') . '</a>';
        $meta[] = '<a href="https://support.nexusplugins.com" target="_blank">' . esc_html__('Get Support', 'formatrica') . '</a>';
        $meta[] = '<a href="https://nexusplugins.com/bug-report" target="_blank">' . esc_html__('Report Bugs', 'formatrica') . '</a>';

        return $meta;
    }

    public function on_init(): void
    {
        $this->register_services();
    }

    private function register_services(): void
    {
        $providers = [
            new Capability\Capability_Service_Provider(),
            new Setup\Setup_Service_Provider(),
            new Assets_Service_Provider(),
            new Admin_Service_Provider(),
            new Rest_Service_Provider(),
            new Frontend_Service_Provider(),
            new Registration_Service_Provider(),
        ];

        foreach ($providers as $provider) {
            $provider->register($this->services);
        }
    }
}
