<?php
/**
 * Uninstall — Full cleanup with validation.
 *
 * @package EPWF
 */

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

if ( ! current_user_can( 'activate_plugins' ) ) {
    exit;
}

if ( plugin_basename( __FILE__ ) !== 'exertpro-faq-ai/uninstall.php' ) {
    exit;
}

global $wpdb;

// Remove plugin options
delete_option( 'epwf_settings' );
delete_option( 'epwf_db_version' );

// Remove all product meta added by this plugin
$epwf_meta_keys = [
    '_epwf_generated_faqs',
    '_epwf_manual_override',
    '_epwf_enabled',
    '_epwf_content_hash',
    '_epwf_last_error',
];

foreach ( $epwf_meta_keys as $epwf_key ) {
    /*
     * Uninstall context: direct DB calls are required here.
     * No WP API alternative exists for bulk meta deletion by key.
     * Caching is intentionally skipped — object cache is flushed below.
     *
     * phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
     * phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
     * phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key
     */
    $wpdb->delete(
        $wpdb->postmeta,
        [ 'meta_key' => $epwf_key ],
        [ '%s' ]
    );
    // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:enable WordPress.DB.DirectDatabaseQuery.NoCaching
    // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key
}

// Remove rate-limit user meta (pattern: _epwf_rate_XXXXXXXXXX)
// Direct query required — no WP API for LIKE-based meta deletion.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
        $wpdb->esc_like( '_epwf_rate_' ) . '%'
    )
);

// Clear object cache
wp_cache_flush();
