<?php

namespace NewsletterBridge\Services\Feed;

use NewsletterBridge\Services\Query\QueryBuilder;
use NewsletterBridge\Services\Query\PostExclusionManager;
use NewsletterBridge\Services\Content\PostTemplateProcessor;
use NewsletterBridge\Services\Feed\RSSFormatter;

/**
 * Responsabilità: Generazione feed newsletter
 * Single Responsibility: Orchestrazione generazione feed
 */
class FeedGenerator {
    
    private QueryBuilder $queryBuilder;
    private PostExclusionManager $exclusionManager;
    private PostTemplateProcessor $templateProcessor;
    private RSSFormatter $rssFormatter;
    private XMLFileManager $xmlFileManager;
    
    public function __construct(
        QueryBuilder $queryBuilder,
        PostExclusionManager $exclusionManager,
        PostTemplateProcessor $templateProcessor,
        RSSFormatter $rssFormatter,
        XMLFileManager $xmlFileManager
    ) {
        $this->queryBuilder = $queryBuilder;
        $this->exclusionManager = $exclusionManager;
        $this->templateProcessor = $templateProcessor;
        $this->rssFormatter = $rssFormatter;
        $this->xmlFileManager = $xmlFileManager;
    }
    
    /**
     * Genera tutti i feed in una singola chiamata
     */
    public function generateAllFeeds(\stdClass $config, bool $preview = false, int $site_id = null): array {
        $feeds = [];
        
        // Genera i feed di sistema
        $feeds['subject'] = $this->generateSingleFeed('subject', $config, $preview);
        
        // Genera i feed configurati
        foreach ($config->feeds as $feed) {
            $feed_name = $feed->name ?? 'unknown';
            $feeds[$feed_name] = $this->generateSingleFeed($feed_name, $config, $preview);
        }
        
        // Se non è preview, salva i file XML
        if (!$preview) {
            $this->xmlFileManager->generateFiles($feeds, $config->feeds, $site_id);
        }
        
        return $feeds;
    }
    
    /**
     * Genera un singolo feed
     */
    public function generateSingleFeed(string $feed_name, \stdClass $config, bool $preview = false): string {
        // Gestione speciale per il feed subject
        if ($feed_name === 'subject') {
            return $this->generateSubjectFeed($config);
        }
        
        $used_posts = $this->exclusionManager->getUsedPosts();
        $feed_config = $this->getFeedConfig($feed_name, $config);
        
        if (!$feed_config) {
            return $this->rssFormatter->formatRSS([]);
        }
        
        // Costruisce la query
        $query_args = $this->queryBuilder->buildQuery($feed_name, $feed_config, $used_posts);
        
        // Esegue la query
        $posts = get_posts($query_args);
        
        // Processa i post in template
        $template_posts = $this->templateProcessor->processPosts($posts);
        
        // Marca i post come utilizzati
        foreach ($template_posts as $post) {
            $this->exclusionManager->markPostAsUsed($post->id);
        }
        
        // Salva i post utilizzati
        $this->exclusionManager->saveUsedPosts();
        
        // Genera il feed RSS
        return $this->rssFormatter->formatRSS($template_posts);
    }
    
    /**
     * Genera il feed subject usando il titolo newsletter
     */
    private function generateSubjectFeed(\stdClass $config): string {
        $title = $config->newsletter_title ?? 'Newsletter {{date}}';
        
        // Sostituisce il placeholder {{date}} con la data italiana
        $title = $this->replaceDatePlaceholder($title);
        
        // Crea un post virtuale per il subject
        $virtual_post = (object) [
            'id' => 'subject_' . time(),
            'title' => $title,
            'content' => '',
            'excerpt' => '',
            'date' => date('Y-m-d H:i:s'),
            'author' => 'Newsletter System',
            'url' => get_home_url(),
            'image' => ''
        ];
        
        return $this->rssFormatter->formatRSS([$virtual_post]);
    }
    
    /**
     * Sostituisce il placeholder {{date}} con la data italiana
     */
    private function replaceDatePlaceholder(string $text): string {
        $months = [
            1 => 'gennaio', 2 => 'febbraio', 3 => 'marzo', 4 => 'aprile',
            5 => 'maggio', 6 => 'giugno', 7 => 'luglio', 8 => 'agosto',
            9 => 'settembre', 10 => 'ottobre', 11 => 'novembre', 12 => 'dicembre'
        ];
        
        $day = date('j');
        $month = $months[(int)date('n')];
        $year = date('Y');
        
        $italian_date = "$day $month $year";
        
        return str_replace('{{date}}', $italian_date, $text);
    }
    
    /**
     * Ottiene la configurazione di un feed
     */
    private function getFeedConfig(string $feed_name, \stdClass $config): ?array {
        if ($feed_name === 'summary') {
            return null; // Feed summary eliminato
        }
        
        foreach ($config->feeds as $feed) {
            if ($feed->name === $feed_name) {
                return (array)$feed;
            }
        }
        
        return null;
    }
    
    /**
     * Resetta i post utilizzati
     */
    public function resetUsedPosts(): void {
        $this->exclusionManager->resetUsedPosts();
    }
}
