<?php
add_filter('wp_head', 'irpp_head');
function irpp_head() {
    global $post, $irpp;

    $irpp->Log->startTime('irpp_head');
    if($irpp->Options->getPostShown()===FALSE || is_null($irpp->Options->getPostShown())) {
        $irpp->Options->initRelatedPostsIds(NULL);
        $irpp->Options->setPostShown(NULL);
        if($post && isset($post->ID) && is_single($post->ID)) {
            $irpp->Options->setPostShown($post);
            $args=array('postId'=>$post->ID, 'shuffle'=>TRUE, 'count'=>-1);
            $ids=$irpp->Manager->getRelatedPostsIds($args);
            $irpp->Options->initRelatedPostsIds($ids, $post->ID);
            //$irpp->Log->info('POST ID=%s IS SHOWN, RELATED POSTS=%s', $post->ID, $ids);
        }
    }
    $irpp->Log->pauseTime();
}
add_filter('wp_footer', 'irpp_footer');
//add_filter('admin_footer', 'irpp_footer');
function irpp_footer() {
    global $irpp;

    $irpp->Log->startTime('irpp_footer');
    $array=$irpp->Options->getCssStyles();
    if(count($array)>0) {
        echo "<style>\n";
        foreach($array as $v) {
            echo $v;
            echo "\n";
        }
        echo "</style>\n";
    }
    $irpp->Log->pauseTime();
    $irpp->Log->stopTime();
}

if(shortcode_exists('irp')) {
    remove_shortcode('irp');
}
add_shortcode('irp', 'irpp_shortcode');
function irpp_shortcode($atts, $content='') {
    global $irpp, $post;
    if(!$irpp->Options->isActive()) {
        return '';
    }

    $default=array(
        'posts'=>''
        , 'name'=>''
        , 'cats'=>''
        , 'tags'=>''
        , 'count'=>1
        , 'theme'=>''
        , 'demo'=>FALSE
        , 'ctaText'=>'default'
        , 'ctaTextColor'=>'default'
        , 'postTitleColor'=>'default'
        , 'boxColor'=>'default'
        , 'borderColor'=>'default'
        , 'hasPoweredBy'=>'default'
        , 'hasShadow'=>'default'
        , 'defaultsColors'=>FALSE
        , 'includeCss'=>TRUE
    );
    $options=$irpp->Utils->shortcodeAtts($default, $atts);
    if(isset($options['postId'])) {
        unset($options['postId']);
    }
    $options['demo']=$irpp->Utils->isTrue($options['demo']);
    $options['count']=intval($options['count']);
    if($options['count']<=0) {
        return '';
    }

    if($options['posts']=='' && $options['cats']=='' && $options['tags']=='') {
        //dynamic
        $ids=$irpp->Options->getToShowPostsIds($options['count'], TRUE);
    } else {
        if($options['posts']=='current' && $post && isset($post->ID)) {
            $options['posts']=$post->ID;
        }
        //static
        $ids=$irpp->Manager->getRelatedPostsIds($options);
    }

    $keys=array('ctaText', 'ctaTextColor', 'postTitleColor', 'boxColor', 'borderColor', 'hasPoweredBy', 'hasShadow');
    foreach($keys as $k) {
        if($options[$k]=='default') {
            unset($options[$k]);
        }
    }
    $result=irpp_ui_get_box($ids, $options);
    if($result!='') {
        $irpp->Options->setShortcodeUsed(TRUE);
    }
    return $result;
}

