<?php
if (!defined('ABSPATH')) exit;

class SS_Multisite_Guard {

    public static function init() {
        if (!is_multisite()) return;

        add_action('admin_init',            [__CLASS__, 'enforce_single_site']);
        add_action('network_admin_notices', [__CLASS__, 'network_notice']);
    }

    /** If plugin was network-activated, auto-deactivate and redirect with a notice. */
    public static function enforce_single_site() {
        if (!is_network_admin()) return;

        // Need plugin functions
        if (!function_exists('is_plugin_active_for_network')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        // Safety: ensure we know our own basename
        if (!defined('SEARCHSHIFTER_BASENAME')) return;

        if (is_plugin_active_for_network(SEARCHSHIFTER_BASENAME)) {
            // Deactivate network-wide silently
            deactivate_plugins(SEARCHSHIFTER_BASENAME, /*silent*/ true, /*network_wide*/ true);

            // Set a one-time notice and bounce back to Network Plugins
            if (function_exists('set_site_transient')) {
                set_site_transient('ss_multisite_block_notice', 1, 60);
            }
            wp_safe_redirect(network_admin_url('plugins.php?ss_net_block=1'));
            exit;
        }
    }

    /** Show the required message in the Network Plugins screen. */
    public static function network_notice() {
        if (!is_network_admin()) return;

        $show = isset($_GET['ss_net_block']) || (function_exists('get_site_transient') && get_site_transient('ss_multisite_block_notice'));
        if (!$show) return;

        if (function_exists('delete_site_transient')) {
            delete_site_transient('ss_multisite_block_notice');
        }

        echo '<div class="notice notice-warning is-dismissible"><p>'
           . esc_html__('SearchShifter™ is licensed per site. Network Activate is disabled. Please activate on individual sites with a valid license.', 'searchshifter')
           . '</p></div>';
    }
}
