<?php
/**
 * Playard Uninstall
 *
 * Runs when the plugin is deleted from the WordPress admin.
 * Drops all playard_ tables and removes all plugin options.
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter

global $wpdb;

// Drop tables in FK-safe order (dependents first).
$tables = [
	$wpdb->prefix . 'playard_otp',
	$wpdb->prefix . 'playard_payments',
	$wpdb->prefix . 'playard_bookings',
	$wpdb->prefix . 'playard_blocked_slots',
	$wpdb->prefix . 'playard_customers',
	$wpdb->prefix . 'playard_fields',
	$wpdb->prefix . 'playard_facilities',
];

foreach ( $tables as $table ) {
	// Table names are built from the trusted $wpdb->prefix — not user input.
	// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
}

// Remove all plugin options.
$options = [
	'playard_version',
	'playard_db_version',
	'playard_settings',
	'playard_onboarding_complete',
	'playard_facility_id',
	'playard_booking_counter',
	'playard_stripe_webhook_secret',
];

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

// Remove any transients.
$wpdb->query(
	$wpdb->prepare(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
		$wpdb->esc_like( '_transient_playard_' ) . '%',
		$wpdb->esc_like( '_transient_timeout_playard_' ) . '%'
	)
);

// Clear scheduled events.
wp_clear_scheduled_hook( 'playard_cleanup_stale_bookings' );
wp_clear_scheduled_hook( 'playard_cleanup_slot_locks' ); // legacy — safe to clear even if not registered
