<?php
/**
 * Copyright (c) 2025 Teleship Limited. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @package Teleship
 */

/**
 * Teleship Global Shipping Uninstall
 *
 * Minimal cleanup of local data - API call is handled during deactivation.
 *
 * @package Teleship
 */

// Exit if accessed directly
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// Clean up local Teleship data only
function teleship_local_cleanup() {
    // Log uninstallation only in debug mode using proper WP logging
    if (defined('WP_DEBUG') && WP_DEBUG) {
        if (function_exists('wp_debug_log')) {
            wp_debug_log('Teleship plugin uninstall - performing local cleanup only');
        }
    }

    // Remove Teleship options
    delete_option('teleship_api_url');
    delete_option('teleship_installation_id');
    delete_option('teleship_connected');
    delete_option('teleship_active');

    // Get all posts with Teleship meta data
    $meta_keys = array(
        '_teleship_integration',
        '_teleship_tracking_number',
        '_teleship_carrier',
        '_teleship_fulfillment_id'
    );

    // For an uninstall script, it's acceptable to use a direct approach
    // as this only runs once when the plugin is deleted
    foreach ($meta_keys as $meta_key) {
        // Delete all instances of this meta key using WordPress functions
        delete_metadata('post', 0, $meta_key, '', true);
    }
}

// Run local cleanup only
teleship_local_cleanup();
