<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

$uninstall_flag            = get_option( 'sifency_uninstall_flag' );
$options                   = get_option( 'sifency-options' );
$permanent_setting_enabled = ( ! empty( $options['delete_data_on_uninstall'] ) && 'yes' === $options['delete_data_on_uninstall'] );

if ( 'delete_all' !== $uninstall_flag && ! $permanent_setting_enabled ) {
	delete_option( 'sifency_uninstall_flag' );
	return;
}

/**
 * Delete plugin options
 */
$sifency_option_keys = array(
	'sifency-options',
	'sifency-addons-license',
	'sifency-addons-activation-data',
	'sifency-addons-notice-dismissed',
);

foreach ( $sifency_option_keys as $key ) {
	delete_option( $key );
	delete_site_option( $key );
}

/**
 * Delete CPT posts
 */
$sifency_cpts = array(
	'award',
	'client',
	'testimonial',
	'restaurant_menu',
	'stack',
	'team',
	'service',
	'portfolio',
	'event',
	'career',
	'doc',
	'digital',
	'themebuilder',
	'section_templates',
);

foreach ( $sifency_cpts as $cpt ) {

	$posts = get_posts(
		array(
			'post_type'   => $cpt,
			'post_status' => 'any',
			'numberposts' => -1,
			'fields'      => 'ids',
		)
	);

	if ( ! empty( $posts ) ) {
		foreach ( $posts as $post_id ) {
			wp_delete_post( $post_id, true );
		}
	}
}

/**
 * Delete taxonomy terms
 */
$taxonomies = array(
	'award_category',
	'client_category',
	'testimonial_category',
	'restaurant_menu_category',
	'team_category',
	'service_category',
	'portfolio_category',
	'event_category',
	'career_category',
	'digital_category',
	'doc_category',
	'themebuilder_category',
	'section_templates_category',
);

foreach ( $taxonomies as $tax ) {
	$terms = get_terms(
		array(
			'taxonomy'   => $tax,
			'hide_empty' => false,
			'fields'     => 'ids',
		)
	);

	if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
		foreach ( $terms as $term_id ) {
			wp_delete_term( $term_id, $tax );
		}
	}
}

flush_rewrite_rules();

delete_option( 'sifency_uninstall_flag' );
delete_option( 'sifency-options' );
