<?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
        $rollback      = $args[0] ?? null;
        $prefix   = getenv('DB_PREFIX') ?? "_wp";
        $limit    = 0;

        // 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' );