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

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

use Blazemedia\Blackhole\Tools\DotEnv;
use Blazemedia\Blackhole\Tools\SimpleDB;
use Blazemedia\Blackhole\Tools\RunLogger;
use Blazemedia\Blackhole\OfferListProvider;

class Offer_Scan_Command {

    public function __invoke( $args, $assoc_args ) {

        // Carica il file .env
        (new DotEnv( __DIR__ . '/../../../../../.env' ))->load();
   
        $prefix   = getenv('DB_PREFIX') ?? "wp_";
        $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);
     
        WP_CLI::log( "Scanning website offer posts..." );
        $provider = new OfferListProvider( $db );

        try {
            $provider->scan();
        } catch ( \Throwable $error ) {
            RunLogger::add(
                'offers-scan',
                $provider->getScannedPostsCount(),
                0,
                'Errore: ' . $error->getMessage()
            );
            WP_CLI::error( 'offers-scan interrotto: ' . $error->getMessage() );
        }

        RunLogger::add(
            'offers-scan',
            $provider->getScannedPostsCount(),
            0,
            sprintf( 'Trovati %d articoli da lavorare.', $provider->getQueuedPostsCount() )
        );

        WP_CLI::success( "Scan completed!" );
    }
}

// Registra il comando WP-CLI
WP_CLI::add_command( 'offers-scan', 'Offer_Scan_Command' );