<?php

namespace Blazemedia\Affiliation\Rendering;

use Blazemedia\Affiliation\API\CachedApi;
use Blazemedia\Affiliation\Rendering\Utils\RandomClassGenerator;

class Table extends RenderingTemplate {

    public function __construct( string $shortcode = 'affiliate_table', string $format = 'table', string $format_id = 'table_id' ) {

        parent::__construct( $shortcode, $format, $format_id );
    }

    /**
     * Stampa il formato impostato da shortcode
     */
    public function manageLink( $atts, $content, $tag ) {

        $params = $this->pageData->getParams([
            
            'format'     => $this->format,
            'format_id'  => $atts[ $this->format_id ],
            'link_id'    => 0,
            'extra'      => urlencode(json_encode( [] ))
        ]);

        
        /// richiede il markup del link
        $this->getFormatData( $params );

        $this->randomizeClassForAdBlockers();

        $this->replaceImageAddressWithCurrentDomain();

        //if( PrintPaidJs::isPaid() ) {
            
            $this->replaceImageAddressWithCdn();
        //}
        
        return $this->markup;
    }


    function randomizeClassForAdBlockers() { 

        // randomize class for adblockers
        $random_class_markup = RandomClassGenerator::getInstance();

        $this->markup = str_replace('blz_grid', $random_class_markup->getRandomClass() , $this->markup);
    }

    function replaceImageAddressWithCdn() : void {

        preg_match_all( '/(https:\/\/format-provider.*?)"/', $this->markup, $matches );

        if( empty($matches[1]) ) return;

        foreach( $matches[1] as $imgPath ) {

            $this->markup = str_replace( $imgPath, $this->getCdnAddress( $imgPath ), $this->markup );            
        }
    }

    function replaceImageAddressWithCurrentDomain(){

        $domain = $this->pageData->getDomain();

        if( $domain == 'punto-informatico.it' ){

            $this->markup = str_replace( 'format-provider.blazemedia.it', 'format-provider.punto-informatico.it', $this->markup );        
        } 
    }


    function getCdnAddress( string $imgPath ) {
    
        // $imgPath = "https://format-provider.blazemedia.it/app/uploads/2023/03/norton-360.png";

        $domain = $this->pageData->getDomain();

        $secret = 'w6MUZgrV8auJh4yv';

        $signature = hash_hmac("sha1", $imgPath, $secret, true);
        $signature = strtr( base64_encode($signature), '/+', '_-' );

        return "https://cdn.{$domain}/{$signature}/{$imgPath}";
    }


}


