<?php
namespace NewsletterBridge\Admin\Tabs\Newsletter;

use NewsletterBridge\Config\NewsletterConfig;
use NewsletterBridge\Services\External\Sender;
use NewsletterBridge\Services\Query\TaxonomyTermReference;
use NewsletterBridge\Utils\ServiceContainer;

/**
 * Processamento dati e comandi per NewsletterTab
 * Responsabilità: Processamento dati, salvataggio e esecuzione comandi
 */
class NewsletterProcessor {
    
    public static function processData($data) {
        // Verifica nonce
        if (!isset($data['newsletter_admin_nonce']) || !wp_verify_nonce($data['newsletter_admin_nonce'], 'newsletter_admin_nonce')) {
            wp_die('Nonce verification failed');
        }
        
        $config = NewsletterConfig::getConfig();

        $title_from_featured = !empty($data['newsletter_title_from_featured']);

        if (!$title_from_featured && isset($data['newsletter_title'])) {
            $config->newsletter_title = sanitize_text_field($data['newsletter_title']);
        }

        $title_to_persist = null;
        if (!$title_from_featured) {
            $title_to_persist = isset($data['newsletter_title'])
                ? sanitize_text_field($data['newsletter_title'])
                : ($config->newsletter_title ?? null);
        }
        
        // Debug: log dei dati ricevuti
        error_log('NewsletterProcessor - Dati ricevuti: ' . print_r($data, true));
        
        // Processa i feed: preferisci JSON compilato dal frontend se presente
        $feeds = [];
        if (!empty($data['newsletter_feeds_compiled'])) {
            $compiled = json_decode(stripslashes($data['newsletter_feeds_compiled']), true);
            if (is_array($compiled)) {
                foreach ($compiled as $feed) {
                    $in_evidenza = sanitize_text_field($feed['query_params']['in_evidenza_filter'] ?? 'prioritize');
                    if (!in_array($in_evidenza, ['prioritize', 'only', 'exclude'], true)) {
                        $in_evidenza = 'prioritize';
                    }
                    $post_types = array_values(array_filter(
                        array_map('sanitize_text_field', (array) ($feed['query_params']['post_types'] ?? []))
                    ));
                    $feeds[] = [
                        'name' => sanitize_text_field($feed['name'] ?? ''),
                        'file' => sanitize_text_field($feed['file'] ?? ''),
                        'query_params' => [
                            'posts_per_page' => intval($feed['query_params']['posts_per_page'] ?? 10),
                            'include_taxonomies' => self::sanitizeTaxonomyRefs((array)($feed['query_params']['include_taxonomies'] ?? [])),
                            'exclude_taxonomies' => self::sanitizeTaxonomyRefs((array)($feed['query_params']['exclude_taxonomies'] ?? [])),
                            'post_types' => $post_types,
                            'in_evidenza_filter' => $in_evidenza,
                        ]
                    ];
                }
            }
        }
        
        // Fallback al parsing legacy se il JSON compilato non è disponibile
        if (empty($feeds)) {
            foreach ($data as $key => $value) {
                if (preg_match('/^feed_name_(\d+)$/', $key, $matches)) {
                    $index = $matches[1];
                    $feed = [
                        'name' => sanitize_text_field($value),
                        'file' => sanitize_text_field($data['feed_file_' . $index] ?? '')
                    ];
                    
                    // Aggiungi parametri query con valori di default
                    $feed['query_params'] = [
                        'posts_per_page' => intval($data['feed_query_posts_' . $index] ?? 10)
                    ];
                    
                    // Tassonomie da includere
                    if (isset($data['feed_query_include_taxonomies_' . $index])) {
                        $feed['query_params']['include_taxonomies'] = self::sanitizeTaxonomyRefs(
                            (array) $data['feed_query_include_taxonomies_' . $index]
                        );
                    }
                    
                    if (isset($data['feed_query_exclude_taxonomies_' . $index])) {
                        $feed['query_params']['exclude_taxonomies'] = self::sanitizeTaxonomyRefs(
                            (array) $data['feed_query_exclude_taxonomies_' . $index]
                        );
                    }
                    
                    // Post types
                    if (isset($data['feed_query_post_types_' . $index])) {
                        $feed['query_params']['post_types'] = array_map('sanitize_text_field', $data['feed_query_post_types_' . $index]);
                    }

                    $in_evidenza = sanitize_text_field($data['feed_query_in_evidenza_' . $index] ?? 'prioritize');
                    if (in_array($in_evidenza, ['prioritize', 'only', 'exclude'], true)) {
                        $feed['query_params']['in_evidenza_filter'] = $in_evidenza;
                    } else {
                        $feed['query_params']['in_evidenza_filter'] = 'prioritize';
                    }
                    
                    $feeds[] = $feed;
                }
            }
        }
        
        // Processa le date dai campi dinamici
        $dates = [];
        foreach ($data as $key => $value) {
            if (preg_match('/^date_date_(\d+)$/', $key, $matches)) {
                $index = $matches[1];
                $date = [
                    'date' => sanitize_text_field($value),
                    'description' => sanitize_text_field($data['date_description_' . $index] ?? '')
                ];
                $dates[] = $date;
            }
        }
        
        // Filtra feed vuoti (nome e file entrambi vuoti oppure file mancante)
        $feeds = array_values(array_filter($feeds, function($f) {
            $name = is_array($f) ? ($f['name'] ?? '') : ($f->name ?? '');
            $file = is_array($f) ? ($f['file'] ?? '') : ($f->file ?? '');
            return !empty($file) || !empty($name);
        }));

        // Salva la configurazione
        NewsletterConfig::saveConfig(
            $config->domain,
            json_encode($feeds),
            json_encode($dates),
            $title_to_persist,
            $title_from_featured
        );
        
        return true;
    }

    /**
     * @param string[] $refs
     * @return string[]
     */
    private static function sanitizeTaxonomyRefs(array $refs): array {
        $clean = array_map(static function ($ref) {
            return sanitize_text_field((string) $ref);
        }, $refs);

        return TaxonomyTermReference::normalizeList($clean);
    }
}

