<?php

namespace Blazemedia\Affiliation\Rendering\LinkConverter;

use Blazemedia\Affiliation\Utils\SimpleDB;

trait LinkConverter {


    protected SimpleDB $db;

    /**
     *  converte tutti i link nel content
     *
     * @param string $content
     * @return string
     */
    function convert( string $content ) : string {

        $content = $this->convertPriceLinks( $content );
        $content = $this->convertPriceAndParseButtons( $content );
        $content = $this->convertTables( $content );
        $content = $this->convertStoredLinks( $content );
        $content = $this->convertBitly($content);
        
        return $content;
    }

    function convertPriceLinks( $content ) {

        $price_patterns = [
            '/\[affiliate_link marketplace=amazon[^\]]*code=(.*?)(|\s.*)\]/',
            '/\[affiliate_link marketplace=ebay[^\]]*code=(.*?)(|\s.*)\]/',
            '/\[affiliate_link marketplace=ebay[^\]]*keyword=(.*?)(|\s.*)\]/'
        ];

        $price_replace = [
            '[affiliate_price link="https://www.amazon.it/dp/{{ code }}?tag=booBLZTRKood&linkCode=ogi&th=1&psc=1" program="Amazon"]',
            '[affiliate_price link="https://www.ebay.it/itm/{{ code }}?mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=booBLZTRKood" program="eBay"]',
            ''
        ];


        foreach( $price_patterns as $idx => $price_pattern) {

            preg_match_all( $price_pattern, $content, $matches );    
            
            [ $shortcodes, $codes ] = $matches;
            
            if( !empty( $shortcodes ) ) {
                
                foreach( $shortcodes as $key => $shortcode ) {
                    
                    $new_shortcode =  str_replace( '{{ code }}', $codes[ $key ], $price_replace[ $idx ] );
                    
                    $content = str_replace( $shortcode, $new_shortcode, $content );
                }
            }

        }

        return $content;
    }

    /**
     * Converte i price link
     *
     * @param string $content
     * @return string 
     */
    function convertPriceAndParseButtons( string $content ) : string {    
    
        $price_patterns = [
            '/(.*?)\[affiliate_link marketplace\=amazon[^\]]*?code\=(.*?)\s.*?\](.*?)/',
            '/(.*?)\[affiliate_link marketplace\=ebay[^\]]*?code\=(.*?)\s.*?\](.*?)/',
            '/(.*?)\[affiliate_link marketplace\=[^\]]*?keyword\=(.*?)\s.*?\](.*?)/'
        ];

        $price_replace = [
            '$1[affiliate_price link="https://www.amazon.it/dp/$2?tag=booBLZTRKood&linkCode=ogi&th=1&psc=1" program="Amazon"]$3',
            '$1[affiliate_price link="https://www.ebay.it/itm/$2?mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=booBLZTRKood" program="eBay"]',
            '$1$3',
        ];

        $parse_button_patterns = [
            '/(.*?)\[affiliate_generic type=\"button\"[^\]]*?url=\"https:\/\/www.amazon.it\/(.*?)dp\/(.*?)\" text=\"(.*?)\"\](.*?)/',
            '/(.*?)\[affiliate_generic type=\"button\"[^\]]*?url=\"https:\/\/www.ebay.it\/itm\/(.*?)\" text=\"(.*?)\"\](.*?)/',
            '/(.*?)\[affiliate_generic type=\"button\"[^\]]*?url=\"https:\/\/www.amazon.it\/(.*?)gp\/product\/(.*?)\" text=\"(.*?)\"\](.*?)/',
            
        ];

        $parse_button_replace = [
            '[parse_button link="https://www.amazon.it/dp/$3?tag=booBLZTRKood" program="Amazon" format_id="70"]$4[/parse_button]',
            '[parse_button link="https://www.ebay.it/itm/$2?mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=booBLZTRKood" program="eBay" format_id="70"]$3[/parse_button]',
            '[parse_button link="https://www.amazon.it/dp/$3?tag=booBLZTRKood" program="Amazon" format_id="70"]$4[/parse_button]',
            
        ];
        
        $content = str_replace(['&#8221;'],['"'],$content);

        $content =  preg_replace( 
            array_merge( $price_patterns, $parse_button_patterns ), 
            array_merge( $price_replace,  $parse_button_replace  ), 
            $content 
        );        

        $content = $this->convertNonProductLinks( $content );

        return $content;
    }


    function convertNonProductLinks( $content ) {

        $parseButtonTemplate = '[parse_button link="{{ link }}" program="{{ program }}" format_id="70"]{{ text }}[/parse_button]';

        $amazonLinkPattern = '/(.*?)(\[affiliate_generic\s*type="button\"[^u]*?url=\"(https:\/\/www.amazon.it.*?)\".*?text=\"(.*?)\"\])(.*?)/s';

        preg_match_all( $amazonLinkPattern, $content, $matches );
        
        $amazonShortcodes = empty( $matches[0] ) ? [] :  array_map( fn( $idx, $item ) => [
                
                'old'     => $item,
                'link'    => str_replace( '&amp;', '&', $this->addAmazonTag( $matches[3][$idx] ) ),
                'text'    => $matches[4][$idx],
                'program' => 'Amazon',
                
        ], array_keys($matches[2]), $matches[2] );


        $ebayLinkPattern = '/(.*?)(\[affiliate_generic\s*type="button\"[^u]*?url=\"(https:\/\/www.ebay.it.*?)\".*?text=\"(.*?)\"\])(.*?)/s';

        preg_match_all( $ebayLinkPattern, $content, $matches );

        $ebayShortcodes = empty( $matches[0] ) ? [] :  array_map( fn( $idx, $item ) => [
                
                'old'  => $item,
                'link' => str_replace( '&amp;', '&', $this->addAmazonTag( $matches[3][$idx] ) ),
                'tezt' => $matches[4][$idx],
                
        ], array_keys($matches[2]), $matches[2] );


        foreach( array_merge( $amazonShortcodes, $ebayShortcodes ) as $shortcode ) {

            $content = str_replace( 
                $shortcode['old'],
                str_replace( 
                    ['{{ link }}','{{ text }}','{{ program }}' ], 
                    [ $shortcode['link'], $shortcode['text'], $shortcode['program'] ],
                    $parseButtonTemplate 
                ),
                $content
            );

        }

        return $content;        
    }