function irpp_ui_get_box($ids, $options=NULL) {
    global $irpp;
    if(!is_array($ids) || count($ids)==0) {
        return "";
    }
    if(!is_array($options)) {
        $options=array();
    }

    $irpp->Log->startTime('irpp_ui_get_box');
    $defaults=array(
        'includeCss'=>TRUE
        , 'comment'=>''
        , 'shortcode'=>FALSE
        , 'preview'=>FALSE
        , 'theme'=>''
        , 'demo'=>FALSE
        , 'array'=>FALSE
        , 'defaultsColors'=>FALSE
    );
    $options=$irpp->Utils->parseArgs($options, $defaults);
    $body='';
    if($options['shortcode']) {
        $body='[irpx posts="'.implode(',', $ids).'" comment="'.$options['comment'].'"]';
    } else {
        $defaults=$irpp->Options->getTemplateStyle();
        $options=$irpp->Utils->parseArgs($options, $defaults);
        if($options['theme']!='') {
            $options['template']=$options['theme'];
        }
        unset($options['theme']);

        if ($options['ctaText'] == 'READ') {
            $options['ctaText'] = __('READ', IRPP_PLUGIN_SLUG);
        }

        $posts=array();
        foreach($ids as $postId) {
            $v=get_post($postId);
            if($v) {
                $posts[]=$v;
            }
        }
        if(count($posts)>0) {      
            $id = rand(0, count($posts)-1);
            $v = $posts[$id];
            $options['postHref']=get_permalink($v->ID);
            if (empty($options['name'])) {
                $options['postTitle'] = $v->post_title;
            } else {
                $options['postTitle'] = $options['name'];
            }

            $options['postImageUrl']='';
            //$options['postImageWidth']=0;
            //$options['postImageHeight']=0;
            $attachmentId=get_post_thumbnail_id($v->ID);
            if($attachmentId!==FALSE && $attachmentId!=='' && intval($attachmentId)>0) {
                $array=wp_get_attachment_image_src($attachmentId, 'medium');
                if($array!==FALSE) {
                    $options['postImageUrl']=$array[0];
                    //$options['postImageWidth']=$array[1];
                    //$options['postImageHeight']=$array[2];
                }
            }
            if($options['postImageUrl']=='') {
                $content=$v->post_content;
                $regex='/<img[^>]+(src="([^"]*)")/';
                $matches=array();
                preg_match_all($regex, $content, $matches);
                $matches=array_reverse($matches);
                if (isset($matches[0][0])) {
                    $options['postImageUrl']=$matches[0][0];
                }
            }

            if($irpp->Utils->isTrue($options['defaultsColors'])) {
                $defaults = $irpp->HtmlTemplate->getDefaults();
                $defaults = $defaults[$options['template']];
                foreach ($defaults as $k => $v) {
                    $options[$k] = $v;
                }
            }
            if($irpp->Utils->isTrue($options['demo'])) {
                $options['postHref']='javascript:void(0);';
                $options['linkRel'] = IRP_DEFAULT_LINK_REL_ATTRIBUTE;
                $options['linkTarget']='';
                //$options['hasShadow']=TRUE;
                //$options['hasPoweredBy']=1;
                $ctaText=$irpp->Utils->qs('ctaText');
                if($ctaText!='') {
                    $options['ctaText']=$ctaText;
                }
                $postTitle=$irpp->Utils->qs('postTitle');
                $postTitle=str_replace("\\\"", "\"", $postTitle);
                if($postTitle!='') {
                    $options['postTitle']=$postTitle;
                }
                $uri=$irpp->Utils->qs('postImageUrl');
                //$w=$irpp->Utils->iqs('postImageWidth');
                //$h=$irpp->Utils->iqs('postImageHeight');
                if($uri!='') {
                    $options['postImageUrl']=$uri;
                    //$options['postImageWidth']=$w;
                    //$options['postImageHeight']=$h;
                }
            } elseif($irpp->Utils->isTrue($options['preview'])) {
                $options['postHref']='javascript:IRPP_changeRelatedBox();';
                $options['linkRel'] = IRP_DEFAULT_LINK_REL_ATTRIBUTE;
                $options['linkTarget']='';
            }

            $body=$options;
            if($options['array']==FALSE) {
                $body=$irpp->HtmlTemplate->html($options['template'], $options, $options);
            }
        }
    }
    $irpp->Log->pauseTime();
    return $body;
}

/*add_filter('the_content', 'irpp_fix_the_content');
function irpp_fix_the_content($content) {
    //this is to prevent wrong rewrite of WP of our content
    $content=str_replace("<p></a></p>", "</a>", $content);
    $content=str_replace("<p></a>", "</a>", $content);
    return $content;
}*/
//add_filter('wp_head', 'irpp_the_content');


