<?php
/**
 * Plugin deactivation: clears scheduled events.
 *
 * @package Brainwerk SEO Suite
 */

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

class Seoforge_Deactivator {
    public static function deactivate( $network_wide = false ) {
        self::clear_cron_hooks();

        // Cron events are per-site (Seoforge_Activator::schedule_events() now
        // loops sites the same way), so a network-wide deactivation must clear
        // them per-site too, or every subsite but the one WP called
        // deactivate() on keeps a now-orphaned cron running forever.
        if ( $network_wide && is_multisite() ) {
            $sites = get_sites( array( 'number' => 0, 'fields' => 'ids' ) );
            foreach ( $sites as $blog_id ) {
                switch_to_blog( (int) $blog_id );
                self::clear_cron_hooks();
                restore_current_blog();
            }
        }

        // Refresh (or clear) the reinstall backup right before a possible delete —
        // WordPress requires deactivation before deletion, so this captures the
        // final configuration for uninstall.php to preserve.
        if ( class_exists( 'Seoforge_Settings' ) ) {
            if ( Seoforge_Settings::get( 'persist_settings', true ) ) {
                Seoforge_Settings::write_backup();
            } else {
                Seoforge_Settings::delete_backup();
            }
        }
    }

    private static function clear_cron_hooks() {
        // Canonical list — see Seoforge_Cron_Hooks for what fires each hook
        // (Free + Pro, whether or not the Pro modules are present here).
        foreach ( Seoforge_Cron_Hooks::all() as $hook ) {
            wp_clear_scheduled_hook( $hook );
        }
    }
}
