<?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 = [
    '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 = [
	'award', 'client', 'testimonial', 'restaurant_menu',
	'team', 'service', 'portfolio', 'event',
	'career', 'doc', 'digital', 'themebuilder', 'section_templates',
];

foreach ( $sifency_cpts as $cpt ) {

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

	if ( ! empty( $posts ) ) {
		foreach ( $posts as $post_id ) {
            // true = force delete (skip trash)
			wp_delete_post( $post_id, true );
		}
	}
}

/**
 * Delete taxonomy terms
 */
$taxonomies = [
	'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( [ 
        'taxonomy'   => $tax, 
        'hide_empty' => false,
        'fields'     => 'ids' // Optimization
    ] );

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

// Clear rewrite rules
flush_rewrite_rules();

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