<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * @package    100Prints
 */

// If uninstall not called from WordPress, exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

global $wpdb;

// Drop generation history table.
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}100p_generation_history" );

// Drop legacy generation log table.
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}100p_generation_log" );

// Drop legacy forms/submissions tables (if they exist from older versions).
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}100p_submission_values" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}100p_submissions" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}100p_form_fields" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}100p_forms" );

// Delete plugin options.
delete_option( '100p_settings' );
delete_option( '100prints_api_key' );
delete_option( '100p_template_index' );
delete_option( '100p_last_sync_error' );

// Delete template caches from options.
$options_to_delete = $wpdb->get_col(
	$wpdb->prepare(
		"SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s",
		$wpdb->esc_like( '100p_template_cache_' ) . '%'
	)
);

if ( ! empty( $options_to_delete ) ) {
	foreach ( $options_to_delete as $option ) {
		delete_option( $option );
	}
}

// Clear transients.
$transients_to_delete = $wpdb->get_col(
	$wpdb->prepare(
		"SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s",
		$wpdb->esc_like( '_transient_100p_template_' ) . '%'
	)
);

if ( ! empty( $transients_to_delete ) ) {
	foreach ( $transients_to_delete as $transient_option ) {
		$transient_name = str_replace( '_transient_', '', $transient_option );
		delete_transient( $transient_name );
	}
}
