<?php 

if( class_exists( 'WPSEO_Options' ) ){
	
    function apk_title() {
		global $post;
		$app_title = get_post_meta(get_the_ID(), 'wp_title_GP', true);
		return $app_title;
	}
	 
	
    function apk_version() {
		global $post;
		$app_version = get_post_meta(get_the_ID(), 'wp_version_GP', true);
		return $app_version;
	}
	
    //function apk_version_web() {
	//	global $post;
	//	$app_version_web = get_post_meta(get_the_ID(), 'wp_version', true);
	//	return $app_version_web;
	//}
	
    function apk_mod() {
		global $post;
		$app_mod = get_post_meta(get_the_ID(), 'wp_mods', true);
		return $app_mod;
	}
	
	function register_custom_yoast_variables() {
		wpseo_register_var_replacement( '%%app_title%%', 'apk_title', 'advanced' );
		wpseo_register_var_replacement( '%%app_version%%', 'apk_version', 'advanced' );
		//wpseo_register_var_replacement( '%%app_version_source%%', 'apk_version_web', 'advanced' );
		wpseo_register_var_replacement( '%%app_mod%%', 'apk_mod', 'advanced' );
	}

	add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');
}

if (class_exists('RankMath')) {
	
	add_action( 'rank_math/vars/register_extra_replacements', function(){
		rank_math_register_var_replacement(
			'app_title',
			[
				'name'        => esc_html__( 'App Title', THEMES_NAMES ),
				'description' => esc_html__( 'Display App Title.', THEMES_NAMES ),
				'variable'    => 'app_title',
				'example'     => titles_callback(),
			],
			'titles_callback'
		); 
	});
	
	add_action( 'rank_math/vars/register_extra_replacements', function(){
		rank_math_register_var_replacement(
			'app_version',
			[
				'name'        => esc_html__( 'App Version', THEMES_NAMES ),
				'description' => esc_html__( 'Display App version.', THEMES_NAMES ),
				'variable'    => 'app_version',
				'example'     => version_callback(),
			],
			'version_callback'
		); 
	});
	
	//add_action( 'rank_math/vars/register_extra_replacements', function(){
	//	rank_math_register_var_replacement(
	//		'app_version_sources',
	//		[
	//			'name'        => esc_html__( 'App Version Source', THEMES_NAMES ),
	//			'description' => esc_html__( 'Display App version Source.', THEMES_NAMES ),
	//			'variable'    => 'app_version_sources',
	//			'example'     => version_sources_callback(),
	//		],
	//		'version_sources_callback'
	//	); 
	//});
	
	add_action( 'rank_math/vars/register_extra_replacements', function(){
		rank_math_register_var_replacement(
			'app_mod',
			[
				'name'        => esc_html__( 'App Mod', THEMES_NAMES ),
				'description' => esc_html__( 'Display App Mod.', THEMES_NAMES ),
				'variable'    => 'app_mod',
				'example'     => mods_callback(),
			],
			'mods_callback'
		); 
	});
	
    function titles_callback(){
        $app_title = get_post_meta(get_the_ID(), 'wp_title_GP', true);
		if(!empty($app_title)) {
			return $app_title;
		} else {
			return '[app_title]';
		}
    }
	
    function version_callback(){
        $app_version = get_post_meta(get_the_ID(), 'wp_version_GP', true);
		if(!empty($app_version)) {
			return $app_version;
		} else {
			return '[app_version]';
		}
    }
	
    //function version_sources_callback(){
    //    $app_version_sources = get_post_meta(get_the_ID(), 'wp_version', true);
	//	if(!empty($app_version_sources)) {
	//		return $app_version_sources;
	//	} else {
	//		return '[app_version_sources]';
	//	}
    //}
	
    function mods_callback(){
        $app_mod = get_post_meta(get_the_ID(), 'wp_mods', true);
		if(!empty($app_mod)) {
			return $app_mod;
		} else {
			return 'mods';
		}
    }
	
}

function download_page_noindex() {
	global $wp_query, $opt_themes;
	$noindex    = "\n<!--[ Meta Robots for Download Page ]-->\n<meta name='robots' content='".$opt_themes['robots']."' />\n"; 
	if ( isset( $wp_query->query_vars['download'] ) ) {			 
		echo $noindex;
	}
}
add_action( 'wp_head', 'download_page_noindex', 1); 

function report_page_noindex() {
	global $wp_query, $opt_themes;
	$noindex    = "\n<!--[ Meta Robots for Download Page ]-->\n<meta name='robots' content='".$opt_themes['robots']."' />\n"; 
	if ( isset( $wp_query->query_vars['report'] ) ) {			 
		echo $noindex;
	}
}
add_action( 'wp_head', 'report_page_noindex', 1); 

function file_page_noindex() {
	global $wp_query, $opt_themes;
	$noindex    = "\n<!--[ Meta Robots for file Page ]-->\n<meta name='robots' content='".$opt_themes['robots']."' />\n"; 
	if ( isset( $wp_query->query_vars['file'] ) ) {			 
		echo $noindex;
	}
}
add_action( 'wp_head', 'file_page_noindex',1); 