    function addAmazonTag( $link, ) {

        if( str_contains( $link, 'tag=' ) ) return preg_replace( '/tag=.*?(&|$)/', 'tag=booBLZTRKood$1', $link );

        return str_contains( $link, '?' ) ? "{$link}&tag=booBLZTRKood" : "{$link}?tag=booBLZTRKood";
    }


    function addEbayTag( $link ) {

        if( str_contains( $link, 'sch' ) ) {

            return "{$link}&mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=booBLZTRKood";
        }

        $url = explode( '?', $link)[0];

        return "{$url}?mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=booBLZTRKood";

    }

    function convertBitly( string $content ) : string {

        $parse_button_patterns = [
            '/(.*?)\[affiliate_generic type=\"button\" url=\"https:\/\/amzn\.eu\/(.*?)\" text=\"(.*?)\"\](.*?)/',            
        ];

        $parse_button_replace = [
            '<div class="IPNRIELBKGE"><a href="https://amzn.eu/$2" class="btn custom_btn" target="_blank" rel="nofollow">$3</a></div><style>.IPNRIELBKGE { text-align:center }</style>'
        ];
        
        

        $content = str_replace(['&#8221;'],['"'],$content);

        $content =  preg_replace( 
            array_merge( $parse_button_patterns ), 
            array_merge( $parse_button_replace  ), 
            $content 
        );        

        return $content;
        
    }

    function convertStoredLinks( string $content ) : string {    

        $this->db = SimpleDB::getInstance();

        $link_patterns = [
           'servizi' => '/\[affiliate_program_link.*?\](.*?)\[\/affiliate_program_link\]/s',
           'stored'  => '/\[affiliate_program_stored_link.*?\](.*?)\[\/affiliate_program_stored_link\]/s'
        ];
        
        $content = str_replace(['&#8221;'],['"'],$content);

        foreach( $link_patterns as $type => $link_pattern ) {

            preg_match_all( $link_pattern, $content, $matches );

            if( !empty( $matches[0] ) ) {

                foreach( $matches[0] as $index => $shortcode ) {

                    //$shortcode = str_replace('&amp;','&', $shortcode );

                    $text = $matches[1][$index];

                    $newShortcode = $this->db->getNewShortcode( $shortcode );

                    if( $newShortcode !== null ) {

                        $content =  str_replace( $shortcode, $newShortcode, $content );

                    } else {

                        if ( $type == 'servizi' ) {

                            $content = str_replace( $shortcode, $this->replaceMarkup( $shortcode, $text ), $content );
                        }
                    }
                }
            }

        }

        return $content;
    }

    function convertTables( string $content ) : string {    

        $this->db = SimpleDB::getInstance();

        $table_patterns = [
            '/\[custom_table\s*id=(\d+).*\]/', 
            '/{{custom_table=(\d+)}}/'           
        ];
        
        $content = str_replace(['&#8221;'],['"'],$content);

        foreach( $table_patterns as $table_pattern ){

            preg_match_all( $table_pattern, $content, $matches );

            if( !empty( $matches[0] ) ) {
                
                foreach( $matches[0] as $shortcode ) {

                    $old_shortcode = str_contains( $table_pattern, '{{' ) ? "[custom_table id={$matches[1][$index]}]" : $shortcode;
                    
                    $newShortcode = $this->db->getNewShortcode( $old_shortcode );


                    if( $newShortcode !== null ) {

                        $content =  str_replace( $shortcode, $newShortcode, $content );

                    }  /*else {

                        if ( $type == 'servizi' ) {

                            $content = str_replace( $shortcode, $this->replaceMarkup( $shortcode, $text ), $content );
                        }
                    }*/
                }
            }

        }

        return $content;
    }

    function replaceMarkup( $shortcode, $text ) {

        if ( !str_contains( $shortcode, 'link' ) ) return $text;
        $link    = str_replace( '&amp;', '&', preg_replace( '/.*link="(.*?)".*/' , '$1', $shortcode ) );
        $type    = preg_replace( '/.*type="(.*?)".*/' , '$1', $shortcode ) == $shortcode ? 'text' : preg_replace( '/.*type="(.*?)".*/' , '$1', $shortcode );

        $markup = [

            'text'   => '<a href="{{ link }}" rel="nofollow">{{ text }}</a>',
            'button' => '<div class="IPNRIELBKGE"><a href="{{ link }}" class="btn custom_btn" target="_blank" rel="nofollow">{{ text }}</a></div><style>.IPNRIELBKGE { text-align:center }</style>'            
        ];

        return str_replace(
            ['{{ text }}','{{ link }}'],
            [ $text, $link ],
            $markup[ $type ]
        );
    }


}