<?php

namespace NewsletterBridge\Services\Newsletter;

use NewsletterBridge\Config\NewsletterConfig;
use NewsletterBridge\Config\Queries;

/**
 * Endpoint WordPress per i feed della newsletter
 * Gestisce l'URL /newsletter-feed/ con logica WordPress
 */
class NewsletterFeedEndpoint {

    public function __construct() {
        add_action('init', [$this, 'add_rewrite_rules']);
        add_action('template_redirect', [$this, 'handle_feed_request']);
        add_filter('query_vars', [$this, 'add_query_vars']);
    }

    /**
     * Aggiunge le regole di rewrite per l'endpoint
     */
    public function add_rewrite_rules() {
        add_rewrite_rule(
            '^newsletter-feed/?$',
            'index.php?newsletter_feed=1',
            'top'
        );
    }

    /**
     * Aggiunge le variabili query personalizzate
     */
    public function add_query_vars($vars) {
        $vars[] = 'newsletter_feed';
        $vars[] = 'nlcontent';
        $vars[] = 'tag';
        $vars[] = 'preview';
        return $vars;
    }

    /**
     * Gestisce le richieste ai feed
     */
    public function handle_feed_request() {
        if (get_query_var('newsletter_feed')) {
            $this->process_feed_request();
            exit;
        }
    }

    /**
     * Processa la richiesta del feed
     */
    private function process_feed_request() {
        // Parametri GET
        $nlcontent = get_query_var('nlcontent') ?: $_GET['nlcontent'] ?? '';
        $tag = get_query_var('tag') ?: $_GET['tag'] ?? '';
        $preview = get_query_var('preview') ?: $_GET['preview'] ?? false;

        // Valori di default
        $feed_length = 20;

        // Validazione parametri
        if (empty($nlcontent)) {
            http_response_code(400);
            die('Parametro nlcontent mancante');
        }

        // Tipi di feed validi - letti dalla configurazione
        $config = NewsletterConfig::getConfig();
        $valid_feeds = ['subject', 'summary']; // Feed di sistema sempre validi
        
        // Aggiungi i feed configurati
        foreach ($config->feeds as $feed) {
            $valid_feeds[] = $feed->name;
        }

        if (!in_array($nlcontent, $valid_feeds)) {
            http_response_code(400);
            die('Tipo di feed non valido: ' . $nlcontent . '. Feed validi: ' . implode(', ', $valid_feeds));
        }

        try {
            // Crea l'istanza del feed
            $newsletterFeed = new Queries($nlcontent, $feed_length, $tag, $preview);
            
            // Ottieni la risposta
            $response = $newsletterFeed->getResponse();
            
            // Output della risposta
            if (is_string($response)) {
                // Imposta l'header per RSS
                header('Content-Type: '.feed_content_type('rss-http').'; charset='.get_option('blog_charset'), true);
                echo $response;
            } else {
                // Se è un array, convertilo in JSON per debug
                header('Content-Type: application/json');
                echo json_encode($response, JSON_PRETTY_PRINT);
            }
            
        } catch (Exception $e) {
            http_response_code(500);
            error_log('Newsletter Feed Error: ' . $e->getMessage());
            die('Errore nella generazione del feed: ' . $e->getMessage());
        }
    }
}
