<?php
/**
 * Livada SEO — Uninstall
 *
 * Fires when the plugin is deleted from the WordPress admin.
 * Removes all plugin data: options, post meta, the redirects table,
 * transients, and scheduled hooks.
 *
 * @package Livada_SEO
 */

// WordPress sets this constant before calling uninstall.php.
// Abort immediately if called directly.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

global $wpdb;

// ── 1. Options ────────────────────────────────────────────────────────────────

delete_option( 'livada_seo_settings' );
delete_option( 'livada_seo_locations' );
delete_option( 'livada_seo_404_log' );
delete_option( 'livada_seo_404_table_version' );
delete_option( 'livada_seo_sitemap_rewrites_version' );
delete_option( 'livada_seo_activity_log_version' );
delete_option( 'livada_seo_onboarding_done' );
delete_option( 'livada_seo_gsc_global_keywords' );

// ── 2. Post meta ──────────────────────────────────────────────────────────────

// No WP API supports bulk-deleting by key prefix, so direct SQL is required.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query(
	"DELETE FROM {$wpdb->postmeta}
	 WHERE meta_key LIKE '_livada_seo_%'"
);

// ── 3. Custom tables ──────────────────────────────────────────────────────────

$tables = [
	$wpdb->prefix . 'livada_seo_redirects',
	$wpdb->prefix . 'livada_seo_404_log',
	$wpdb->prefix . 'livada_seo_activity_log',
];

foreach ( $tables as $table_name ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );
}

// ── 4. Transients ─────────────────────────────────────────────────────────────

// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query(
	"DELETE FROM {$wpdb->options}
	 WHERE option_name LIKE '_transient_livada_seo_%'
	    OR option_name LIKE '_transient_timeout_livada_seo_%'"
);

// Object cache: flush any in-memory transient values so they don't linger if
// an object cache (Redis/Memcached) is active.
wp_cache_flush();

// ── 5. Scheduled hooks ────────────────────────────────────────────────────────

wp_clear_scheduled_hook( 'livada_seo_cron_sitemap' );
wp_clear_scheduled_hook( 'livada_seo_cron_indexnow' );
wp_clear_scheduled_hook( 'livada_seo_cron_audit' );
wp_clear_scheduled_hook( 'livada_seo_indexnow_ping' );
