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

/**
 * Only delete data if the user opted in via:
 * Settings → Simple Amazon Affiliate → “Delete all data on uninstall”.
 */
$options = get_option('saa_options', []);
if (!is_array($options) || empty($options['delete_on_uninstall'])) {
    // Respect user's choice to keep data.
    return;
}

/**
 * 1) Remove plugin options
 */
delete_option('saa_options');
$asins = get_option('saa_cached_asins', []);
delete_option('saa_cached_asins');

/**
 * 2) Remove cached transients for any remembered ASINs
 */
if (is_array($asins)) {
    foreach ($asins as $asin) {
        $key = 'saa_api_' . strtolower(sanitize_key((string) $asin));
        delete_transient($key);
    }
}

/**
 * 3) Remove all post meta that stores per-post product data
 */
if (function_exists('delete_post_meta_by_key')) {
    delete_post_meta_by_key('_saa_products');
}

/**
 * 4) Unschedule the weekly cron (if present)
 */
if (function_exists('wp_next_scheduled') && function_exists('wp_unschedule_event')) {
    $ts = wp_next_scheduled('saa_weekly_price_refresh');
    if ($ts) {
        wp_unschedule_event($ts, 'saa_weekly_price_refresh');
    }
}