add_filter('the_content', 'irpp_the_content', intval(get_option('IRP_HookPriority','99999')));

function irpp_the_content($content) {
    global $irpp, $post;
    $irpp->Log->startTime('irpp_the_content');
    if(!$post || trim($content)=='') {
        return $content;
    }

    if($irpp->Options->getPostShown()===FALSE || is_null($irpp->Options->getPostShown())) {
        $irpp->Options->initRelatedPostsIds(NULL);
        $irpp->Options->setPostShown(NULL);
        if($post && isset($post->ID) && is_single($post->ID)) {
            $irpp->Options->setPostShown($post);
            $args=array('postId'=>$post->ID, 'shuffle'=>TRUE, 'count'=>-1);
            $ids=$irpp->Manager->getRelatedPostsIds($args);
            $irpp->Options->initRelatedPostsIds($ids, $post->ID);
            //$irpp->Log->info('POST ID=%s IS SHOWN, RELATED POSTS=%s', $post->ID, $ids);
        }
    } else {
        $irpp->Options->refreshRelatedPostsIds();
    }

    if($irpp->Options->isPostShownExcluded()) {
        $irpp->Log->error('TheContent: POST UNDEFINED OR POST EXCLUDED');
        return $content;
    }

    if(!$irpp->Options->isActive() || !$irpp->Options->isRewriteActive()) {
        $irpp->Log->error('TheContent: NOT ACTIVE NOT REWRITE ACTIVE');
        return $content;
    }
    if($irpp->Options->isShortcodeUsed()) {
        $irpp->Log->error('TheContent: NOT ACTIVE DUE TO SHORTCODE USED');
        return $content;
    }
    if(!$irpp->Options->hasRelatedPostsIds()) {
        $irpp->Log->error('TheContent: NOT ACTIVE DUE TO WITHOUT RELATED POSTS');
        return $content;
    }

    $body=$content;
    /*if(strpos($body, '[irp')!==FALSE) {
        $irpp->Log->error('TheContent: SHORTCODE DETECTED');
        $irpp->Options->setShortcodeUsed(TRUE);
        return;
    }*/

    $context=new IRPP_HTMLContext();
    $irpp->Options->setRewriteBoxesWritten(0);
    $body=$context->execute($body);

    $irpp->Log->pauseTime();
    $irpp->Log->info('TheContent: BODY SUCCESSULLY CREATED');
    //$body=apply_filters('the_content', $body);
    //$post->post_content=$body;
    return $body;
}
function irpp_ui_first_time() {
    global $irpp;
    if($irpp->Options->isShowActivationNotice()) {
        //$tcmp->Options->pushSuccessMessage('FirstTimeActivation');
        //$tcmp->Options->writeMessages();
        $irpp->Options->setShowActivationNotice(FALSE);
    }
}
function irpp_get_list_posts() 
{
	global $irpp;

	$result = array();

	$search = strip_tags(trim($_GET['q'])); 
	add_filter('posts_where', function( $where ) use ($search) {
		$where .= (" AND post_title LIKE '%" . $search . "%'");
		return $where;
	});

    if (esc_attr($_REQUEST['irpp_post_type']) == 'post') {
        $postTypes = $irpp->Utils->getSelectedPostTypes();
    } else {
        $postTypes = esc_attr($_REQUEST['irpp_post_type']);
    }
	
	$query = array(
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'post_type' => $postTypes,
		'order' => 'ASC',
		'orderby' => 'title',
		'suppress_filters' => false,
	);
	
	$posts = get_posts( $query );

	foreach ($posts as $this_post) {
			
		$post_title = $this_post->post_title;
		$id = $this_post->ID;
	
		$result[] = array(
			'text' => $post_title,
			'id' => $id,
		);
			
	}
	
	$posts['items'] = $result;
	echo json_encode($posts);
		
	die();

}
add_action( 'wp_ajax_irpp_list_posts', 'irpp_get_list_posts' );