<?php

namespace Blazemedia\Affiliation\Rendering\DirectLink;

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_LINK_PROVIDER . 'program_by_awin_id/' . ( ((int) $awinMid) );
        
        $program = json_decode( HttpRequest::getContent( $apicall ) );

        /// 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[0]->name,
            'suffix'       => $program[0]->program_suffix,
            'subject'      => $program[0]->related_subject,
            'subject_code' => $program[0]->related_subject_code,
            'theme_label'  => $program[0]->related_theme,
            'theme_code'   => $program[0]->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
        );
        
    }
    

}
