<?php

/**
 * Fired when the plugin is uninstalled.
 *
 *
 * @link       https:fernan/
 * @since      1.0.0
 *
 * @package    tarokkina_free
 */

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


// DELETE IN DATABASE
$tkna_free_unistall = get_option( '_tkna_free_unistall' );

if ( $tkna_free_unistall == 'yes' && is_admin()) {
	global $wpdb;
	$post_type = 'tarokkina_free';


	// Delete posts and postmetas.
	$wpdb->query(
		$wpdb->prepare("
			DELETE posts,pt,pm
			FROM $wpdb->posts posts
			LEFT JOIN $wpdb->postmeta pm ON pm.post_id = posts.ID
			LEFT JOIN $wpdb->term_relationships pt ON pt.object_id = posts.ID
			WHERE posts.post_type = %s
			",
			$post_type
		)
	);



	// Delete TEXTOS VINCULADOS CON TAROTS
	$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key LIKE '%tkna_free_text%'" );
	$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key LIKE '%_tkna_free_text%'" );



	// Delete terms
	$wpdb->query(
	 $wpdb->prepare("
		DELETE FROM
		{$wpdb->terms}
		WHERE term_id IN
		( SELECT * FROM (
			SELECT {$wpdb->terms}.term_id
			FROM {$wpdb->terms}
			JOIN {$wpdb->term_taxonomy}
			ON {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id
			WHERE taxonomy = %s
		) as T
		);
		",
		'tarokkina_free-cat'
		)
    );


	// Delete term taxonomies.
	$wpdb->query("DELETE FROM $wpdb->term_taxonomy WHERE taxonomy LIKE '{$post_type}-cat' OR taxonomy LIKE '{$post_type}-tag'");


	// Delete Options page.
	$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '%options_{$post_type}%'");
	//delete_option( 'tarokkina_free-cat_children' );
	delete_option( 'tarokina_tarokina_free' );
	delete_option( 'tarokkina_free-cat_children' );

	// Delete Transients
	//$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '%transient_tarokki_free%'" );
	$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '%tkna_free_deck%'" );

	// Delete Options
	$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '%_tarokki_free%'" );
	$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '%tarokki_free%'" );
	delete_option( '_tkna_free_unistall' );
	delete_option( 'tarokki-check-fields');

}



    // Unistall Sin if()
	delete_option( 'tarokki_install_free' );
	delete_option( '_tarokki_checkCartas_free');
	delete_option( 'tarokki_tarotsAll_free');
	delete_option( '_tkna_free_deck');
	delete_option( '_tarokki_cardsids_free');

	wp_cache_flush();