<?php

/**
 * Uninstall routines.
 *
 * This file is called automatically when the plugin is deleted per user interface.
 *
 * @see https://developer.wordpress.org/plugins/the-basics/uninstall-methods/
 */

declare(strict_types=1);

namespace Inpsyde\MultilingualPress;

use Inpsyde\MultilingualPress\Core\Admin\Settings\Cache\CacheSettingsRepository;
use Inpsyde\MultilingualPress\Framework\Database\TableList;
use Inpsyde\MultilingualPress\Installation\Uninstaller;
use Inpsyde\MultilingualPress\Onboarding\Onboarding;
use Inpsyde\MultilingualPress\Onboarding\State;

defined('ABSPATH') || die();

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

if (!current_user_can('activate_plugins')) {
    return;
}

if (!is_multisite()) {
    return;
}

$mainPluginFile = __DIR__ . '/multilingualpress.php';

if (
    plugin_basename($mainPluginFile) !== WP_UNINSTALL_PLUGIN
    || !is_readable($mainPluginFile)
) {
    unset($mainPluginFile);

    return;
}

/** @noinspection PhpIncludeInspection */
require_once $mainPluginFile;

unset($mainPluginFile);

if (!bootstrap()) {
    return;
}

$uninstaller = resolve(Uninstaller::class);
$tableList = resolve(TableList::class);

$uninstaller->uninstallTables($tableList->mlpTableNames());

$uninstaller->deleteNetworkOptions(
    [
        Activation\Activator::OPTION,
        Core\Admin\SiteSettingsRepository::OPTION,
        Core\PostTypeRepository::OPTION,
        Core\TaxonomyRepository::OPTION,
        Framework\Module\ModuleManager::OPTION,
        MultilingualPress::OPTION_VERSION,
        CacheSettingsRepository::OPTION_NAME,
    ]
);

$uninstaller->deleteSiteOptions(
    [
        Module\Redirect\Settings\Repository\Repository::OPTION_SITE,
        Module\Redirect\Settings\Repository\Repository::MODULE_SETTINGS,
    ]
);

$uninstaller->deletePostMeta(
    [
        Module\Trasher\TrasherSettingRepository::META_KEY,
        NavMenu\ItemRepository::META_KEY_SITE_ID,
        Module\ExternalSites\ExternalSitesMetaBox\ExternalSitesMetaBoxView::META_NAME,
        Module\ExternalSites\NavMenu\ExternalSiteMenuItemFactory::META_KEY_EXTERNAL_SITE_ID,
    ]
);

$uninstaller->deleteUserMeta(
    [
        Module\Redirect\Settings\Repository\Repository::META_KEY_USER,
    ]
);

$uninstaller->deleteOnboardingData(
    [
        Onboarding::OPTION_ONBOARDING_DISMISSED,
        State::OPTION_NAME,
    ],
    [
        Core\Admin\Pointers\Pointers::USER_META_KEY,
    ]
);

$uninstaller->deleteScheduledEvents(
    [
        SiteDuplication\Schedule\AttachmentDuplicatorScheduler::SCHEDULE_HOOK,
        Schedule\Scheduler::ACTION_CLEANUP,
    ]
);

unset($uninstaller);