function auto_seo() {

    global $post, $opt_themes;
 

    // Pagination aman
    $paged = max( 1, get_query_var('paged') );

    $blogname   = get_option('blogname');
    $siteurls   = get_option('siteurl');
    $blogdesc   = get_option('blogdescription');
    $sitelangs  = get_bloginfo('language');
    $no_images  = ! empty($opt_themes['img_json_seo']['url']) ? $opt_themes['img_json_seo']['url'] : '';

    /* ===============================
     * Theme Info
     * =============================== */
    echo "\n<!--[ Theme Designer ]-->\n";
    echo '<meta name="designer" content="'.esc_attr(EXTHEMES_AUTHOR).'">'."\n";
    echo '<meta name="themes" content="'.esc_attr(THEMES_NAMES).'">'."\n";
    echo '<meta name="version" content="'.esc_attr(VERSION).'">'."\n";
    echo "<!--[ end Theme Designer ]-->\n\n";

    /* ===============================
     * Title
     * =============================== */
    if ( get_post_meta( get_the_ID(), 'wp_GP_ID', true ) ) {
        $the_title = ucwords( get_post_meta( get_the_ID(), 'wp_title_GP', true ) );
    } else {
        $the_title = get_the_title();
    }

    /* ===============================
     * Description
     * =============================== */
    if ( ! empty( $post->post_content ) ) {
        $the_content = wp_strip_all_tags( $post->post_content );
        $the_content = preg_replace( '/\s+/', ' ', $the_content );
        $the_content = mb_substr( trim($the_content), 0, 160, 'UTF-8' );
    } else {
        $the_content = $blogdesc;
    }

    /* ===============================
     * Category & Tags
     * =============================== */
    $the_category = '';
    $the_tags     = '';

    $categories = get_the_category( get_the_ID() );
    if ( ! empty($categories) ) {
        $cat_name = wp_list_pluck( $categories, 'name' );
        $the_category = implode(', ', $cat_name);
    }

    $tags = get_the_tags( get_the_ID() );
    if ( ! empty($tags) ) {
        $tag_name = wp_list_pluck( $tags, 'name' );
        $tag_list = implode(', ', $tag_name);
        $the_tags = $the_category ? $the_category . ', ' . $tag_list : $tag_list;
    }

    /* ===============================
     * Thumbnail
     * =============================== */
    if ( has_post_thumbnail() ) {
        $thumb_id  = get_post_thumbnail_id( get_the_ID() );
        $thumb_url = wp_get_attachment_image_src( $thumb_id, 'full' );
        $the_thumbnail = $thumb_url[0];
    } else {
        $the_thumbnail = $no_images;
    }

    /* ===============================
     * Author & Date
     * =============================== */
    $author_id   = get_post_field( 'post_author', $post );
    $author_name = get_the_author_meta( 'display_name', $author_id );
    $authorurl   = get_author_posts_url( $author_id );

    // Ganti mysql2date (deprecated style)
    $datePublished = get_post_time( DATE_W3C, true, $post );
    $dateModified  = get_post_modified_time( DATE_W3C, true, $post );

    $the_permalink = get_permalink();

	$image_link			= get_post_meta( get_the_ID(), 'wp_images_GP', true);
	$gallery_data		= get_post_meta( get_the_ID(), 'gallery_data', true );
    /* ===============================
     * Canonical
     * =============================== */
    echo '<link rel="canonical" href="'.esc_url($the_permalink).'">'."\n";

    /* ===============================
     * Pagination SEO
     * =============================== */
    if ( get_previous_posts_link() ) {
        echo '<link rel="prev" href="'.esc_url( get_pagenum_link( $paged - 1 ) ).'">'."\n";
    }

    if ( get_next_posts_link() ) {
        echo '<link rel="next" href="'.esc_url( get_pagenum_link( $paged + 1 ) ).'">'."\n";
    }

    /* ===============================
     * Meta SEO
     * =============================== */
    if ( ( is_home() || is_front_page() ) && ! empty($opt_themes['seo_meta_tag']) ) {

        echo "\n<!--[ ".esc_html(THEMES_NAMES)." v.".esc_html(VERSION)." SEO Meta start ]-->\n";

        echo '<meta name="title" content="'.esc_attr($the_title).'">'."\n";
        echo '<meta name="description" content="'.esc_attr($the_content).'">'."\n";

        if ( ! empty($the_tags) ) {
            echo '<meta name="keywords" content="'.esc_attr($the_tags).'">'."\n";
        }

        echo "<!--[ SEO Meta end ]-->\n";
    }
	
	/* ==========================================================
	 * SEO META CONTROLLER
	 * ========================================================== */

	if ( ( is_home() || is_front_page() ) && ! empty($opt_themes['seo_meta_tag']) ) {

		/* ===============================
		 * HOME / FRONT PAGE SEO
		 * =============================== */

		// Meta description homepage
		echo "<!--[ Description and Keyword ]-->\n";
		echo '<meta name="description" content="'.esc_attr(
			get_option('blogname').' '.get_option('blogdescription')
		).'">'."\n";

		// Ambil 4 judul post terbaru untuk meta keywords
		$custom_query = new WP_Query( array(
			'posts_per_page' => 4,
			'no_found_rows'  => true,
			'post_status'   => 'publish'
		) );

		if ( $custom_query->have_posts() ) {
			$keywords = array();
			while ( $custom_query->have_posts() ) {
				$custom_query->the_post();
				$keywords[] = get_the_title();
			}
			echo '<meta name="keywords" content="'.esc_attr( implode(', ', $keywords) ).'">'."\n";
		}
		wp_reset_postdata();

		echo "<!--[ End Description and Keyword ]-->\n\n";

		/* Robots directive */
		echo "<!--[ Theme Robots Search ]-->\n";
		echo '<meta name="robots" content="index,follow,max-snippet:-1,max-video-preview:-1,max-image-preview:large">'."\n";
		echo '<meta name="googlebot" content="index,follow">'."\n";
		echo '<meta name="googlebot-news" content="snippet">'."\n";
		echo "<!--[ End Theme Robots Search ]-->\n\n";

		/* Open Graph for Facebook */
		echo "<!--[ Open Graph Facebook ]-->\n";
		echo '<meta property="og:type" content="website">'."\n";
		echo '<meta property="og:site_name" content="'.esc_attr(get_option('blogname')).'">'."\n";
		echo '<meta property="og:url" content="'.esc_url(home_url('/')).'">'."\n";
		echo '<meta property="og:title" content="'.esc_attr(get_option('blogname').' '.get_option('blogdescription')).'">'."\n";
		echo '<meta property="og:description" content="'.esc_attr(get_option('blogname').' '.get_option('blogdescription')).'">'."\n";
		echo '<meta property="og:image" content="'.esc_url($opt_themes['img_json_seo']['url']).'">'."\n";
		echo '<meta property="og:locale" content="'.esc_attr(get_bloginfo('language')).'">'."\n";
		echo "<!--[ End Graph Facebook ]-->\n\n";

		/* Twitter Card */
		echo "<!--[ Open Graph Twitter ]-->\n";
		echo '<meta name="twitter:card" content="summary_large_image">'."\n";
		echo '<meta name="twitter:url" content="'.esc_url(home_url('/')).'">'."\n";
		echo '<meta name="twitter:title" content="'.esc_attr(get_option('blogname').' '.get_option('blogdescription')).'">'."\n";
		echo '<meta name="twitter:description" content="'.esc_attr(get_option('blogname').' '.get_option('blogdescription')).'">'."\n";
		echo '<meta name="twitter:image" content="'.esc_url($opt_themes['img_json_seo']['url']).'">'."\n";
		echo "<!--[ End Graph Twitter ]-->\n";

	}

	/* ========================================================== */

	elseif (
		is_single()
		&& get_post_type() === 'post'
		&& empty($wp_query->query_vars['download'])
		&& empty($wp_query->query_vars['file'])
		&& ! empty($opt_themes['seo_meta_tag'])
	) {

		/* ===============================
		 * SINGLE POST SEO
		 * =============================== */

		echo "<!--[ Description and Keyword ]-->\n";
		echo '<meta name="description" content="'.esc_attr(wp_strip_all_tags($the_content)).'">'."\n";

		if ( ! empty($the_tags) ) {
			echo '<meta name="keywords" content="'.esc_attr($the_tags).'">'."\n";
		}

		echo "<!--[ End Description and Keyword ]-->\n\n";

		/* Robots */
		echo "<!--[ Theme Robots Search ]-->\n";
		echo '<meta name="robots" content="index,follow,max-snippet:-1,max-video-preview:-1,max-image-preview:large">'."\n";
		echo '<meta name="googlebot" content="index,follow">'."\n";
		echo '<meta name="googlebot-news" content="snippet">'."\n";
		echo "<!--[ End Theme Robots Search ]-->\n\n";

		/* Open Graph Article */
		echo "<!--[ Open Graph Facebook ]-->\n";
		echo '<meta property="og:type" content="article">'."\n";
		echo '<meta property="og:locale" content="'.esc_attr(get_bloginfo('language')).'">'."\n";
		echo '<meta property="og:title" content="'.esc_attr($the_title).'">'."\n";
		echo '<meta property="og:description" content="'.esc_attr(wp_strip_all_tags($the_content)).'">'."\n";
		echo '<meta property="og:image" content="'.esc_url($the_thumbnail).'">'."\n";
		echo '<meta property="og:image:alt" content="'.esc_attr($the_title).'">'."\n";
		echo '<meta property="og:url" content="'.esc_url($the_permalink).'">'."\n";
		echo '<meta property="og:site_name" content="'.esc_attr(get_option('blogname')).'">'."\n";
		echo '<meta property="article:author" content="'.esc_url($authorurl).'">'."\n";
		echo '<meta property="article:published_time" content="'.esc_attr($datePublished).'">'."\n";
		echo '<meta property="article:modified_time" content="'.esc_attr($dateModified).'">'."\n";
		echo '<meta property="og:updated_time" content="'.esc_attr($dateModified).'">'."\n";
		echo "<!--[ End Graph Facebook ]-->\n\n";

		/* Twitter */
		echo "<!--[ Open Graph Twitter ]-->\n";
		echo '<meta name="twitter:card" content="summary_large_image">'."\n";
		echo '<meta name="twitter:url" content="'.esc_url($the_permalink).'">'."\n";
		echo '<meta name="twitter:title" content="'.esc_attr($the_title).'">'."\n";
		echo '<meta name="twitter:description" content="'.esc_attr(wp_strip_all_tags($the_content)).'">'."\n";
		echo '<meta name="twitter:image" content="'.esc_url($the_thumbnail).'">'."\n";
		echo "<!--[ End Graph Twitter ]-->\n";

	}

	/* ========================================================== */

	elseif (
		is_page()
		|| is_search()
		|| is_archive()
		|| is_404()
		|| is_tag()
		|| is_author()
		|| is_attachment()
		|| ( is_single() && get_post_type() === 'blog' )
	) {
		// Jangan cetak SEO meta di halaman ini
		return false;
	}

		
	/**
	 * JSON-LD Schema untuk SEO
	 * Organization, Website, dan BlogPosting
	 */

	if ( ! empty( $opt_themes['json_seo_on'] ) ) :
		// ============================================================
		// Organization Schema
		// Digunakan untuk menandai identitas organisasi / brand
		// ============================================================
		$sameAs = array();
		if ( ! empty( $opt_themes['json_url'] ) && is_array( $opt_themes['json_url'] ) ) {
			foreach ( $opt_themes['json_url'] as $url ) {
				if ( ! empty( $url ) ) {
					$sameAs[] = esc_url( $url ); // pastikan URL aman
				}
			}
		}
		?>
		
<script type="application/ld+json">
<?php
echo wp_json_encode( [
			'@context' => 'https://schema.org',
			'@type'    => 'Organization',
			'url'      => esc_url( home_url( '/' ) ),
			'logo'     => esc_url( $opt_themes['img_json_seo']['url'] ?? '' ),
			'sameAs'   => $sameAs,
		], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
?>

</script>

		<?php
		// ============================================================
		// WebSite Schema
		// Menandai website secara umum dan mendukung SearchAction
		// ============================================================
		?>
		
<script type="application/ld+json">
<?php
echo wp_json_encode( [
			'@context' => 'https://schema.org',
			'@type'    => 'WebSite',
			'url'      => esc_url( home_url( '/' ) ),
			'name'     => get_option( 'blogname' ),
			'alternateName' => get_option( 'blogname' ),
			'potentialAction' => [
				'@type' => 'SearchAction',
				'target' => esc_url( home_url( '/?s={search_term_string}&max-results=10' ) ),
				'query-input' => 'required name=search_term_string',
			],
		], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
?>

</script>
	
	<?php
	endif; // End json_seo_on check

	// ============================================================
	// BlogPosting Schema (untuk single post)
	// ============================================================
	if (
		is_single() &&
		get_post_type() === 'post' &&
		empty( $wp_query->query_vars['download'] ) &&
		empty( $wp_query->query_vars['file'] ) &&
		! empty( $opt_themes['json_blogposting_on'] )
	) :

		// ============================================================
		// Thumbnail / image fallback
		// ============================================================
		if ( has_post_thumbnail() ) {
			$img = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
			$image_url = $img[0];
			$image_w   = $img[1];
			$image_h   = $img[2];
		} elseif ( $poster = get_post_meta( get_the_ID(), 'wp_poster_GP', true ) ) {
			$image_url = esc_url( $poster );
			$image_w   = 1200; // default width
			$image_h   = 630;  // default height
		} else {
			$image_url = get_template_directory_uri() . '/assets/img/no-image.png';
			$image_w   = 1200;
			$image_h   = 630;
		}

		// ============================================================
		// Headline & Description
		// Headline: judul post
		// Description: excerpt / content truncated 160 chars
		// ============================================================
		$headline = get_the_title();
		$description = mb_substr( wp_strip_all_tags( $the_content ?? '' ), 0, 160, 'UTF-8' );
		?>

<script type="application/ld+json">
<?php
echo wp_json_encode( [
			'@context' => 'https://schema.org',
			'@type'    => 'BlogPosting',
			'mainEntityOfPage' => [
				'@type' => 'WebPage',
				'@id'   => esc_url( get_permalink() ),
			],
			'headline'    => $headline,
			'description' => $description,
			'datePublished' => $datePublished,
			'dateModified'  => $dateModified,
			'image' => [
				'@type'  => 'ImageObject',
				'url'    => esc_url( $image_url ),
				'width'  => $image_w,
				'height' => $image_h,
			],
			'author' => [
				'@type' => 'Person',
				'name'  => $author_name,
				'url'   => esc_url( $authorurl ),
			],
			'publisher' => [
				'@type' => 'Organization',
				'name'  => get_option( 'blogname' ),
				'logo'  => [
					'@type' => 'ImageObject',
					'url'   => esc_url( $opt_themes['img_json_seo']['url'] ?? '' ),
					'width' => 600,
					'height'=> 60,
				],
			],
		], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
		?>

</script>

	<?php
	endif;
	 
	/**
	 * JSON-LD SoftwareApplication & WordPress SEO
	 * Menambahkan schema untuk aplikasi, rating, meta tags, RSS, canonical
	 */

	// ============================================================
	// Hanya untuk single post, tipe 'post', JSON SEO aktif,
	// dan memiliki meta 'wp_GP_ID'
	// ============================================================
	if (
		is_single() &&
		get_post_type() === 'post' &&
		empty( $wp_query->query_vars['download'] ) &&
		empty( $wp_query->query_vars['file'] ) &&
		! empty( $opt_themes['json_seo_on'] ) &&
		get_post_meta( get_the_ID(), 'wp_GP_ID', true )
	) :

		// ========================================================
		// Rating
		// ========================================================
		$total  = get_post_meta( get_the_ID(), RATING_TOTALS2, true );
		$count  = get_post_meta( get_the_ID(), RATING_COUNTS2, true ) ?: 0;
		$average = $count > 0 ? round( $total / $count, 1 ) : 0;

		$average2 = get_post_meta( get_the_ID(), 'wp_rated_GP', true ) ?: '4.5';
		$count2   = get_post_meta( get_the_ID(), 'wp_ratings_GP', true ) ?: mt_rand(559, 9999);

		// ========================================================
		// JSON-LD SoftwareApplication
		// ========================================================
		?>

<script type="application/ld+json">
<?php
		// Image utama
		if ( has_post_thumbnail() ) {
			$img = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
			$image_url = $img[0];
			$image_w   = $img[1];
			$image_h   = $img[2];
		} elseif ( $poster = get_post_meta( get_the_ID(), 'wp_poster_GP', true ) ) {
			$image_url = esc_url( $poster );
			$image_w   = 1200;
			$image_h   = 630;
		} else {
			$image_url = esc_url( $opt_themes['no_img']['url'] ?? '' );
			$image_w   = 1200;
			$image_h   = 630;
		}

		// Category pertama
		$categories = get_the_category();
		$first_category = ! empty( $categories ) ? $categories[0]->cat_name : '';

echo wp_json_encode( [
			'@context' => 'https://schema.org',
			'@type'    => 'SoftwareApplication',
			'name'     => get_post_meta( get_the_ID(), 'wp_title_GP', true ) ?: get_the_title(),
			'applicationCategory' => $first_category,
			'mainEntityOfPage' => [
				'@type' => 'WebPage',
				'@id'   => get_permalink(),
			],
			'datePublished' => $datePublished,
			'dateModified'  => $dateModified,
			'aggregateRating' => [
				'@type'       => 'AggregateRating',
				'ratingValue' => $average > 0 ? $average : $average2,
				'ratingCount' => $count > 0 ? $count : $count2,
				'worstRating' => 1,
				'bestRating'  => 5,
			],
			'author' => [
				'@type' => 'Person',
				'name'  => $author_name,
				'url'   => esc_url( $authorurl ),
			],
			'image' => [ $image_url ],
			'screenshot' => ! empty( $gallery_data['image_url'] ) ? $gallery_data['image_url'] : ( $image_link ?? [] ),
			'description' => $the_content,
			'operatingSystem' => 'android ' . ( get_post_meta( get_the_ID(), 'wp_requires_GP', true ) ?: '5.0' ),
			'softwareVersion' => trim( strip_tags( get_post_meta( get_the_ID(), 'wp_version_GP', true ) ) ),
			'publisher' => [
				'@type' => 'Organization',
				'name'  => get_post_meta( get_the_ID(), 'wp_developers_GP', true ),
				'logo'  => [
					'@type' => 'ImageObject',
					'url'   => esc_url( $opt_themes['img_json_seo']['url'] ?? '' ),
					'width' => $image_w,
					'height'=> $image_h,
				],
			],
			'headline' => get_post_meta( $post->ID, 'wp_desck_GP', true ) ? mb_substr( get_post_meta( $post->ID, 'wp_desck_GP', true ), 0, 120, 'utf8' ) : get_the_title(),
			'offers' => [
				'@type' => 'AggregateOffer',
				'price' => '0',
				'priceCurrency' => 'USD',
				'lowPrice' => '0',
			],
		], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
?>

</script>

	<?php
	endif;

	// ============================================================
	// RSS & Canonical Links
	// ============================================================
	?>
	<!-- RSS Feed -->
	<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />

	<!-- Canonical URL -->
	<?php if ( is_home() || is_front_page() ) : ?>
		<link rel="canonical" href="<?php echo esc_url( home_url('/') ); ?>" />
	<?php elseif ( is_single() || is_page() ) : ?>
		<link rel="canonical" href="<?php echo get_permalink(); ?>" />
	<?php elseif ( is_archive() ) : 
		global $wp;
		$current_url = home_url( $wp->request ) . '/';
	?>
		<link rel="canonical" href="<?php echo esc_url( $current_url ); ?>" />
	<?php endif; ?>

	<?php
	// ============================================================
	// SEO Meta Comment (Generator Info)
	// ============================================================
	if ( ! empty( $opt_themes['seo_meta_tag'] ) ) :
		echo '<!--[ '.THEMES_NAMES.' v.'.VERSION.' SEO Meta Keywords Generator for '.get_option("siteurl").' @'.date("Y").' ]-->'.PHP_EOL;
		echo '<!--[ 
	- '.get_option("siteurl").' using '.THEMES_NAMES.' v.'.VERSION.' 
	- Buy now on '.EXTHEMES_ITEMS_URL.'
	- Designer and Developer: '.EXTHEMES_AUTHOR.'
	- More Premium Themes Visit: '.EXTHEMES_API_URL.'
	]-->'.PHP_EOL;
	endif;

}


function auto_seo1234(){
//ini_set('display_errors', ERRORS); 
global $post, $paged, $opt_themes, $wpdb, $query, $wp_query;

$blogname			= get_option("blogname");
$siteurls			= get_option("siteurl");
$blogemail			= get_option("admin_email");
$blogdesc			= get_option("blogdescription");
$sitelangs			= get_bloginfo("language");
$no_images			= $opt_themes['img_json_seo']['url'];

echo '<!--[ Theme Designer ]-->'.PHP_EOL;
echo '<meta name="designer" content="'.EXTHEMES_AUTHOR.'" />'.PHP_EOL;
echo '<meta name="themes" content="'.THEMES_NAMES.'" />'.PHP_EOL;
echo '<meta name="version" content="'.VERSION.'" />'.PHP_EOL; 
echo '<!--[ end Theme Designer ]-->'.PHP_EOL.PHP_EOL;

if(get_post_meta( get_the_ID(), 'wp_GP_ID', true )) {  
$the_title			= ucwords(get_post_meta( get_the_ID(), 'wp_title_GP', true ));
} else { 
$the_title			= get_the_title();
}

if(!empty(get_post()->post_content)){
$the_content		= trim(strip_tags( get_post()->post_content) );
$the_content		= str_replace( array("\n", "\r", "\t"), ' ', $the_content );
$the_content		= str_replace( array( "/<[^>]*>/", "\\n", "\\r", "\\t" ), '', $the_content);
$the_content		= mb_substr( $the_content, 0, 160, 'utf8' );
} else {
$the_content		= '';
}

if(get_the_category(get_the_ID())){
	
$catlist			= get_the_category(get_the_ID());
$cat_name			= array();
foreach ($catlist as $category){
    $cat_name[] 	= $category->cat_name;
}
$the_category		= implode(', ', $cat_name);
}

if(get_the_tags(get_the_ID())){
	
$taglist			= get_the_tags(get_the_ID());
$tag_name			= array();
foreach ($taglist as $tags){
    $tag_name[] 	= $tags->name;
}
$tag_list 			= implode(', ', $tag_name);
if(!empty($the_category)){
$the_tags			= $the_category.', '.$tag_list;
} else {
$the_tags			= '';
}

}

if (has_post_thumbnail()) { 
$urlimagesnya		= wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'full' );
$thumb_id			= get_post_thumbnail_id( get_the_ID() );
//if (get_the_post_thumbnail( get_the_ID() )) { 
$thumb_url			= wp_get_attachment_image_src( $thumb_id, 'full', true );
	$the_thumbnail	= $thumb_url[0];
} else {
	$the_thumbnail	= $no_images;
} 
//print_r($thumb_url);

$authorurl			= get_author_posts_url( $post->post_author );
$author_id			= get_post_field( 'post_author', $post );
$author_name		= get_the_author_meta('user_nicename', $author_id);
$datePublished		= mysql2date( DATE_W3C, $post->post_date_gmt, false );
$dateModified		= mysql2date( DATE_W3C, $post->post_modified_gmt, false );
$the_permalink		= get_the_permalink();  

$image_link			= get_post_meta( get_the_ID(), 'wp_images_GP', true);
$gallery_data		= get_post_meta( get_the_ID(), 'gallery_data', true );

 
if ( get_previous_posts_link() ) {
    echo '<link rel="prev" href="'.get_pagenum_link( $paged - 1 ).'" />'. "\n";
}

if ( get_next_posts_link() ) {
    echo '<link rel="next" href="'.get_pagenum_link( $paged + 1 ).'" />'. "\n";
}

if($opt_themes['seo_meta_tag']){ 
	echo PHP_EOL .'<!--[ '.THEMES_NAMES.' v.'.VERSION.' SEO Meta Keywords Generator for '.get_option("siteurl").' @'.date("Y").', Buy on '.EXTHEMES_ITEMS_URL.' start ]-->'.PHP_EOL.PHP_EOL;
}

if (is_home() || is_front_page() && $opt_themes['seo_meta_tag'] ) { 
	
echo '<!--[ Description and Keyword ]-->'.PHP_EOL;
echo '<meta name="description" content="'.get_option("blogname").' '.get_option("blogdescription").'" />'.PHP_EOL;
//echo '<meta name="keywords" content="'.current(explode(',', get_the_title())).'" />'.PHP_EOL.PHP_EOL;
$custom_query = new WP_Query( array( 'posts_per_page' => '4' ) );
if ( $custom_query->have_posts() ) : 
echo '<meta name="keywords" content="';
while ( $custom_query->have_posts() ) : $custom_query->the_post(); 
echo get_the_title().', ';
endwhile;  
echo '" />'.PHP_EOL;
endif; 
echo '<!--[ End Description and Keyword ]-->'.PHP_EOL.PHP_EOL;

echo '<!--[ Theme Robots Search ]-->'.PHP_EOL;
echo '<meta name="robots" content="max-snippet:-1, max-video-preview:-1, max-image-preview:large" />'.PHP_EOL;
echo '<meta name="googlebot" content="index" />'.PHP_EOL;
echo '<meta name="googlebot-news" content="snippet" />'.PHP_EOL;
echo '<!--[ End Theme Robots Search ]-->'.PHP_EOL.PHP_EOL;

echo '<!--[ Open Graph Facebook ]-->'.PHP_EOL;
echo '<meta property="og:type" content="website" />'.PHP_EOL;
echo '<meta property="og:site_name" content="'.get_option("blogname").'" />'.PHP_EOL;
echo '<meta property="og:url" content="'.home_url( '/' ).'" />'.PHP_EOL;
echo '<meta property="og:title" content="'.trim(get_option("blogname")).' '.trim(get_option("blogdescription")).'" />'.PHP_EOL;
echo '<meta property="og:description" content="'.trim(get_option("blogname")).' '.trim(get_option("blogdescription")).'" />'.PHP_EOL;
echo '<meta property="og:image" content="'.$opt_themes['img_json_seo']['url'].'" />'.PHP_EOL;
echo '<meta property="og:locale" content="'.get_bloginfo("language").'" />'.PHP_EOL;
echo '<!--[ End Graph Facebook ]-->'.PHP_EOL.PHP_EOL;

echo '<!--[ Open Graph Twitter ]-->'.PHP_EOL;
echo '<meta name="twitter:card" content="summary" />'.PHP_EOL;
echo '<meta name="twitter:url" content="'.home_url( '/' ).'" />'.PHP_EOL;
echo '<meta name="twitter:site" content="'.home_url( '/' ).'" />'.PHP_EOL; 
echo '<meta name="twitter:title" content="'.trim(get_option("blogname")).' '.trim(get_option("blogdescription")).'" />'.PHP_EOL;
echo '<meta name="twitter:description" content="'.trim(get_option("blogname")).' '.trim(get_option("blogdescription")).'" />'.PHP_EOL;
echo '<meta name="twitter:image" content="'.$opt_themes['img_json_seo']['url'].'" />'.PHP_EOL;
echo '<!--[ End Graph Twitter ]-->'.PHP_EOL;
 

} elseif (is_single() && 'post' == get_post_type() && !isset( $wp_query->query_vars['download'] ) && !isset( $wp_query->query_vars['file'] ) && $opt_themes['seo_meta_tag'] ) {
 
echo '<!--[ Description and Keyword ]-->'.PHP_EOL;
echo "<meta name='description' content='".strip_tags($the_content)."' />".PHP_EOL;
echo '<meta name="keywords" content="'.$the_tags.'" />'.PHP_EOL;
echo '<!--[ End Description and Keyword ]-->'.PHP_EOL.PHP_EOL;

echo '<!--[ Theme Robots Search ]-->'.PHP_EOL;
echo '<meta name="googlebot" content="index">'.PHP_EOL;
echo '<meta name="googlebot-news" content="snippet">'.PHP_EOL;
echo '<meta name="robots" content="max-snippet:-1, max-video-preview:-1, max-image-preview:large"/>'.PHP_EOL;
echo '<!--[ End Theme Robots Search ]-->'.PHP_EOL.PHP_EOL;

echo '<!--[ Open Graph Facebook ]-->'.PHP_EOL;
echo '<meta property="og:type" content="article" />'.PHP_EOL;
echo '<meta property="og:locale" content="'.get_bloginfo("language").'" />'.PHP_EOL;
echo '<meta property="og:locale:alternate" content="'.get_bloginfo("language").'" />'.PHP_EOL;
echo '<meta property="og:title" content="'.$the_title.'" />'.PHP_EOL;
echo '<meta property="og:image:alt" content="'.$the_title.'" />'.PHP_EOL;
echo '<meta property="og:site_name" content="'.get_option("blogname").'" />'.PHP_EOL;
echo '<meta property="og:image" content="'.$the_thumbnail.'" />'.PHP_EOL;
echo "<meta property='og:description' content='".strip_tags($the_content)."' />".PHP_EOL;
echo '<meta property="article:tag" content="'.$the_tags.'" />'.PHP_EOL;
echo '<meta property="og:url" content="'.$the_permalink.'" />'.PHP_EOL;
echo '<meta property="article:author" content="'.$author_name.'" />'.PHP_EOL;
echo '<meta property="article:author" content="'.$authorurl.'" />'.PHP_EOL;
echo '<meta property="article:publisher" content="'.$authorurl.'" />'.PHP_EOL;
echo '<meta property="article:published_time" content="'.$datePublished.'" />'.PHP_EOL;
echo '<meta property="article:modified_time" content="'.$dateModified.'" />'.PHP_EOL;
echo '<meta property="og:updated_time" content="'.$dateModified.'" />'.PHP_EOL;
echo '<meta property="og:image:secure_url" content="'.$the_thumbnail.'" />'.PHP_EOL;
echo '<!--[ End Graph Facebook ]-->'.PHP_EOL.PHP_EOL;

echo '<!--[ Open Graph Twitter ]-->'.PHP_EOL;
echo '<meta name="twitter:card" content="summary" />'.PHP_EOL;
echo '<meta name="twitter:site" content="'.$the_permalink.'" />'.PHP_EOL;
echo '<meta name="twitter:url" content="'.$the_permalink.'" />'.PHP_EOL;
echo '<meta name="twitter:domain" content="'.$the_permalink.'" />'.PHP_EOL;
echo '<meta name="twitter:title" content="'.$the_title.'" />'.PHP_EOL;
echo "<meta name='twitter:description' content='".strip_tags($the_content)."' />".PHP_EOL;
echo '<meta name="twitter:image" content="'.$the_thumbnail.'" />'.PHP_EOL;
echo '<!--[ End Graph Twitter ]-->'.PHP_EOL;
 
} elseif ( is_page() || is_search() || is_archive() || is_404() || is_tag() || is_author() || is_404() || is_attachment() || is_single() && 'blog' == get_post_type() ) {
echo "";
} 

if($opt_themes['json_seo_on']){ 
?>

<!--[ Theme Json Schema Organization ]-->
<script type="application/ld+json">
{
	"@context": "https://schema.org",
	"@type": "Organization",
	"url": "<?php echo esc_url( home_url( '/' ) ); ?>",
	"logo": "<?php echo $opt_themes['img_json_seo']['url']; ?>",
	"sameAs": [<?php foreach ( (array) $opt_themes['json_url'] as $key => $val ) { ?>"<?php echo $val; ?>",<?php } ?> ""]
}
</script>

<!--[ Theme Json Schema WebSite ]-->
<script type='application/ld+json'>
{
	"@context": "https://schema.org",
	"@type": "WebSite",
	"url": "<?php echo esc_url( home_url( '/' ) ); ?>",
	"name": "<?php echo get_option("blogname"); ?>",
	"alternateName": "<?php echo get_option("blogname"); ?>",
	"potentialAction": {
		"@type": "SearchAction",
		"target": "<?php echo esc_url( home_url( '/' ) ); ?>?s={search_term_string}&max-results=10",
		"query-input": "required name=search_term_string"
	}
}
</script>

<?php } if (is_single() && 'post' == get_post_type() && !isset( $wp_query->query_vars['download'] ) && !isset( $wp_query->query_vars['file'] ) && $opt_themes['json_seo_on'] ) { ?>
<!--[ Theme Json Schema BlogPosting ]-->
<script type='application/ld+json'>
{
	"@context": "http://schema.org",
	"@type": "BlogPosting",
	"mainEntityOfPage": {
		"@type": "WebPage",
		"@id": "<?php echo $the_permalink; ?>"
	},
	"headline": "<?php if( !empty( get_post_meta( $post->ID, 'wp_desck_GP', true ))){ echo mb_substr( get_post_meta( $post->ID, 'wp_desck_GP', true ), 0, 120, 'utf8' ); } else { get_the_title(); } ?>",
	"description": '<?php echo $the_content; ?>',
	"datePublished": "<?php echo $datePublished; ?>",
	"dateModified": "<?php echo $dateModified; ?>",
	"image": {
		"@type": "ImageObject",
		"url": "<?php if (get_the_post_thumbnail( get_the_ID() )) { echo wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' )[0]; } elseif(get_post_meta( get_the_ID(), 'wp_poster_GP', true )) { echo get_post_meta( get_the_ID(), 'wp_poster_GP', true ); } else { echo get_template_directory_uri().'/assets/img/no-image.png'; } ?>",
		"height": <?php echo $thumb_url[2]; ?>,
		"width": <?php echo $thumb_url[1]; ?>
	
	},
	"publisher": {
		"@type": "Organization",
		"name": "<?php echo get_post_meta( get_the_ID(), 'wp_developers_GP', true ); ?>",
		"logo": {
			"@type": "ImageObject",
			"url": "<?php echo $opt_themes['img_json_seo']['url']; ?>",
			"width": <?php echo $thumb_url[1]; ?>, 
			"height": <?php echo $thumb_url[2]; ?> 
		}
	},
	"author": {
		"@type": "Person",
		"name": "<?php echo $author_name; ?>",
		"url": "<?php echo $authorurl; ?>"
	}
}
</script>
 
<?php } ?>

<?php if( is_single() && 'post' == get_post_type() && !isset( $wp_query->query_vars['download'] ) && !isset( $wp_query->query_vars['file'] ) && $opt_themes['json_seo_on'] && get_post_meta( get_the_ID(), 'wp_GP_ID', true ) ) { ?>

		<?php 
			
		$total_rating = floatval(get_post_meta(get_the_ID(), 'rating_total_value', true));
		$vote_count   = intval(get_post_meta(get_the_ID(), 'rating_total_votes', true));
		$average      = $vote_count > 0 ? round($total_rating / $vote_count, 2) : 0;
		
		//$total 		= get_post_meta(get_the_ID(), 'rating_total_value', true);	
		//$count 		= get_post_meta( get_the_ID(), 'rating_total_votes', true) > 0 ? get_post_meta( get_the_ID(), 'rating_total_value', true) : 0;
		//$average 	= $count > 0 ? round($total / $count, 1) : 0;
		
		if(get_post_meta( get_the_ID(), 'wp_rated_GP', true )) {
		$average2 	= get_post_meta( get_the_ID(), 'wp_rated_GP', true );
		} else {
		$average2 	= '4.5';
		}
		if(get_post_meta( get_the_ID(), 'wp_ratings_GP', true )) {
		$count2 	= get_post_meta( get_the_ID(), 'wp_ratings_GP', true );
		} else {
		$count2 	= mt_rand(559, 9999); 
		}
		
		?>	
		
<!--[ Theme Json Schema SoftwareApplication ]-->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
		"@type": "SoftwareApplication",
		"@context": "https://schema.org/",
		"name": "<?php if(get_post_meta( get_the_ID(), 'wp_title_GP', true)){ echo get_post_meta( get_the_ID(), 'wp_title_GP', true); } else { the_title(); } ?>",
		"applicationCategory": "<?php $ix = 0; foreach((get_the_category()) as $cat) { echo $cat->cat_name; if (++$ix == 1) break; } ?>",
		"mainEntityOfPage": {
			"@type": "WebPage",
			"@id": "<?php the_permalink(); ?>"
		},
		"datePublished": "<?php echo $datePublished; ?>",
		"dateModified": "<?php echo $dateModified; ?>",		
		"aggregateRating": {
			"@type": "AggregateRating",
			"ratingValue": "<?php echo $average > 0 ? $average : $average2; ?>",
			"ratingCount": "<?php echo $vote_count > 0 ? $vote_count : $count2; ?>",
			"worstRating": 1,
			"bestRating": 5
		},
		"author": {
			"@type": "Person",
			"name": "<?php echo $author_name; ?>",
			"url": "<?php echo $authorurl; ?>"
		},
		"image": [
			"<?php if (get_the_post_thumbnail( get_the_ID() )) { echo wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' )[0]; } elseif(get_post_meta( get_the_ID(), 'wp_poster_GP', true )) { echo get_post_meta( get_the_ID(), 'wp_poster_GP', true ); } else { echo $opt_themes['no_img']['url']; } ?>"
		],
<?php if ($gallery_data) { ?>
		"screenshot": [
<?php for( $i = 0; $i < count( $gallery_data['image_url'] ); $i++ ) {
?>
					"<?php echo $gallery_data['image_url'][$i]; ?>",
<?php } ?>
					""
		],
<?php } elseif($image_link){ ?>
		"screenshot": [
<?php 
$ni		= 0; 
foreach($image_link as $elemento) {
if ( $ni <= $image_link ) {
$thumbnails_gp  = $image_link[$ni]; 
?>
					"<?php echo $thumbnails_gp; ?>",
<?php } $ni++; } ?> 
					""
		],
<?php } ?>
		"description": '<?php echo $the_content; ?>',
		"operatingSystem": "<?php _e('android', TEXT_DOMAIN); ?> <?php if(get_post_meta( get_the_ID(), 'wp_requires_GP', true )){ echo get_post_meta( get_the_ID(), 'wp_requires_GP', true ); } else { echo '5.0';} ?>",
		"softwareVersion": "<?php echo trim(strip_tags(get_post_meta( get_the_ID(), 'wp_version', true ))); ?>",
		"publisher": {
			"@type": "Organization",
			"name": "<?php echo get_post_meta( get_the_ID(), 'wp_developers_GP', true ); ?>"
		},
		"headline": "<?php if( !empty( get_post_meta( $post->ID, 'wp_desck_GP', true ))){ echo mb_substr( get_post_meta( $post->ID, 'wp_desck_GP', true ), 0, 120, 'utf8' ); } else { get_the_title(); } ?>",
		"offers": {
			"@type": "AggregateOffer",
			"Price": "0",
			"priceCurrency": "USD",
			"lowPrice": "0"
		}
    }
  ]
}
 
</script> 

<?php } ?>


