<?php

namespace Blazemedia\Affiliation\Rendering;

use Blazemedia\Affiliation\Rendering\LinkConverter\LinkConverter;
use Blazemedia\Affiliation\Rendering\LinkParser\LinkParser;

/**
 * Parse - rileva la presenza di link di affiliazione nel contenuto 
 *         e li trasforma aggiungendo i dati a corredo 
 */
class Parse extends RenderingTemplate {

    use DirectLink\Params;
    use LinkConverter;

    protected LinkParser $parser;

    public function __construct() {

        $this->disclaimer = Disclaimer::getInstance();
        
        $this->format   = 'parse';
        $this->parser   = new LinkParser;
        $this->pageData = new PageData;

        /// rileva il link nel testo
        add_filter( 'the_content', [ $this, 'parseLinks'] , 1 );
    }


    /**
     * Rileva i link all'interno del contenuto 
     * e li trasforma aggiungendo i dati di affiliazione
     *
     * @param string $content
     * @return string
     */
    public function parseLinks( string $content ) {
    
        // conversione degli shortcode da formati precedenti
        $content = $this->convert( $content );    

        $links = $this->parser->parse( $content );
        foreach( $links as $link ) {
            //! se il link contiene il tag "data-no-affiliate" non viene modificato - modifica per la campagna paid
            if(str_contains($link->tag, 'data-no-affiliate='))continue;
            $content = str_replace( $link->tag, $this->renderLink( $link ), $content );
        }

        return $content;
    }

    
    protected function addTrackingIdPlaceholder( $link, $placeHolder = 'booBLZTRKood' ) {
        switch( strtolower( $link->marketplace ) ) {

            case 'amazon'       : return $this->addAmazonTrackingIdPlaceholder( $link->url, $placeHolder );
            case 'ebay'         : return $this->addEbayTrackingIdPlaceholder( $link->url, $placeHolder );
            case 'awin'         : return $this->addAwinTrackingIdPlaceholder( $link->url, $placeHolder );
            case 'tradetracker' : return $this->addTradeTrackerTrackingIdPlaceholder( $link->url, $placeHolder );
            case 'partnerize'   : return $this->addPartnerizeTrackingIdPlaceholder( $link->url, $placeHolder );
            case 'primevideo'   : return $this->addPrimeVideoTrackingIdPlaceholder( $link->url, $placeHolder );
            case 'impact'       : return $this->addImpactTrackingIdPlaceholder( $link->url, $placeHolder );
        }
    }

     protected function addAmazonTrackingIdPlaceholder( $url, $placeHolder ) {

        $url = str_replace('&amp;', '&', $url);

        if ( str_contains( $url, 'tag=') ) {
            
            return preg_replace('/(.*?)(tag=.*?)(\&.*|$)/', "$1tag={$placeHolder}$3", $url);
        }
        
        return $url .  ( str_contains( $url, '?') ? '&' : '?' ) . "tag={$placeHolder}";
    }


