<?php
require_once __DIR__ . '/../vendor/autoload.php';

use Blazemedia\Blackhole\Tools\DotEnv;
use Blazemedia\Blackhole\Tools\SimpleDB;
use Blazemedia\Blackhole\OffersReaper;

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
    return;
}

class Blackhole_Command {

    public function __invoke( $args, $assoc_args ) {
        // Carica il file .env
        (new DotEnv( __DIR__ . '/../../../../../.env' ))->load();

        // Estrae gli argomenti
         // Estrae gli argomenti
         $rollback      = $assoc_args['rollback'] ?? null;
         $prefix        = getenv('DB_PREFIX') ?? "wp_";
         $limit         = 0;
         $blog_id       = $assoc_args['blog_id'] ?? null;

        //se multisite setta il blog
        if (is_multisite() && $blog_id) {
            if (get_blog_details($blog_id)) {
                WP_CLI::log("Switching to blog ID: $blog_id");
                switch_to_blog($blog_id);
            } else {
                WP_CLI::error("The blog with ID $blog_id does not exist.");
            }
        }

        // Inizializza il database
        $db = SimpleDB::getInstance($prefix);

        $offersReaper = new OffersReaper( $db );

        if ( $rollback ) {
            WP_CLI::log( "Resetting all posts to 'publish'" );
            $offersReaper->rollback();
        } else {
            WP_CLI::log( "Setting posts to blackhole" );
            $offersReaper->blackhole( $limit );
        }
    }
}

// Registra il comando WP-CLI
WP_CLI::add_command( 'blackhole', 'Blackhole_Command' );