<?php
/**
 * Removing the plugin's data, when that was asked for.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wp;

/**
 * Records are legal evidence, so they survive by default. Deleting them is an
 * explicit choice in the settings, never a side effect of removing the plugin.
 *
 * This runs off the SDK's after_uninstall action rather than the uninstall.php
 * file WordPress looks for. The two cannot coexist: WordPress runs uninstall.php
 * instead of the uninstall hook when the file is present, which would leave
 * Freemius unable to close its own side of the install.
 */
final class Uninstall
{
    public static function run(): void
    {
        $settings = get_option(Settings::OPTION, []);

        if (!is_array($settings) || empty($settings['delete_on_uninstall'])) {
            return;
        }

        $records = get_posts(
            [
                'post_type'   => PostType::NAME,
                'post_status' => 'any',
                'numberposts' => -1,
                'fields'      => 'ids',
            ]
        );

        foreach ($records as $recordId) {
            wp_delete_post((int) $recordId, true);
        }

        delete_option(Settings::OPTION);
    }
}