    protected function addEbayTrackingIdPlaceholder( $url, $placeHolder ) {
        /// estraggo l'url di ebay senza parametri ad eccezione del parametro "var=X"
        preg_match('/^(https:\/\/www\.ebay\.it\/itm\/\d+)\?.*var=(\d+)/', $url, $matches);
        $var = 0;
        if (!empty($matches) && count($matches) == 3){
            $url = $matches[1];
            $var = $matches[2];
        }else{
            $url = explode('?', $url)[0]; 
        }

        $attributes = [
            'mkevt'    => '1',                 // The tracking event type      | 1 = Click
            'toolid'   => '10001',             // Unique ID of link source     | 10001 = default
            'mkcid'    => '1',                 // The channel ID               | 1 = EPN
            'mkrid'    => '724-53478-19255-0', // The rotation ID for the target marketplace. | Italy (ebay.it) = 724-53478-19255-0
            'siteid'   => '101',               // Site ID to Global ID Mapping | 101 = eBay Italy
            'campid'   => '{campaign-id}',
            'customid' => $placeHolder,
            'var'      => $var
        ];

        return $url .'?'. http_build_query( $attributes);
    }

    
    protected function addAwinTrackingIdPlaceholder( $url, $placeHolder ) {

        //$prefix = preg_replace('/https:\/\/www.awin1.com\/(.*?)\?.*/', '$1', $url );
        /*
        $link = [ 
            'cread.php'   => (object) [ 'type' => 'deep',   'regex' => '/(.*awinaffid=).*?(&.*clickref=).*?(&.*)/' ], 
            'awclick.php' => (object) [ 'type' => 'landing','regex' => '/(.*awinaffid=).*?(&.*clickref=).*?(&.*)/' ]
        ][ $prefix ];*/

        $url = str_replace('&amp;', '&', $url);

        $url = preg_replace( '/(.*awinaffid=).*?(&.*clickref=).*?(&.*|$)/', '$1{{ publisher_id }}$2{{ placeholder }}$3', $url);

        /// al momento c'è solo un publisher id, quindi lo scriviamo direttamente
        /// altrimenti dobbiamo lasciarlo parametrizzato
        $publisher_id = 570971;

        return str_replace([
            '{{ publisher_id }}', '{{ placeholder }}'
            ],[
                $publisher_id, $placeHolder
            ],
            $url
        );
    }

    protected function addPrimeVideoTrackingIdPlaceholder( $url, $placeHolder ) {

        $url = str_replace('&amp;', '&', $url);

        if ( str_contains( $url, 'tag=') ) {
            
            return preg_replace('/(.*?)(tag=.*?)(\&.*|$)/', "$1tag={$placeHolder}$3", $url);
        }
        
        return $url .  ( str_contains( $url, '?') ? '&' : '?' ) . "tag={$placeHolder}";
    }

    protected function addTradeTrackerTrackingIdPlaceholder( $url, $placeHolder ) {

        $url = str_replace('&amp;', '&', $url);

        // https://tc.tradetracker.net/?c=32682&m=12&a={website_id}&r=booBLZTRKood&u=%2Fit-IT%2Ffixture%2FContentId%3A2n9b6f4f4rz4fbdpnqhts2uc4%2F2n9b6f4f4rz4fbdpnqhts2uc4

        $url = preg_replace( '/(.*&a=).*?(&r=).*?(&.*|$)/', '$1{website_id}$2{{ placeholder }}$3', $url);

        /// {website_id} sarà sostituito a valle dal rendering manager
        /// quindi lo lasciamo parametrizzato

        /// in alternativa possiamo scriverlo direttamente interrogando il rendering manager 
        /// ma non adesso
    
        return str_replace([
                '{{ placeholder }}'
            ],[
                $placeHolder
            ],
            $url
        );

    }

    protected function addPartnerizeTrackingIdPlaceholder( $url, $placeHolder ) {
        $url = str_replace('&amp;', '&', $url);
        
        $url = preg_replace( '/(.*pubref:).*?(\/.*|$.*|$)/', '$1{{ placeholder }}$2', $url);

        return str_replace([
                '{{ placeholder }}'
            ],[
                $placeHolder
            ],
            $url
        );

    }

    protected function addImpactTrackingIdPlaceholder( $url, $placeHolder ) {
        $url = str_replace('&amp;', '&', $url);
        
        $url = preg_replace( '/(.*pubref:).*?(\/.*|$.*|$)/', '$1{{ placeholder }}$2', $url);

        return str_replace([
                '{{ placeholder }}'
            ],[
                $placeHolder
            ],
            $url
        );

    }

    /**
     * Stampa il formato impostato da shortcode
     */
    public function renderLink( $link ) {

        $trackedLink = $this->addTrackingIdPlaceholder( $link, 'booBLZTRKood' );
        
        /// ricava i parametri per i link inseriti direttamente in pagina
        $directLinkParams = $this->getDirectLinkParams( $link->marketplace, $trackedLink );

        $params = $this->pageData->getParams( $directLinkParams );

        $this->getFormatData( $params );

        return $this->markup;
    }

    public function insertCSS() { }
}


