<?php
/**
 * TitanCart Uninstall.
 *
 * Runs when the plugin is deleted from the WP admin (not just deactivated).
 * Only removes data if the user has explicitly opted in via settings.
 *
 * @package TitanCart
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

// Safety check — only remove data if user opted in.
$remove_data = get_option( 'titancart_remove_data_on_uninstall', false );

if ( ! $remove_data ) {
    return;
}

// Drop all tc_ tables.
global $wpdb;
$prefix = $wpdb->prefix . 'tc_';

$tables = $wpdb->get_col(
    $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $prefix ) . '%' )
);

foreach ( $tables as $table ) {
    $wpdb->query( "DROP TABLE IF EXISTS `{$table}`" ); // phpcs:ignore
}

// Remove plugin options.
$options = [
    'titancart_version',
    'titancart_db_version',
    'titancart_remove_data_on_uninstall',
];

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

// Clear scheduled cron events.
wp_clear_scheduled_hook( 'titancart_process_jobs' );
wp_clear_scheduled_hook( 'titancart_daily_snapshot' );