<!--[ Theme Wordpress Rss ]-->
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />
<!--[ <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />  ]--> 
<?php if (is_home() || is_front_page()) {?>
<!--[ <link rel="canonical" href="<?php echo esc_url( home_url( '/' ) ); ?>" /> ]-->
<?php } else { if (is_single() || is_page() ) { ?>
<!--[ <link rel="canonical" href="<?php echo get_permalink(); ?>" /> ]-->
<?php } } if (is_archive()){
global $wp;
$current_url = home_url( $wp->request ) . '/';
?>
<!--[ <link rel="canonical" href="<?php echo $current_url; ?>" /> ]-->
<?php } 
 
if($opt_themes['seo_meta_tag']){
//echo PHP_EOL .'<meta http-equiv="copyright @'.date("Y").' '.$blogemail.'" content="' . strip_tags($blogname) . ' - '.get_option("siteurl").' @'.date("Y").'">'.PHP_EOL;
	echo '<!--[ '.THEMES_NAMES.' v.'.VERSION.' SEO Meta Keywords Generator for '.get_option("siteurl").' @'.date("Y").', Buy on '.EXTHEMES_ITEMS_URL.' end ]-->'.PHP_EOL;
}

echo '<!--[ '.PHP_EOL.'- '.get_option("siteurl").' using '.THEMES_NAMES.' v.'.VERSION.' '.PHP_EOL.'- Buy now on '.EXTHEMES_ITEMS_URL.' '.PHP_EOL.'- Designer and Developer by '.EXTHEMES_AUTHOR.' '.PHP_EOL.'- More Premium Themes Visit Now On '.EXTHEMES_API_URL.' '.PHP_EOL.']-->'.PHP_EOL;

}
add_action( 'wp_head', 'auto_seo', 3); 


