<?php

if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

/*----------------------------------------
IM Mail Formのデータを削除
----------------------------------------*/
function immf_uninstall_site_data() {

    $delete_data = (bool) get_option(
        'immf_delete_data_on_uninstall',
        false
    );

    if (!$delete_data) {
        return;
    }

    $form_ids = get_posts([
        'post_type'      => 'im_mail_form',
        'post_status'    => 'any',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'no_found_rows'  => true,
    ]);

    foreach ($form_ids as $form_id) {
        wp_delete_post(
            $form_id,
            true
        );
    }

    delete_option(
        'immf_templates'
    );

    global $wpdb;

    // A direct uncached query is required to find all locale-specific options.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
    $template_option_names = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT option_name
            FROM {$wpdb->options}
            WHERE option_name LIKE %s",
            $wpdb->esc_like(
                'immf_templates_'
            ) . '%'
        )
    );

    foreach ($template_option_names as $option_name) {
        delete_option($option_name);
    }

    delete_option(
        'immf_templates_locale_migrated'
    );

    // メール送信履歴テーブルを削除
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Removing plugin-created tables during uninstall is intentional.
    $wpdb->query(
        $wpdb->prepare(
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange -- Removing plugin-created tables during uninstall is intentional.
            'DROP TABLE IF EXISTS %i',
            $wpdb->prefix . 'im_mail_form_logs'
        )
    );

    delete_option(
        'immf_db_version'
    );

    wp_clear_scheduled_hook(
        'immf_cleanup_mail_logs'
    );

    delete_option(
        'immf_delete_data_on_uninstall'
    );
}

/*----------------------------------------
サイトごとにデータを削除
----------------------------------------*/
if (is_multisite()) {

    $immf_site_ids = get_sites([
        'fields' => 'ids',
        'number' => 0,
    ]);

    foreach ($immf_site_ids as $immf_site_id) {

        switch_to_blog($immf_site_id);

        immf_uninstall_site_data();

        restore_current_blog();
    }

} else {

    immf_uninstall_site_data();
}