<?php

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

require_once plugin_dir_path( __FILE__ ) . 'scholar-sync.php';

scholar_sync_drop_tables();
scholar_sync_delete_cron();
scholar_sync_delete_options();
scholar_sync_delete_pages();

function scholar_sync_drop_tables() {
    global $wpdb;
    $tableArray = [
        SCHOLAR_SYNC_DB_ARTICLES,
        SCHOLAR_SYNC_DB_AUTHORS,
        SCHOLAR_SYNC_DB_GROUP_AUTHORS,
        SCHOLAR_SYNC_DB_GROUPS,
        SCHOLAR_SYNC_DB_CO_AUTHORS,
        SCHOLAR_SYNC_DB_SYNC_LOG,
        SCHOLAR_SYNC_DB_SYNC_RUNS,
    ];

    foreach ($tableArray as $name) {
        $wpdb->query( "DROP TABLE IF EXISTS {$name}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- $name is a trusted constant, not user input
    }
}

function scholar_sync_delete_options() {
    $all_options = wp_load_alloptions();
    foreach ($all_options as $option_name => $option_value) {
        if ( strpos($option_name, 'scholar_sync_') === 0 ||
             strpos($option_name, 'scholar-sync-') === 0 ) {
            delete_option($option_name);
        }
    }
}

function scholar_sync_delete_cron() {
    wp_clear_scheduled_hook( 'scholar_sync_background_sync' );
}

function scholar_sync_delete_pages() {
    global $wpdb;
    $name = 'scholar_sync_page_1';
    $page_id = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->prepare('SELECT id FROM ' . $wpdb->prefix . 'posts WHERE post_name = %s', $name)
    );
    if (!empty($page_id)) {
        wp_delete_post($page_id, true);
    }
}
