<?php

namespace Blazemedia\Affiliation\Rendering\DirectLink;

use Blazemedia\Affiliation\Utils\HttpCachedRequest;
use Blazemedia\Affiliation\Utils\HttpRequest;

/**
 * Sono i parametri per i link diretti 
 * ( tipicamente Amazon/eBay )
 */
class TradeTrackerAttributes extends Attributes {
    
    protected function setDirectLinkAttributes() {
    
        $this->label          = 'Tradetracker';
        $this->code           = 'trck';

        $program = $this->getProgramData();

        $this->program        = $program->name;
        $this->program_suffix = $program->suffix;
        $this->subject        = $program->subject;
        $this->subject_code   = $program->subject_code;
        $this->theme_label    = $program->theme_label;
        $this->theme_code     = $program->theme_code;
        
    }

    protected function getProgramData(){

        $tt_program_id = preg_replace( '/.*c=(\d*?)&.*/', '$1', $this->url );

        $apicall = BLZ_API_RENDERING_MANAGER . 'programby/tradetracker/' . ( ((int) $tt_program_id) );
        
        $program = json_decode( HttpCachedRequest::getCachedContent( $apicall , 'tradetracker_program_'.$tt_program_id) );

        /// deve restituire un errore 
        if( empty( $program ) ) {

            $this->printError( $this->url, $tt_program_id );

            return (object) [

                'name'         => '',
                'suffix'       => '',
                'subject'      => '',
                'subject_code' => '',
                'theme_label'  => '',
                'theme_code'   => ''
            ];
        }

    
        return (object) [

            'name'         => $program->name,
            'suffix'       => $program->program_suffix,
            'subject'      => $program->related_subject,
            'subject_code' => $program->related_subject_code,
            'theme_label'  => $program->related_theme,
            'theme_code'   => $program->related_theme_code,
        ];

    }


    protected function printError( $link, $tt_program_id ) {

        if( !is_user_logged_in() ) return;

        $awinError = <<<HTML
            <div class="awinerror">
                <h2>ERRORE Mapping Tradetracker </h2>                    
                Il link : {{ link }}<br>
                Presenta l'id programma {{ program_id }} non mappato
            </div>
            <style>.awinerror{ background: red; color: white }</style>
        HTML;

        echo str_replace( 
            [ '{{ link }}', '{{ program_id }}'],
            [ $link,        $tt_program_id       ],
            $awinError
        );
        
    }

}
