<?php
/**
 * Uninstall
 *
 * Runs when ChamaWP is deleted if the "Delete plugin data" option is checked in
 */
// Exit if accessed directly or not called by WordPress uninstall process.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

// Do nothing if option to leave data unchanged is checked.
$delete_data = $require_membership = get_option('chama_delete_plugin_data');
if (!$delete_data) {
    return;
}
try {
    global $wpdb;
// Delete pages.
    $chama_pages = array(
        'hub' => get_option('chama_hub_page'),
        'donate' => get_option('chama_donate_page'),
        'membership' => get_option('chama_membership_page'),
        'crowdfunding' => get_option('chama_crowdfunding_page'),
        'commissions' => get_option('chama_commissions_page'),
        'login' => get_option('chama_login_page'),
        'registration' => get_option('chama_registration_page'),
        'edit_account' => get_option('chama_edit_account_page'),
        'edit_password' => get_option('chama_edit_password_page'),
        'forgot_password' => get_option('chama_forgot_password_page'),
        'reset_password' => get_option('chama_reset_password_page'),
        'verify_email' => get_option('chama_verify_email_page'),
        'account' => get_option('chama_account_page'),
        'payment' => get_option('chama_payment_page'),
        'payment_confirmation' => get_option('chama_payment_confirmation_page'),
        'subscription' => get_option('chama_subscription_page'),
        'subscription_confirmation' => get_option('chama_subscription_confirmation_page'),
        'newsletter_sign_up_confirmation' => get_option('chama_newsletter_sign_up_confirmation_page'),
        'newsletter_opt_out_confirmation' => get_option('chama_newsletter_opt_out_confirmation_page'),
    );
    foreach ($chama_pages as $key => $chama_page) {
        if ($chama_page) {
            wp_delete_post($chama_page, true);

        }
    }

    // Delete options.
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'chama%'");// check

    // Delete all plugin posts and related meta data.
    $wpdb->query("DELETE FROM {$wpdb->posts} WHERE post_type IN ('chama_tier','chama_campaign','chama_commission','chama_donation','chama_subscription','chama_fund','chama_com_order');");// check
    $wpdb->query("DELETE meta FROM {$wpdb->postmeta} meta LEFT JOIN {$wpdb->posts} posts ON posts.ID = meta.post_id WHERE posts.ID IS NULL;");// check
    $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = 'chama_tier_level';");// check

    // Delete usermeta.
    $wpdb->query("DELETE FROM $wpdb->usermeta WHERE meta_key LIKE 'chama_%'");// check

    // Clear any cached data that has been removed.
    wp_cache_flush();

} catch (Exception $e) {
   
    die(esc_html($e->getMessage()));
}
