<?php

namespace _121Digital\Connect\Integration\WordpressSeo;

class WordpressSeo
{
    public function register(): void
    {
        // tmp disable this module from loading for now...
        return;

        try {
            $this->safelyExecuteSeoToolsRuntime();
        } catch (\Exception $e) {
            Plugin::die(esc_html(sprintf('REG121 SEOTools Integration: could not initialize module: %s', $e->getMessage())));
        }
    }

    private function safelyExecuteSeoToolsRuntime(): void
    {
        if ($this->isSeoToolsOptionEnabled() && $this->validateSeoToolsCompatability()) {
            $pluginModuleDirectory = __DIR__;
            $pluginModuleRuntimeEntrypoint = $pluginModuleDirectory . '/wordpress-seo/wp-seo.php';

            if (file_exists($pluginModuleRuntimeEntrypoint)) {
                require_once $pluginModuleRuntimeEntrypoint;
            } else {
                // do not halt frontend execution if the plugin module cannot be loaded.
                if (!is_admin()) {
                    return;
                }

                throw new \Exception('REG121 SEOTools: required runtime file missing: ' . $pluginModuleRuntimeEntrypoint);
            }
        } else {
            if (is_admin()) {
                $this->renderCompatabilityErrorNotice();
            }
        }
    }

    private function isSeoToolsOptionEnabled(): bool
    {
        // return SEOToolsOptionsUtils::isSeoToolsOptionEnabled();
        return true;
    }

    private function renderUnableToLoadModuleNotice(): void
    {
        ?>
        <div class="notice notice-error is-dismissible">
            <p><?php esc_html_e('REG121 SEO Tools Integration: Cannot load SEO Tools module because it is disabled in the plugin settings.', 'reg121-connect'); ?></p>
        </div>
        <?php
    }

    private function renderCompatabilityErrorNotice(): void
    {
        ?>
        <div class="notice notice-error is-dismissible">
            <p><?php esc_html_e('REG121 SEO Tools Integration: Cannot activate SEO Tools module because another SEO plugin is already active. Please deactivate other SEO plugins to use this module.', 'reg121-connect'); ?></p>
        </div>
        <?php
    }

    private function validateSeoToolsCompatability(): bool
    {
        // check if YOAST SEO is installed and active
        if (defined('WPSEO_VERSION')) {
            return false;
        }

        // check if original RankMath SEO is installed and active
        if (defined('RANK_MATH_VERSION')) {
            return false;
        }

        return true; // no SEO tools installed, so we can proceed
    }
}
