<?php

namespace NewsletterBridge\Services\Newsletter;

/**
 * Classe per recuperare contenuti newsletter da feed esterni
 * Fa chiamate HTTP ai feed esterni
 */
class NewsletterFeed {


    function __construct( public bool $dryrun = false ) {
        // Mantiene solo la logica per chiamate HTTP esterne
    }

    
    function getSubject( bool $flagAsSent = false ) {

        $subject = $this->get( 'subject', $flagAsSent );

        $subject = str_replace([ '&#8217;', '"' ], "'", $subject);

        return $subject;
    }


    function getSummary( bool $flagAsSent = false ) {

        return $this->get( 'summary', $flagAsSent );
    }

    
    // Metodo flagPostsAsSent rimosso - non più necessario


    function get( string $method, bool $flagAsSent = false ) {
        
        $cacheBreaker = rand(0, 9999);
        $sent         = $flagAsSent ? 'true' : 'false';

        // Usa l'URL del sito WordPress invece del campo dominio
        $site_url = get_home_url();
        $url = "{$site_url}/newsletter-feed/?nlcontent={$method}&newsletter_sent={$sent}&rnd={$cacheBreaker}";

        return $this->doCall( $url );
    }


    protected function doCall( $url ) {

        $streamContext = stream_context_create([ 
            "ssl"=> [
                "verify_peer"=>false,
                "verify_peer_name"=>false
            ],
            "http" => [
                "timeout" => 500 // Timeout in seconds
            ]
        ]);  

        return  file_get_contents( $url, false, $streamContext );

    }

}
