<?php

namespace Blazemedia\Affiliation\Rendering;

use Blazemedia\Affiliation\Utils\Logger;
use Blazemedia\Affiliation\Rendering\Parameters;
use Blazemedia\Affiliation\Support\Environment;

/**
 * Effettua la richiesta al server per ottenere i formati dell'affiliazione
 * 
 */
class AffiliationClient {

    use Trait\DebugPrint;
    
    const TIMEOUT = 15;

    protected string $baseUrl;
    private string $apiSecret;
    public Parameters $parameters;
    private \WP_Post $post;

    
    public function __construct( \WP_Post $post ) {

        $this->baseUrl = Environment::get('BLZ_API_RENDERING_MANAGER', 'https://rendering-manager.blazemedia.it/api/') . 'v2/';
        $this->apiSecret = (string) Environment::get('BLZ_AFF_API_SECRET');
        $this->post = $post;
        $this->parameters = new Parameters( $this->post );
    }


    public function getRenderResponse(): RenderResponse {

        if ($this->apiSecret === '') {
            Logger::write("AffiliationClient: API Secret mancante, impossibile generare la firma", "ERROR");
            return new RenderResponse;
        }

        $signature  = $this->parameters->getSignature( $this->apiSecret );
       
        $apiCall = $this->baseUrl . 'render/content/' . $signature;
        
        $options = [
            'headers'   => [
                'Content-Type' => 'application/json',
                'X-API-Key'    => $signature,
                'Source'       => get_permalink($this->post->ID),
            ],
            'body'      => json_encode($this->parameters->toArray() ),
            'timeout'   => self::TIMEOUT,
            'sslverify' => false,
            'Accept'     => 'application/json',
        ];

        try {
            
            $response = wp_remote_post( $apiCall, $options );

        } catch (\Throwable $th) {

            //TODO:: LOG ERROR WITH OPENTELEMETRY
            Logger::write("Error getting values for post {$this->post->ID} - {$this->post->post_title}: " . $th->getMessage(), "ERROR");

            return new RenderResponse;
        }

        if (is_wp_error($response)) {

            Logger::write("Error getting values for post {$this->post->ID} - {$this->post->post_title}: " . $response->get_error_message(), "ERROR");

            return new RenderResponse;
        }

        $responseCode = wp_remote_retrieve_response_code($response);

        if ($responseCode !== 200) {
            Logger::write("Error getting values for post {$this->post->ID} - {$this->post->post_title}: " . $responseCode, "ERROR");
            return new RenderResponse;
        }

        $responseBody = wp_remote_retrieve_body($response);
        if (empty($responseBody)) {
            Logger::write("Error getting values for post {$this->post->ID} - {$this->post->post_title}: Empty body", "ERROR");
            return new RenderResponse;
        }
        $renderResponse = new RenderResponse($responseBody, ['options' => $options, 'parameters' => $this->parameters]);

        return $renderResponse;
    }


}
