<?php
/**
 * Answyr — uninstall cleanup.
 *
 * Freemius ships its own top-level `uninstall.php`, so our teardown lives here
 * and is registered on the Freemius `after_uninstall` hook (see
 * inc/core/freemius.php). Removes plugin-owned data: the custom ticket/message
 * tables, every `answyr_*` option (including the encrypted per-provider API
 * keys), and the rate-limiter transients.
 *
 * Deliberately left intact: the `answyr_kb` knowledge-base CPT posts.
 * Those are the site owner's authored content, not ours to delete on uninstall.
 *
 * @package Answyr
 */

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

if ( ! function_exists( 'answyr_uninstall_site' ) ) {

	/**
	 * Remove all plugin data for the current site.
	 */
	function answyr_uninstall_site() {
		global $wpdb;

		// Custom tables (plugin-owned ticket/message store).
		$tables = array(
			$wpdb->prefix . 'answyr_desk_tickets',
			$wpdb->prefix . 'answyr_desk_messages',
		);
		foreach ( $tables as $table ) {
			// A table name can't be a prepared placeholder; it's built from a trusted
			// prefix, and this only runs on explicit uninstall.
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
		}

		// Every answyr_* option (seeded settings + dynamic api_key_* keys).
		$options_like = $wpdb->esc_like( 'answyr_' ) . '%';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $options_like ) );

		// Rate-limiter transients (answyr_rl_*) — short-lived, but tidy them up.
		$transient_like = $wpdb->esc_like( '_transient_answyr_rl_' ) . '%';
		$timeout_like   = $wpdb->esc_like( '_transient_timeout_answyr_rl_' ) . '%';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $transient_like, $timeout_like ) );
	}

	/**
	 * Dispatch cleanup across the network (multisite) or the single site.
	 *
	 * Registered on the Freemius `after_uninstall` hook.
	 */
	function answyr_uninstall() {
		if ( is_multisite() ) {
			$site_ids = get_sites(
				array(
					'fields' => 'ids',
					'number' => 0,
				)
			);
			foreach ( $site_ids as $site_id ) {
				switch_to_blog( (int) $site_id );
				answyr_uninstall_site();
				restore_current_blog();
			}
		} else {
			answyr_uninstall_site();
		}
	}
}
