<?php
/**
 * TC Theme Ads Functions
 *
 * @package pingraphy
 */

if (!function_exists('pingraphy_ad_managment')) :

	/**
	|------------------------------------------------------------------------------
	| Ads Managment
	|------------------------------------------------------------------------------
	| 
	| Three ads postion on single post
	| 
	| 1. After post title (Postions: left, center or right)
	| 2. Middle post content (Position: left, center or right)
	| 3. Below post content (Position: left, center or right)
	| 
	| @return void
	|
	*/

	function pingraphy_ad_managment($content) {
		global $post;


		if (!is_single()) return $content;


		$today = date_create(date('Y-m-d'));
		$published = date_create(get_the_date('Y-m-d', $post->ID));
		$interval = date_diff($today, $published);
		$age = $interval->format('%a');

		if (  $age >= ot_get_option('duration-ads-top') ) {

			if (ot_get_option('ad-after-post-title')) {
				$content = '<div class="ads-banner-block top-single-ads '. ot_get_option('top-ads-position') .'">' . ot_get_option('ad-after-post-title') . '</div>' . $content;
			}

			if (ot_get_option('ad-middle-post')) {
				$content =  pingraphy_ad_middle_content($content, '<div class="ads-banner-block middle-single-ads '. ot_get_option('middle-ads-position') .'">' . ot_get_option('ad-middle-post') . '</div>');
			}
			
			if (ot_get_option('ad-below-post')) {
				$content = $content . '<div class="ads-banner-block below-single-ads '. ot_get_option('below-ads-position') .'">' . ot_get_option('ad-below-post') . '</div>';
			}
		}

		return $content;

	}

	add_filter('the_content', 'pingraphy_ad_managment');

endif;

/**
|------------------------------------------------------------------------------
| Render ads middle post content
|------------------------------------------------------------------------------
| 
| @return string
|
*/

function pingraphy_ad_middle_content( $content, $middle_ad ) {

	$content = explode("</p>", $content);
    $new_content = '';
    $paragraphAfter = round(count($content)/2); //Enter number of paragraphs to display ad after.

    for ($i = 0; $i < count($content); $i++) {

        if ($i == $paragraphAfter) {
          $new_content .= $middle_ad;
        }

        $new_content.= $content[$i] . "</p>";
    }

    return $new_content;
}