<?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 PartnerizeAttributes extends Attributes {
    
    protected function setDirectLinkAttributes() {
    
        $this->label          = 'Partnerize';
        $this->code           = 'ptnz';

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

        $partnerize_program_id_found = preg_match('/camref:(.*?)\//', $this->url, $matches);

        $program = null;

        if( $partnerize_program_id_found ) {

            $partnerize_program_id = $matches[1]; 

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

            $apicall = BLZ_API_RENDERING_MANAGER . 'programby/partnerize/' . ( ( $partnerize_program_id) );
            
            $program = json_decode( HttpCachedRequest::getCachedContent( $apicall , 'partnerize_program_'.$partnerize_program_id) );
        }

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

            $this->printError( $this->url, $partnerize_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, $partnerize_program_id ) {

        if( !is_user_logged_in() ) return;

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

}
