<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Core;

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

class Uninstaller {

	public static function uninstall() {
		// Check if user has permission to uninstall
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}

		// Remove database tables
		self::remove_database_tables();

		// Remove all plugin options
		self::remove_plugin_options();

		// Clear any remaining cron events
		self::clear_cron_events();

		// Remove any uploaded media files that were tagged as Wisewand uploads
		self::cleanup_media_files();
	}

	private static function remove_database_tables() {
		global $wpdb;

		$tables = array(
			$wpdb->prefix . 'wisewand_logs',
			$wpdb->prefix . 'wisewand_rate_limits',
			$wpdb->prefix . 'wisewand_pull_queue',
		);

		foreach ( $tables as $table ) {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Table names from $wpdb->prefix array above, DDL DROP TABLE statement
			$wpdb->query( "DROP TABLE IF EXISTS $table" );
		}
	}

	private static function remove_plugin_options() {
		$options_to_remove = array(
			'wisewand_plugin_version',
			'wisewand_hmac_secret',
			'wisewand_timestamp_skew',
			'wisewand_ip_whitelist',
			'wisewand_rate_limit_enabled',
			'wisewand_rate_limit_requests',
			'wisewand_rate_limit_window',
			'wisewand_enable_app_passwords',
			'wisewand_allowed_post_types',
			'wisewand_default_post_status',
			'wisewand_fallback_author',
			'wisewand_auto_create_categories',
			'wisewand_auto_create_tags',
			'wisewand_allow_slug_override',
			'wisewand_media_max_size',
			'wisewand_media_timeout',
			'wisewand_allowed_mime_types',
			'wisewand_download_inline_images',
			'wisewand_allowed_domains',
			'wisewand_seo_mode',
			'wisewand_seo_meta_mapping',
			'wisewand_wpml_enabled',
			'wisewand_wpml_lang_mapping',
			'wisewand_wpml_default_lang',
			'wisewand_logging_enabled',
			'wisewand_debug_mode',
			'wisewand_log_max_entries',
			'wisewand_log_retention_days',
			'wisewand_pull_api_key',
			'wisewand_pull_base_url',
			'wisewand_pull_timeout',
			'wisewand_acf_enabled',
			'wisewand_acf_mode',
			'wisewand_acf_mapping',
			'wisewand_custom_fields_whitelist',
		);

		foreach ( $options_to_remove as $option ) {
			delete_option( $option );
		}
	}

	private static function clear_cron_events() {
		// Clear main cleanup cron
		wp_clear_scheduled_hook( 'wisewand_cleanup_logs' );

		// Clear all pull retry crons
		wp_clear_scheduled_hook( 'wisewand_pull_retry' );
	}

	private static function cleanup_media_files() {
		global $wpdb;  // v1.3.4: Moved outside comment block - needed for meta cleanup below

		// DISABLED: Post deletion is too dangerous and violates WordPress.org guidelines
		//
		// WordPress.org Guidelines: Plugins MUST NOT delete user content without explicit confirmation
		// Previous behavior: Permanently deleted ALL posts created by Wisewand on plugin uninstall
		//
		// Users who want to delete posts should:
		// 1. Use "Cleanup RSS Data" button BEFORE uninstalling (deletes RSS posts)
		// 2. Use WordPress bulk actions to delete posts manually
		// 3. Or use a separate cleanup plugin
		//
		// This prevents accidental content loss when users reinstall/update the plugin

		// The code below is COMMENTED OUT for safety:
		/*
		// Get all posts with Wisewand external_id
		$wisewand_posts = $wpdb->get_col(
			"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wisewand_external_id'"
		);

		foreach ( $wisewand_posts as $post_id ) {
			// Get attachments for this post
			$attachments = get_attached_media( '', $post_id );

			// Delete attachments
			foreach ( $attachments as $attachment ) {
				wp_delete_attachment( $attachment->ID, true );
			}

			// Delete the post
			wp_delete_post( $post_id, true );
		}
		*/ // END DISABLED CODE

		// Clean up orphaned Wisewand meta (safe to remove - just metadata)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Delete plugin meta from postmeta table during uninstall cleanup, meta_key filter acceptable for one-time uninstall operation
		$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_wisewand_external_id' ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Delete plugin meta from postmeta table during uninstall cleanup, meta_key filter acceptable for one-time uninstall operation
		$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_wisewand_input_data' ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Delete plugin meta from postmeta table during uninstall cleanup, meta_key filter acceptable for one-time uninstall operation
		$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_wisewand_schema_json' ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Delete plugin meta from postmeta table during uninstall cleanup, meta_key filter acceptable for one-time uninstall operation
		$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_wisewand_audio_url' ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Delete plugin meta from postmeta table during uninstall cleanup, meta_key filter acceptable for one-time uninstall operation
		$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_wisewand_cover_images' ) );
	}
}
