<?php

/**
 * MassPost — uninstall cleanup
 */
defined('WP_UNINSTALL_PLUGIN') || exit;

/**
 * Per-site cleanup.
 */
function masspost_uninstall_site()
{
    global $wpdb;

    // 1) Known option keys used by MassPost
    $option_keys = array(
        'masspost_websites',
        'masspost_api_token',
        'masspost_api_user',
        // 'masspost_version', // (add later if you store one)
    );
    foreach ($option_keys as $key) {
        delete_option($key);
    }

    // 2) Autoloaded options with "masspost_" prefix (safe sweep via core API)
    if (function_exists('wp_load_alloptions')) {
        $all = wp_load_alloptions();
        if (is_array($all)) {
            foreach ($all as $name => $_v) {
                if (0 === strpos($name, 'masspost_')) {
                    delete_option($name);
                }
            }
        }
    }

    // 3) Fallback: any remaining options "masspost_%"
    if ($wpdb instanceof wpdb) {
        $like = $wpdb->esc_like('masspost_') . '%';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $opt_names = $wpdb->get_col($wpdb->prepare("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", $like));
        if ($opt_names) {
            foreach ($opt_names as $name) {
                delete_option($name);
            }
        }
    }

    // 4) Transients with "masspost_" prefix (both value and timeout rows)
    if ($wpdb instanceof wpdb) {
        $t1 = $wpdb->esc_like('_transient_mmasspost_') . '%';
        $t2 = $wpdb->esc_like('_transient_timeout_masspost_') . '%';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
                $t1,
                $t2
            )
        );
    }

    // 5) Unschedule ANY cron events created by MassPost (defensive)
    if (function_exists('_get_cron_array')) {
        $cron = _get_cron_array();
        if (is_array($cron)) {
            foreach ($cron as $ts => $hooks) {
                foreach ($hooks as $hook => $events) {
                    if (strpos($hook, 'masspost_') !== 0) {
                        continue;
                    }
                    foreach ($events as $sig => $data) {
                        $args = isset($data['args']) ? (array) $data['args'] : array();
                        wp_unschedule_event((int) $ts, $hook, $args);
                    }
                    wp_clear_scheduled_hook($hook);
                }
            }
        }
    }

    // 6) Post meta keys used by MassPost (do NOT delete user content)
    $post_meta_keys = array(
        '_masspost_source_post_id',
        '_masspost_selected_sites',
        '_masspost_content_hash',
        '_masspost_featured_src',
        '_masspost_synced_images',
    );
    foreach ($post_meta_keys as $key) {
        delete_post_meta_by_key($key);
    }

    // Also sweep any unexpected keys with "masspost_" or "_masspost_" prefixes
    if ($wpdb instanceof wpdb) {
        foreach (array('masspost_%', '_masspost_%') as $pattern) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $keys = $wpdb->get_col(
                $wpdb->prepare("SELECT DISTINCT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE %s", $pattern)
            );
            if ($keys) {
                foreach ($keys as $key) {
                    delete_post_meta_by_key($key);
                }
            }
        }
    }

    // 7) User meta keys (none currently, but sweep defensively)
    if ($wpdb instanceof wpdb) {
        foreach (array('masspost_%', '_masspost_%') as $pattern) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $keys = $wpdb->get_col(
                $wpdb->prepare("SELECT DISTINCT meta_key FROM {$wpdb->usermeta} WHERE meta_key LIKE %s", $pattern)
            );
            if ($keys) {
                foreach ($keys as $key) {
                    delete_metadata('user', 0, $key, '', true);
                }
            }
        }
    }

    // 8) Term meta keys (not used by MassPost; sweep defensively if present)
    if ($wpdb instanceof wpdb && property_exists($wpdb, 'termmeta')) {
        foreach (array('masspost_%', '_masspost_%') as $pattern) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $keys = $wpdb->get_col(
                $wpdb->prepare("SELECT DISTINCT meta_key FROM {$wpdb->termmeta} WHERE meta_key LIKE %s", $pattern)
            );
            if ($keys) {
                foreach ($keys as $key) {
                    delete_metadata('term', 0, $key, '', true);
                }
            }
        }
    }

    // 9) Roles/caps (MassPost doesn't add them; remove just in case)
    if (function_exists('get_role')) {
        foreach (array('administrator', 'editor') as $role_name) {
            if ($role = get_role($role_name)) {
                $role->remove_cap('masspost_manage');
            }
        }
    }
    if (function_exists('remove_role')) {
        remove_role('masspost_manager');
    }

    // 10) (Optional) Custom plugin tables — not used by MassPost. Example:
    /*
    if ( $wpdb instanceof wpdb ) {
        $tables = array(
            $wpdb->prefix . 'masspost_logs',
            $wpdb->prefix . 'masspost_queue',
        );
        foreach ( $tables as $table ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
            $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
        }
    }
    */
}

/**
 * Multisite-aware: clean every site, then network options.
 */
if (function_exists('is_multisite') && is_multisite()) {
    $masspost_site_ids = function_exists('get_sites') ? get_sites(array('fields' => 'ids')) : array();
    if (is_array($masspost_site_ids)) {
        foreach ($masspost_site_ids as $masspost_site_id) {
            switch_to_blog($masspost_site_id);
            masspost_uninstall_site();
            restore_current_blog();
        }
    }

    // Network-level options in sitemeta with "masspost_" prefix
    global $wpdb;
    if ($wpdb instanceof wpdb && property_exists($wpdb, 'sitemeta')) {
        $masspost_like_net = $wpdb->esc_like('masspost_') . '%';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $masspost_keys = $wpdb->get_col(
            $wpdb->prepare("SELECT meta_key FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s", $masspost_like_net)
        );
        if ($masspost_keys) {
            foreach ($masspost_keys as $masspost_key) {
                delete_site_option($masspost_key);
            }
        }
    }
} else {
    masspost_uninstall_site();
}
