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

class SS_Multisite_Guard {

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

        // Only relevant on the Network Admin screens
        if ( is_network_admin() ) {
            // Hide the "Network Activate" UI for this plugin
            add_filter('network_admin_plugin_action_links_' . plugin_basename(SEARCHSHIFTER_PLUGIN_FILE), [__CLASS__, 'block_network_action_link'], 10, 1);

            // Prevent sitewide activation being saved to the option
            add_filter('pre_update_option_active_sitewide_plugins', [__CLASS__, 'prevent_sitewide_activation'], 10, 2);

            // If it's already active network-wide (e.g., someone forced it), deactivate immediately
            add_action('admin_init', [__CLASS__, 'maybe_deactivate_sitewide']);

            // Show the official message
            add_action('network_admin_notices', [__CLASS__, 'notice']);
        }
    }

    /** Remove the "Network Activate" link for this plugin in Network Admin */
    public static function block_network_action_link(array $links): array {
        foreach ($links as $k => $html) {
            if (stripos($html, 'activate') !== false) {
                unset($links[$k]);
            }
        }
        // Small hint chip (read-only)
        $links['ss_hint'] = '<span style="color:#8a1f11;">Single-site only</span>';
        return $links;
    }

    /** Stop the plugin from being stored in active_sitewide_plugins when someone clicks Network Activate */
    public static function prevent_sitewide_activation($new, $old) {
        $base = plugin_basename(SEARCHSHIFTER_PLUGIN_FILE);
        if (isset($new[$base])) {
            unset($new[$base]);
            set_site_transient('ss_blocked_network_activate', 1, 60); // show notice once
        }
        return $new;
    }

    /** If the plugin is somehow active network-wide, deactivate it immediately (no fatal) */
    public static function maybe_deactivate_sitewide() {
        $base = plugin_basename(SEARCHSHIFTER_PLUGIN_FILE);
        if ( is_plugin_active_for_network($base) ) {
            deactivate_plugins($base, true, true); // silent, network context
            set_site_transient('ss_blocked_network_activate', 1, 60);
        }
    }

    /** Banner in Network Admin explaining policy */
    public static function notice() {
        if ( get_site_transient('ss_blocked_network_activate') ) {
            delete_site_transient('ss_blocked_network_activate');
            echo '<div class="notice notice-error"><p><strong>SearchShifter&trade;</strong> is licensed per site. <em>Network Activate is disabled.</em> Please activate on individual sites with a valid license.</p></div>';
        }
    }
}
