<?php
/**
 * Plugin uninstall — runs when the user deletes the plugin from
 * WP-admin (not on simple deactivate). Removes plugin options, the
 * dismiss-state on the welcome banner, and any leftover preview drafts
 * we created. Media-library uploads stay; they are the user's content.
 *
 * Reasoning:
 *  - The user opted to remove the plugin. Leftover drafts in the WP DB
 *    would be confusing later.
 *  - Per-call usage logs on our proxy stay (anonymous billing-trail).
 *  - We do NOT delete WP revisions of pages — those are normal WP
 *    history and not ours to remove.
 */
if (!defined('WP_UNINSTALL_PLUGIN')) exit;

$option_keys = [
    'sailwp_copilot_installed_at',
    'sailwp_copilot_license_key',
    'sailwp_copilot_site_id',
    'sailwp_copilot_site_api_key',
    'sailwp_copilot_workspace_id',
    'sailwp_copilot_ai_proxy_url',
    'sailwp_copilot_cloud_url',
];
foreach ($option_keys as $k) {
    delete_option($k);
}

// Welcome banner per-user dismiss state.
delete_metadata('user', 0, 'sailwp_copilot_welcome_dismissed', '', true);

// Hard-delete any preview drafts we created.
$previews = get_posts([
    'post_type'      => 'page',
    'post_status'    => ['draft', 'trash', 'private'],
    'meta_key'       => '_swcp_is_preview',
    'meta_value'     => 1,
    'posts_per_page' => 200,
    'fields'         => 'ids',
]);
foreach ($previews as $id) {
    wp_delete_post($id, true);
}

// Clean up any leftover scheduled events.
wp_clear_scheduled_hook('swcp_purge_old_previews');

// Drop the upload-by-copilot meta marker (image attachments stay).
delete_metadata('post', 0, '_swcp_uploaded_via_copilot', '', true);
