<?php
class AMVG_Native_Item {

    protected $item,
              $video_block,
              $params;

    function __construct( $video_block ){
        $this->video_block = $video_block;
    }

    public function init( $params, $feed_infos){

        if( empty( $params ) || empty( $feed_infos ) ) return false;

        $params       = json_decode( json_encode( $params ), true );
        $feed_infos   = json_decode( json_encode( $feed_infos ), true );
        $partner_id   = $params['partner']['id'];

        $this->params = $params;

        $this->item['id']               = $this->get_partner_feed_infos('feed_item_id',               $partner_id, $feed_infos);
        $this->item['title']            = $this->get_partner_feed_infos('feed_item_title',            $partner_id, $feed_infos);
        $this->item['desc']             = $this->get_partner_feed_infos('feed_item_desc',             $partner_id, $feed_infos);
        $this->item['tags']             = $this->get_partner_feed_infos('feed_item_tags',             $partner_id, $feed_infos);
        $this->item['more_tags']        = $this->detect_more_tags();
        $this->item['length']           = $this->get_partner_feed_infos('feed_item_length',           $partner_id, $feed_infos);
        $this->item['length_format']    = $this->get_partner_feed_infos('feed_item_length_format',    $partner_id, $feed_infos);
        $this->item['thumb_url']        = $this->get_partner_feed_infos('feed_item_thumb_url',        $partner_id, $feed_infos);
        $this->item['thumbs_urls']      = $this->get_partner_feed_infos('feed_item_thumbs_urls',      $partner_id, $feed_infos);
        $this->item['video_url']        = $this->get_partner_feed_infos('feed_item_video_url',        $partner_id, $feed_infos);
        $this->item['tracking_url']     = $this->get_partner_feed_infos('feed_item_join_url',         $partner_id, $feed_infos);
        $this->item['code']             = $this->get_partner_feed_infos('feed_item_code',             $partner_id, $feed_infos);
        $this->item['actors']           = $this->get_partner_feed_infos('feed_item_actors',           $partner_id, $feed_infos);
    }

    public function get_id(){
        return AMVG_Item::get_id( $this->item );
    }

    public function is_valid(){
        return AMVG_Item::is_valid( $this->item );
    }

    public function get_data_for_js(){
        return AMVG_Item::get_data_for_js( $this->item );
    }

    public function get_data_for_json( $cpt = 0 ){
        return AMVG_Item::get_data_for_json( $this->item, $cpt = 0 );
    }

    private function get_partner_feed_infos( $partner_feed_item, $partner_id, $feed_infos ){

        $output             = false;
        $feed_item_type     = isset( $feed_infos[$partner_feed_item] ) ? key( $feed_infos[$partner_feed_item] ) : null;
        $short_item         = '';

        if( isset( $feed_infos[$partner_feed_item][$feed_item_type] ) ){

            $short_item = $feed_infos[$partner_feed_item][$feed_item_type];

            if( $feed_item_type != 'find' ){

                $results = array();
                preg_match_all("/<%(.+)%>/U", $short_item, $results);

                foreach ($results[1] as $result) {
                    if( strpos($result, 'get_partner_option') !== false){
                        $saved_partner_options  = WPSCORE()->get_product_option( 'AMVG', $partner_id . '_options' );
                        $option                 = str_replace( array( 'get_partner_option("', '")'), array('', ''),  $result);
                        $new_result             = '$saved_partner_options["' . $option . '"]';
                        $short_item             = str_replace('<%' . $result . '%>', eval('return ' . $new_result . ';'), $short_item);
                    }else{
                        $short_item             = str_replace('<%' . $result . '%>', eval('return ' . $result . ';'), $short_item);
                    }
                }
                unset($results);
            }

            switch ($feed_item_type) {
                case 'find':
                    $video_block    = $this->video_block;
                    $query          = $short_item['query'];
                    $offset         = $short_item['offset'];
                    $attr           = $short_item['attr'];

                    if( isset( $short_item['loop'] ) && isset( $short_item['separator'] ) ){

                        $blocks = $video_block->find( (string) $query );

                        foreach( (array) $blocks as $block ){
                            $output[] = $block->{$attr};
                        }

                        $output = implode( $short_item['separator'], (array) $output );

                    }else{
                        if( $query != '' ){
                            $output = $video_block->find( (string) $query, (int) $offset )->{$attr};
                        }else{
                            $output = $video_block->{$attr};
                        }
                    }

                    //xhamster thumb size
                    if( strpos($output, 'xhcdn.com') !== false  ){
                        $output = preg_replace('/([0-9]+_)/i', "640/$1", $output);
                    }

                    //redtube thumb resize
                    $output = str_replace("eGJF8f", "eWgr9f", $output);

                    //porntube thumb resize + join_url build + multithumb build
                    $output = str_replace("240x180", "835x470", $output);
                    if( $query == 'a.thumb-link' && $attr == 'href' ){
                        $output = 'http://www.porntube.com' . $output;
                    }
                    if( $query == 'ul.mini-slide' && $attr == 'plaintext' ){
                        $output = rtrim( str_replace('.jpg', '.jpg,', $output), ',');
                    }

                    //xvideos
                    if( $query == 'script' && $attr == 'innertext' && $this->params['partner']['id'] == 'xvideos' ){
                        if( $partner_feed_item == 'feed_item_id' ){
                            preg_match("|id=\"pic_(.+)\" onload|U", $output, $matches);
                            $output = $matches[1];
                        }
                        if( $partner_feed_item == 'feed_item_thumb_url' ){
                            preg_match("|src=\"http:(.+)\.jpg|U", $output, $matches);
                            $output = str_replace('THUMBNUM', '1', $matches[1]);
                            $output = str_replace('thumbs169', 'thumbs169lll', $output . '.jpg' );
                        }
                    }

                    //xnxx
                    if( $query == 'script' && $attr == 'innertext' && $this->params['partner']['id'] == 'xnxx' ){
                        if( $partner_feed_item == 'feed_item_id' ){
                            preg_match("|id=\"pic_(.+)\" onload|U", $output, $matches);
                            $output = $matches[1];
                        }
                        if( $partner_feed_item == 'feed_item_thumb_url' ){
                            preg_match("|src=\"https:(.+)\.jpg|U", $output, $matches);
                            $output = $matches[1] . '.jpg';
                        }
                    }

                    //youjizz
                    if( $this->params['partner']['id'] == 'youjizz' ){
                        if( $partner_feed_item == 'feed_item_id' ){
                            preg_match("|-([0-9]+)\.html|U", $output, $matches);
                            $output = $matches[1];
                        }
                    }
                    break;

                default:
                    $output = $short_item;
                    break;
            }
        }
        if( !$output )
            return false;
        return AMVG_Item::clean_string( $output );
    }

    private function detect_more_tags(){

        require( AMVG_DIR . 'admin/data/tags-x/tags.php' );//$data['tags']

        $unwanted_chars     = array(',', '!', '?', ';', ':', '.');
        $title_words        = explode( ' ', strtolower( str_replace($unwanted_chars, '', $this->item['title'] ) ) );
        $rephrased_title    = implode(' ', $title_words);
        $differences_tags   = array_diff($title_words, (array)explode(',', $this->item['tags'] ));
        $more_tags          = array_intersect($differences_tags, $data['tags']);

        foreach ( (array) $data['tags'] as $tag ) {

            if( strpos($rephrased_title, $tag) !== false && count( explode( ' ', $tag) ) >= 2 ){
                $more_tags[] = $tag;
            }
        }
        
        return implode( ',', array_unique( (array) $more_tags) );
    }
}