<?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 AwinAttributes extends Attributes {

    protected function setDirectLinkAttributes() {
    
        $this->label          = 'Awin';
        $this->code           = 'awin';

        $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(){

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

        $apicall = BLZ_API_RENDERING_MANAGER . 'programby/awin/' . ( ((int) $awinMid) );
        
        $program = json_decode( HttpCachedRequest::getCachedContent( $apicall , 'awin_program_'.$awinMid) );

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

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

            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, $program_id ) {

        if( !is_user_logged_in() ) return;

        $awinError = <<<HTML
            <div class="awinerror">
                <h2>ERRORE Mapping AWIN </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,        $program_id       ],
            $awinError
        );
        
    }
    

}
