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

use NewsletterBridge\Config\NewsletterConfig;
use NewsletterBridge\Services\External\Sender;
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();
        
        // Processa il titolo newsletter
        if (isset($data['newsletter_title'])) {
            $config->newsletter_title = sanitize_text_field($data['newsletter_title']);
        }
        
        // 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) {
                    $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' => array_map('sanitize_text_field', (array)($feed['query_params']['include_taxonomies'] ?? [])),
                            'exclude_taxonomies' => array_map('sanitize_text_field', (array)($feed['query_params']['exclude_taxonomies'] ?? [])),
                            'post_types' => array_map('sanitize_text_field', (array)($feed['query_params']['post_types'] ?? []))
                        ]
                    ];
                }
            }
        }
        
        // 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'] = array_map('sanitize_text_field', $data['feed_query_include_taxonomies_' . $index]);
                    }
                    
                    // Tassonomie da escludere
                    if (isset($data['feed_query_exclude_taxonomies_' . $index])) {
                        $feed['query_params']['exclude_taxonomies'] = array_map('sanitize_text_field', $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]);
                    }
                    
                    $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),
            $config->newsletter_title ?? null
        );
        
        return true;
    }
}