function get_breadcrumb_json_ld() {
	$home_url			= get_home_url();
	$post_categories	= get_the_category();
	$first_category		= $post_categories[0];
	$category_url		= get_category_link($first_category->term_id);
  
	$cat				= get_the_category(); 
	$catID				= $cat[0]->cat_ID;
	$parents			= get_ancestors( $catID, 'category' );
	$parents			= array_reverse( $parents );
	$parents[] 			= $catID;
	$position			= 2;
		
	$post_title 	= get_the_title();
	$post_url 		= get_the_permalink();

	$json_ld 	= array(
    '@context' 	=> 'https://schema.org',
    '@type' 	=> 'BreadcrumbList',
	'name' 		=> 'Breadcrumb',
    'itemListElement' => array(
		array(
			'@type' 	=> 'ListItem',
			'position' 	=> 1,
			'name' 		=> 'Home',
			'item' 		=> array(
				'@id'	=> $home_url,          
			),
		),
 
		array(
			'@type' 	=> 'ListItem',
			'position' 	=> 2,
			'name' 		=> $first_category->name,
			'item' 		=> array(
				'@id'	=> $category_url,          
			),
		),
		
		array(
			'@type' 	=> 'ListItem',
			'position' 	=> 3,
			'name' 		=> get_the_title(),
			'item' 		=> array(
				'@id' 	=> get_the_permalink(),          
			),
		),
		
    ),
  );

  //return json_encode($json_ld, JSON_UNESCAPED_SLASHES);
  return json_encode($json_ld);
}

//Output JSON LD to the footer
function output_breadcrumb_json_ld() {
	global $opt_themes;
	if (is_single() && 'post' == get_post_type() && $opt_themes['breadcrumb_seo_on'] ) { 

    $json_ld = get_breadcrumb_json_ld();
echo PHP_EOL.'<!--[ Theme Json Schema breadcrumb ]-->
<script type="application/ld+json">
' . $json_ld . '
</script>
<!--[ End Theme Json Schema breadcrumb ]-->'.PHP_EOL.PHP_EOL;

	}
}
//add_action('wp_head', 'output_breadcrumb_json_ld', 10, 1); 

