<?php
/**
 * Consolety Uninstall
 *
 * Fired when the plugin is uninstalled.
 * Cleans up all plugin data from the database.
 *
 * @package Consolety
 * @since   1.0.0
 */

// If uninstall not called from WordPress, exit.
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

/**
 * Clean up all Consolety options from the database.
 *
 * This runs when a user deletes the plugin (not just deactivates).
 * We remove all options to leave no traces in the database.
 */

// Notify Hub that plugin is being uninstalled BEFORE deleting token
$consolety_token = get_option('consolety_trust_token');
if (!empty($consolety_token)) {
    wp_remote_post('https://app.consolety.ai/api/v1/site/disconnect', [
        'method'   => 'POST',
        'timeout'  => 5,
        'blocking' => false,
        'headers'  => [
            'Authorization' => 'Bearer ' . $consolety_token,
            'X-Site-URL'    => home_url(),
            'Accept'        => 'application/json',
            'Content-Type'  => 'application/json',
        ],
        'body' => wp_json_encode(['reason' => 'plugin_uninstalled']),
    ]);
}

// List of all options used by Consolety
$consolety_options_to_delete = array(
    // Core connection options
    'consolety_trust_token',
    'consolety_api_token',  // Legacy key
    'consolety_site_id',
    'consolety_tier',
    'consolety_webhook_secret',

    // Site information
    'consolety_site_info',
    'consolety_metrics',
    'consolety_last_sync',
    'consolety_last_heartbeat',

    // User preferences
    'consolety_guest_post_requirements',
    'consolety_profile_category',
    'consolety_profile_language',
    'consolety_profile_bio',

    // Cache and transients
    'consolety_partners_cache',
    'consolety_network_stats_cache',
    'consolety_points_history_cache',

    // Feature flags
    'consolety_link_monitor_enabled',
    'consolety_notifications_enabled',

    // Plugin state
    'consolety_version',
    'consolety_installed_at',
    'consolety_first_activation',
);

// Delete each option
foreach ($consolety_options_to_delete as $consolety_option) {
    delete_option($consolety_option);

    // Also delete from network options if multisite
    if (is_multisite()) {
        delete_site_option($consolety_option);
    }
}

// Clear any scheduled cron events
$consolety_cron_hooks = array(
    'consolety_daily_sync',
    'consolety_heartbeat',
    'consolety_check_links',
    'consolety_daily_points_drip',
    'consolety_cleanup_expired_drafts',
);

foreach ($consolety_cron_hooks as $consolety_hook) {
    $consolety_timestamp = wp_next_scheduled($consolety_hook);
    if ($consolety_timestamp) {
        wp_unschedule_event($consolety_timestamp, $consolety_hook);
    }
    // Clear all instances of the hook
    wp_clear_scheduled_hook($consolety_hook);
}

// Delete any transients with our prefix
global $wpdb;

// Delete transients
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
        '_transient_consolety_%',
        '_transient_timeout_consolety_%'
    )
);

// If multisite, clean up network transients too
if (is_multisite()) {
    $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->prepare(
            "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s OR meta_key LIKE %s",
            '_site_transient_consolety_%',
            '_site_transient_timeout_consolety_%'
        )
    );
}

// Note: We intentionally do NOT delete published guest posts.
// Those are regular WordPress posts that should remain even after plugin removal.
// The content belongs to the site owner and should not be deleted automatically.

// Optional: Log the uninstall for debugging (remove in production)
// error_log('Consolety: Plugin uninstalled and data cleaned up.');
