<?php

namespace NewsletterBridge\Admin\Tabs\Newsletter;

use NewsletterBridge\Config\NewsletterConfig;
use NewsletterBridge\Services\External\Sender;
use NewsletterBridge\Utils\FeedQueryLogger;
use NewsletterBridge\Utils\Log;
use NewsletterBridge\Utils\ErrorNotification;

/**
 * Gestione dei comandi lanciati dal tab Newsletter via interfaccia admin.
 */
class NewsletterCommands
{
    /**
     * Esegue il comando richiesto dal form.
     */
    public static function executeCommand(string $action): bool
    {
        return match ($action) {
            'generate_xml' => self::handleGenerateXml(),
            'send_newsletter' => self::handleSendNewsletter(),
            default => self::notify('Comando newsletter non riconosciuto', 'error'),
        };
    }

    /**
     * Genera i file XML senza inviare la newsletter.
     */
    private static function handleGenerateXml(): bool
    {
        try {
            $config = NewsletterConfig::getConfig();
            $sender = new Sender($config, true);
            $query_log = FeedQueryLogger::formatForOutput($sender->getFeedGenerator()->getQueryLog());

            self::notify('File XML generati con successo.', 'success');
            self::notifyQueryLog($query_log);
            return true;
        } catch (\Throwable $e) {
            $errorMessage = '[NewsletterBridge] Errore generazione XML: ' . $e->getMessage();
            Log::error($errorMessage);
            ErrorNotification::send('XML Generation Error', $errorMessage, $e);
            self::notify('Errore durante la generazione dei file XML: ' . $e->getMessage(), 'error');
            return false;
        }
    }

    /**
     * Genera gli XML e invia la newsletter completa.
     */
    private static function handleSendNewsletter(): bool
    {
        try {
            $config = NewsletterConfig::getConfig();
            new Sender($config, false);

            self::notify('Newsletter generata e inviata correttamente.', 'success');
            return true;
        } catch (\Throwable $e) {
            $errorMessage = '[NewsletterBridge] Errore invio newsletter: ' . $e->getMessage();
            Log::error($errorMessage);
            ErrorNotification::send('Newsletter Send Error', $errorMessage, $e);
            self::notify('Errore durante l\'invio della newsletter: ' . $e->getMessage(), 'error');
            return false;
        }
    }

    /**
     * Mostra un messaggio nella UI di WordPress.
     */
    private static function notify(string $message, string $type): bool
    {
        $class = $type === 'error' ? 'notice notice-error' : 'notice notice-success';

        add_action('admin_notices', function () use ($message, $class) {
            printf(
                '<div class="%s is-dismissible"><p>%s</p></div>',
                esc_attr($class),
                esc_html($message)
            );
        });

        return $type !== 'error';
    }

    private static function notifyQueryLog(string $log): void {
        if ($log === '') {
            return;
        }

        add_action('admin_notices', function () use ($log) {
            echo '<div class="notice notice-info" style="max-width:100%;">';
            echo '<p><strong>Query feed eseguite (debug)</strong></p>';
            echo '<pre style="max-height:420px;overflow:auto;background:#f6f7f7;padding:12px;font-size:12px;line-height:1.4;">';
            echo esc_html($log);
            echo '</pre></div>';
        });
    }
}
