<?php

namespace _121Digital\Connect\Integration\ElementsImporter;

use _121Digital\Connect\Admin\Services\NoticeService;
use _121Digital\Connect\Core\Plugin;

class ElementsImporter
{
    public function register(): void
    {
        // Registration logic for the Elements Importer integration
        add_action('init', [$this, 'initElementsImporterModule']);
    }

    public function initElementsImporterModule(): void
    {
        // Initialization logic for the Elements Importer integration
        $file = __DIR__ . '/envato-elements/envato-elements.php';
        if (! file_exists($file)) {
            Plugin::die(esc_html(sprintf('Elements Importer: required file missing: %s', $file)));
        }

        try {
            // verify that the site does not have the Envato Elements plugin already installed.
            // we will display a soft warning in this case and not load our bundled version.
            if (defined('ENVATO_ELEMENTS_VER')) {
                // Add notice early (priority 5) so it's queued before renderCustomNotices runs
                add_action('admin_notices', [$this, 'displayNonBundledNotice'], 5);
                return;
            }

            require_once $file;
        } catch (\Exception $e) {
            Plugin::die(esc_html(sprintf('Elements Importer: could not initialize module: %s', $e->getMessage())));
        }
    }

    public function displayNonBundledNotice(): void
    {
        // Build a nonce-protected deactivate URL for the known Envato Elements plugin main file.
        $plugin_file = 'envato-elements/envato-elements.php';
        $deactivate_button = '';
        $message = __('The Envato Elements plugin is already installed on this site. The bundled version has been disabled to prevent conflicts.', '121-connect');

        if (current_user_can('activate_plugins')) {
            $deactivate_url = wp_nonce_url(self_admin_url('plugins.php?action=deactivate&plugin=' . rawurlencode($plugin_file)), 'deactivate-plugin_' . $plugin_file);
            $deactivate_button = sprintf(
                ' <a href="%1$s" style="text-align: right; float: right; font-size: 12px;">%2$s</a>',
                esc_url($deactivate_url),
                esc_html__('Deactivate Envato Elements', '121-connect')
            );
        }

        // Use NoticeService to display the warning
        NoticeService::addWarning(
            esc_html($message) . $deactivate_button,
            true,
            'envato-elements-bundled-disabled'
        );
    }
}
