<?php

if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

// Version 1.1 is single-site only. Never perform a partial one-blog cleanup on multisite.
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
	return;
}
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Uninstall removes only plugin-owned options, meta, transients, and custom tables.

require_once __DIR__ . '/includes/core/class-platform-capabilities.php';
require_once __DIR__ . '/includes/core/helpers.php';
require_once __DIR__ . '/includes/core/class-api-endpoints.php';
require_once __DIR__ . '/includes/core/class-settings.php';

update_option( 'fotogenic_ai_background_runtime_state', 'disabled', false );

function fotogenic_ai_uninstall_cleanup_auth_session(): void {
    $session = get_option( 'fotogenic_ai_auth_session', [] );

    if ( is_array( $session ) ) {
        $encrypted_refresh = trim( (string) ( $session['refreshToken'] ?? '' ) );
        $refresh_token     = '' !== $encrypted_refresh ? \Fotogenic_AI\fotogenic_ai_decrypt_string( $encrypted_refresh ) : '';

        if ( '' !== $refresh_token ) {
            $settings  = \Fotogenic_AI\Settings::instance();
            $base_url  = rtrim( $settings->get_api_base_url(), '/' );
            $base_path = trim( (string) $settings->get_api_base_path(), '/' );
            if ( '' !== $base_path ) {
                $base_url .= '/' . $base_path;
            }
            wp_remote_request(
                $base_url . '/auth/revoke',
                [
                    'method'      => 'POST',
                    'headers'     => [
                        'Accept'       => 'application/json',
                        'Content-Type' => 'application/json',
                    ],
                    'body'        => wp_json_encode(
                        [
                            'platform'     => 'wp',
                            'refreshToken' => $refresh_token,
                        ]
                    ),
                    'timeout'     => 10,
                    'redirection' => 0,
                    'reject_unsafe_urls' => true,
                ]
            );
        }
    }

    delete_option( 'fotogenic_ai_auth_session' );
    wp_unschedule_hook( 'fotogenic_ai_auth_refresh' );
}

fotogenic_ai_uninstall_cleanup_auth_session();

$fotogenic_ai_options      = get_option( 'fotogenic_ai_settings', [] );
$fotogenic_ai_delete_data  = is_array( $fotogenic_ai_options ) && ! empty( $fotogenic_ai_options['delete_data_on_uninstall'] );

// Unschedule all plugin hooks from WP-Cron and Action Scheduler groups.
wp_unschedule_hook( 'fotogenic_ai_log_purge' );
wp_unschedule_hook( 'fotogenic_ai_bulk_tick' );
wp_unschedule_hook( 'fotogenic_ai_store_queue_tick' );
wp_unschedule_hook( 'fotogenic_ai_store_queue_purge' );
wp_unschedule_hook( 'fotogenic_ai_finalize_run' );
wp_unschedule_hook( 'fotogenic_ai_background_housekeeping' );
wp_unschedule_hook( 'fotogenic_ai_bulk_housekeeping' );
wp_unschedule_hook( 'fotogenic_ai_result_delivery_retry' );

if ( function_exists( 'as_unschedule_all_actions' ) ) {
    as_unschedule_all_actions( 'fotogenic_ai_bulk_tick' );
    as_unschedule_all_actions( 'fotogenic_ai_store_queue_tick' );
    as_unschedule_all_actions( 'fotogenic_ai_finalize_run' );
    as_unschedule_all_actions( 'fotogenic_ai_background_housekeeping' );
    as_unschedule_all_actions( 'fotogenic_ai_result_delivery_retry' );
}

delete_option( 'fotogenic_ai_background_runtime_state' );
delete_option( 'fotogenic_ai_background_scheduling_disabled' );

if ( ! $fotogenic_ai_delete_data ) {
    return;
}

global $wpdb;

// Remove plugin options.
delete_option( 'fotogenic_ai_settings' );

$fotogenic_ai_option_prefix_like = $wpdb->esc_like( 'fotogenic_ai_' ) . '%';
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
        $fotogenic_ai_option_prefix_like
    )
);

// Remove transients (and timeout rows) for plugin prefixes.
$fotogenic_ai_transient_like = $wpdb->esc_like( '_transient_fotogenic_ai_' ) . '%';
$fotogenic_ai_timeout_like   = $wpdb->esc_like( '_transient_timeout_fotogenic_ai_' ) . '%';
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
        $fotogenic_ai_transient_like,
        $fotogenic_ai_timeout_like
    )
);

// Remove plugin meta rows.
$fotogenic_ai_user_meta_like        = $wpdb->esc_like( 'fotogenic_ai_' ) . '%';
$fotogenic_ai_private_user_meta_like = $wpdb->esc_like( '_fotogenic_ai_' ) . '%';
$fotogenic_ai_post_meta_like        = $wpdb->esc_like( '_fotogenic_ai_' ) . '%';
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s OR meta_key LIKE %s",
        $fotogenic_ai_user_meta_like,
        $fotogenic_ai_private_user_meta_like
    )
);
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
        $fotogenic_ai_post_meta_like
    )
);

// Drop custom plugin tables.
$fotogenic_ai_tables = [
	$wpdb->prefix . 'fotogenic_ai_store_queue_batches',
	$wpdb->prefix . 'fotogenic_ai_store_queue_items',
	$wpdb->prefix . 'fotogenic_ai_store_queues',
    $wpdb->prefix . 'fotogenic_ai_bulk_runs',
    $wpdb->prefix . 'fotogenic_ai_bulk_run_items',
    $wpdb->prefix . 'fotogenic_ai_logs',
    $wpdb->prefix . 'fotogenic_ai_runs',
    $wpdb->prefix . 'fotogenic_ai_presets',
];

foreach ( $fotogenic_ai_tables as $fotogenic_ai_table ) {
    $fotogenic_ai_safe_table = preg_replace( '/[^A-Za-z0-9_]/', '', (string) $fotogenic_ai_table );
    if ( '' === $fotogenic_ai_safe_table ) {
        continue;
    }
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table names come from a fixed plugin-owned allowlist.
    $wpdb->query( "DROP TABLE IF EXISTS {$fotogenic_ai_safe_table}" );
}
