<?php
/**
 * Kadence Berita Teknologi — child theme functions
 *
 * @package kadence-beritateknologi
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/* -------------------------------------------------------------------------
 * 1. Enqueue parent + child styles + Google Fonts
 * ---------------------------------------------------------------------- */
add_action( 'wp_enqueue_scripts', 'kbt_enqueue_styles', 20 );
function kbt_enqueue_styles() {
	$parent_style = 'kadence-style';

	// Parent theme style.
	wp_enqueue_style(
		$parent_style,
		get_template_directory_uri() . '/style.css',
		array(),
		wp_get_theme( 'kadence' )->get( 'Version' )
	);

	// Child style.css (frontmatter only).
	wp_enqueue_style(
		'kbt-style',
		get_stylesheet_directory_uri() . '/style.css',
		array( $parent_style ),
		wp_get_theme()->get( 'Version' )
	);

	// Custom design CSS.
	wp_enqueue_style(
		'kbt-custom',
		get_stylesheet_directory_uri() . '/custom-style.css',
		array( 'kbt-style' ),
		filemtime( get_stylesheet_directory() . '/custom-style.css' )
	);

	// Google Fonts: Plus Jakarta Sans + Inter.
	wp_enqueue_style(
		'kbt-google-fonts',
		'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap',
		array(),
		null
	);

	// Reading progress bar + dark mode toggle script.
	wp_enqueue_script(
		'kbt-custom',
		get_stylesheet_directory_uri() . '/custom.js',
		array(),
		filemtime( get_stylesheet_directory() . '/custom.js' ),
		true
	);
}

/* Preconnect ke Google Fonts (lebih cepat) */
add_action( 'wp_head', 'kbt_preconnect_google_fonts', 1 );
function kbt_preconnect_google_fonts() {
	echo '<link rel="preconnect" href="https://fonts.googleapis.com">' . "\n";
	echo '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>' . "\n";
}

/* Hapus duplikat Google Fonts dari Kadence (child theme sudah load via kbt-google-fonts) */
add_filter( 'kadence_print_google_fonts', '__return_false' );

/* -------------------------------------------------------------------------
 * 2. Reading time function
 * ---------------------------------------------------------------------- */
function kbt_reading_time( $post_id = null ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$content = get_post_field( 'post_content', $post_id );
	$word_count = str_word_count( wp_strip_all_tags( $content ) );
	$minutes = (int) ceil( $word_count / 200 ); // 200 wpm.
	$minutes = max( 1, $minutes );
	/* translators: %d: reading time in minutes */
	return sprintf( _n( '%d menit baca', '%d menit baca', $minutes, 'kadence-beritateknologi' ), $minutes );
}

add_shortcode( 'kbt_reading_time', function() {
	return esc_html( kbt_reading_time() );
} );

/* -------------------------------------------------------------------------
 * 3. Custom excerpt length (20 kata) + "..." more
 * ---------------------------------------------------------------------- */
add_filter( 'excerpt_length', function() { return 30; }, 999 );
add_filter( 'excerpt_more',   function() { return '&hellip;'; }, 999 );

/* -------------------------------------------------------------------------
 * 4. Remove emoji scripts (speed up pages)
 * ---------------------------------------------------------------------- */
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );

/* -------------------------------------------------------------------------
 * 5. Remove query strings from static assets
 * ---------------------------------------------------------------------- */
add_filter( 'style_loader_src', 'kbt_remove_qs', 15 );
add_filter( 'script_loader_src', 'kbt_remove_qs', 15 );
function kbt_remove_qs( $src ) {
	if ( strpos( $src, '?ver=' ) !== false ) {
		$src = remove_query_arg( 'ver', $src );
	}
	return $src;
}

/* -------------------------------------------------------------------------
 * 6. og:image fallback if featured image kosong
 * ---------------------------------------------------------------------- */
add_filter( 'rank_math/opengraph/facebook/image', 'kbt_og_image_fallback' );
function kbt_og_image_fallback( $image ) {
	if ( empty( $image ) ) {
		$image = get_stylesheet_directory_uri() . '/assets/og-default.jpg';
	}
	return $image;
}

/* -------------------------------------------------------------------------
 * 7. Custom body class per kategori + darkmode hint
 * ---------------------------------------------------------------------- */
add_filter( 'body_class', 'kbt_body_class' );
function kbt_body_class( $classes ) {
	if ( is_single() ) {
		$cats = get_the_category();
		foreach ( (array) $cats as $c ) {
			$classes[] = 'cat-' . sanitize_html_class( $c->slug );
		}
	}
	return $classes;
}

/* -------------------------------------------------------------------------
 * 8. Breadcrumb fallback (kalau Rank Math dimatikan)
 * ---------------------------------------------------------------------- */
function kbt_breadcrumbs() {
	if ( function_exists( 'rank_math_the_breadcrumbs' ) ) {
		rank_math_the_breadcrumbs();
		return;
	}

	$sep = ' <span class="kbt-sep">›</span> ';
	echo '<nav class="kbt-breadcrumbs" aria-label="Breadcrumb">';
	echo '<a href="' . esc_url( home_url( '/' ) ) . '">Beranda</a>';

	if ( is_category() || is_single() ) {
		$cats = get_the_category();
		if ( ! empty( $cats ) ) {
			echo $sep . '<a href="' . esc_url( get_category_link( $cats[0]->term_id ) ) . '">' . esc_html( $cats[0]->name ) . '</a>';
		}
		if ( is_single() ) {
			echo $sep . '<span>' . esc_html( get_the_title() ) . '</span>';
		}
	} elseif ( is_page() ) {
		echo $sep . '<span>' . esc_html( get_the_title() ) . '</span>';
	}
	echo '</nav>';
}

/* -------------------------------------------------------------------------
 * 9. Sembunyikan WP version dari header
 * ---------------------------------------------------------------------- */
remove_action( 'wp_head', 'wp_generator' );
add_filter( 'the_generator', '__return_empty_string' );

/* -------------------------------------------------------------------------
 * 10. Disable XML-RPC (tambahan atas blokir .htaccess)
 * ---------------------------------------------------------------------- */
add_filter( 'xmlrpc_enabled', '__return_false' );

/* -------------------------------------------------------------------------
 * 11. Nonaktifkan dukungan komentar sepenuhnya (blog berita)
 * ---------------------------------------------------------------------- */
add_action( 'init', function() {
	remove_post_type_support( 'post', 'comments' );
	remove_post_type_support( 'page', 'comments' );
} );

/* -------------------------------------------------------------------------
 * 12. Reading progress bar markup
 * ---------------------------------------------------------------------- */
add_action( 'wp_body_open', function() {
	if ( is_singular( 'post' ) ) {
		echo '<div id="kbt-reading-progress" aria-hidden="true"></div>';
	}
} );

/* -------------------------------------------------------------------------
 * 13. DNS prefetch + preload critical assets
 * ---------------------------------------------------------------------- */
add_action( 'wp_head', 'kbt_resource_hints', 2 );
function kbt_resource_hints() {
	echo '<link rel="dns-prefetch" href="//fonts.googleapis.com">' . "\n";
	echo '<link rel="dns-prefetch" href="//fonts.gstatic.com">' . "\n";
	echo '<link rel="dns-prefetch" href="//www.google-analytics.com">' . "\n";
	echo '<link rel="dns-prefetch" href="//www.googletagmanager.com">' . "\n";
}

/* -------------------------------------------------------------------------
 * 14. Schema.org structured data (Article + Organization + Breadcrumb)
 * ---------------------------------------------------------------------- */
add_action( 'wp_head', 'kbt_schema_markup', 5 );
function kbt_schema_markup() {
	// Organization schema (semua halaman).
	$org = array(
		'@context' => 'https://schema.org',
		'@type'    => 'Organization',
		'name'     => get_bloginfo( 'name' ),
		'url'      => home_url( '/' ),
		'logo'     => get_stylesheet_directory_uri() . '/assets/og-default.jpg',
	);
	echo '<script type="application/ld+json">' . wp_json_encode( $org, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>' . "\n";

	// Article schema (single post only).
	if ( is_singular( 'post' ) ) {
		global $post;
		$thumb = get_the_post_thumbnail_url( $post, 'full' );
		$article = array(
			'@context'         => 'https://schema.org',
			'@type'            => 'Article',
			'headline'         => get_the_title( $post ),
			'description'      => wp_trim_words( wp_strip_all_tags( $post->post_content ), 30, '...' ),
			'image'            => $thumb ? $thumb : get_stylesheet_directory_uri() . '/assets/og-default.jpg',
			'author'           => array(
				'@type' => 'Person',
				'name'  => get_the_author_meta( 'display_name', $post->post_author ),
			),
			'publisher'        => array(
				'@type' => 'Organization',
				'name'  => get_bloginfo( 'name' ),
				'logo'  => array(
					'@type' => 'ImageObject',
					'url'   => get_stylesheet_directory_uri() . '/assets/og-default.jpg',
				),
			),
			'datePublished'    => get_the_date( 'c', $post ),
			'dateModified'     => get_the_modified_date( 'c', $post ),
			'mainEntityOfPage' => get_permalink( $post ),
		);
		echo '<script type="application/ld+json">' . wp_json_encode( $article, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>' . "\n";
	}
}

/* -------------------------------------------------------------------------
 * 15. Related Posts (3 artikel dari kategori yang sama)
 * ---------------------------------------------------------------------- */
add_action( 'kadence_single_after_inner_content', 'kbt_related_posts', 15 );
function kbt_related_posts() {
	if ( ! is_singular( 'post' ) ) return;

	$cats = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );
	if ( empty( $cats ) ) return;

	$related = new WP_Query( array(
		'category__in'        => $cats,
		'post__not_in'        => array( get_the_ID() ),
		'posts_per_page'      => 3,
		'ignore_sticky_posts' => true,
		'orderby'             => 'rand',
	) );

	// Fallback: any recent posts if no same-category posts.
	if ( ! $related->have_posts() ) {
		$related = new WP_Query( array(
			'post__not_in'        => array( get_the_ID() ),
			'posts_per_page'      => 3,
			'ignore_sticky_posts' => true,
			'orderby'             => 'date',
		) );
	}

	if ( ! $related->have_posts() ) return;

	echo '<div class="kbt-related-posts">';
	echo '<h3 class="kbt-related-title">Artikel Terkait</h3>';
	echo '<div class="kbt-related-grid">';
	while ( $related->have_posts() ) {
		$related->the_post();
		echo '<a href="' . esc_url( get_the_permalink() ) . '" class="kbt-related-item">';
		if ( has_post_thumbnail() ) {
			echo '<div class="kbt-related-thumb">' . get_the_post_thumbnail( get_the_ID(), 'medium', array( 'loading' => 'lazy' ) ) . '</div>';
		}
		echo '<div class="kbt-related-info">';
		$r_cats = get_the_category();
		if ( ! empty( $r_cats ) ) {
			echo '<span class="kbt-related-cat">' . esc_html( $r_cats[0]->name ) . '</span>';
		}
		echo '<h4>' . esc_html( get_the_title() ) . '</h4>';
		echo '<time>' . esc_html( get_the_date() ) . '</time>';
		echo '</div></a>';
	}
	echo '</div></div>';
	wp_reset_postdata();
}

/* -------------------------------------------------------------------------
 * 16. Social share buttons (single post)
 * ---------------------------------------------------------------------- */
add_action( 'kadence_single_after_inner_content', 'kbt_share_buttons', 10 );
function kbt_share_buttons() {
	if ( ! is_singular( 'post' ) ) return;

	$url   = rawurlencode( get_the_permalink() );
	$title = rawurlencode( get_the_title() );
	$links = array(
		'whatsapp' => array(
			'url'   => 'https://api.whatsapp.com/send?text=' . $title . '%20' . $url,
			'label' => 'WhatsApp',
			'icon'  => '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>',
		),
		'twitter'  => array(
			'url'   => 'https://twitter.com/intent/tweet?url=' . $url . '&text=' . $title,
			'label' => 'X',
			'icon'  => '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>',
		),
		'facebook' => array(
			'url'   => 'https://www.facebook.com/sharer/sharer.php?u=' . $url,
			'label' => 'Facebook',
			'icon'  => '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>',
		),
		'copy'     => array(
			'url'   => '#',
			'label' => 'Salin',
			'icon'  => '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>',
		),
	);

	echo '<div class="kbt-share">';
	echo '<span class="kbt-share-label">Bagikan:</span>';
	foreach ( $links as $key => $s ) {
		$extra = ( 'copy' === $key ) ? ' data-url="' . esc_attr( get_the_permalink() ) . '" onclick="kbtCopyLink(this);return false;"' : ' target="_blank" rel="noopener noreferrer"';
		echo '<a href="' . esc_url( $s['url'] ) . '" class="kbt-share-btn kbt-share-' . $key . '" aria-label="' . esc_attr( $s['label'] ) . '"' . $extra . '>' . $s['icon'] . '</a>';
	}
	echo '</div>';
}

/* -------------------------------------------------------------------------
 * 17. Author Box (single post)
 * ---------------------------------------------------------------------- */
add_action( 'kadence_single_after_inner_content', 'kbt_author_box', 20 );
function kbt_author_box() {
	if ( ! is_singular( 'post' ) ) return;

	$author_id   = get_the_author_meta( 'ID' );
	$name        = get_the_author_meta( 'display_name' );
	$bio         = get_the_author_meta( 'description' );
	$avatar      = get_avatar( $author_id, 72 );
	$posts_url   = get_author_posts_url( $author_id );
	$post_count  = count_user_posts( $author_id, 'post' );

	echo '<div class="kbt-author-box">';
	echo '<div class="kbt-author-avatar">' . $avatar . '</div>';
	echo '<div class="kbt-author-info">';
	echo '<span class="kbt-author-label">Ditulis oleh</span>';
	echo '<h4 class="kbt-author-name"><a href="' . esc_url( $posts_url ) . '">' . esc_html( $name ) . '</a></h4>';
	if ( $bio ) {
		echo '<p class="kbt-author-bio">' . esc_html( $bio ) . '</p>';
	}
	echo '<span class="kbt-author-count">' . $post_count . ' artikel</span>';
	echo '</div></div>';
}

/* -------------------------------------------------------------------------
 * 18. Auto Table of Contents for long posts (3+ headings)
 * ---------------------------------------------------------------------- */
add_filter( 'the_content', 'kbt_auto_toc', 12 );
function kbt_auto_toc( $content ) {
	if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) return $content;

	preg_match_all( '/<h([2-3])[^>]*>(.*?)<\/h\1>/i', $content, $matches, PREG_SET_ORDER );
	if ( count( $matches ) < 3 ) return $content;

	$toc = '<div class="kbt-toc"><div class="kbt-toc-header"><span class="kbt-toc-title">Daftar Isi</span><button class="kbt-toc-toggle" aria-label="Toggle daftar isi" onclick="this.closest(\'.kbt-toc\').classList.toggle(\'collapsed\')">▼</button></div><ol class="kbt-toc-list">';
	$i = 0;
	foreach ( $matches as $m ) {
		$level = $m[1];
		$text  = wp_strip_all_tags( $m[2] );
		$slug  = 'kbt-h-' . ( ++$i );

		$content = str_replace( $m[0], '<h' . $level . ' id="' . $slug . '">' . $m[2] . '</h' . $level . '>', $content );

		$indent = ( '3' === $level ) ? ' class="kbt-toc-sub"' : '';
		$toc .= '<li' . $indent . '><a href="#' . $slug . '">' . esc_html( $text ) . '</a></li>';
	}
	$toc .= '</ol></div>';

	// Sisipkan setelah paragraf pertama.
	$pos = strpos( $content, '</p>' );
	if ( false !== $pos ) {
		$content = substr_replace( $content, '</p>' . $toc, $pos, 4 );
	}

	return $content;
}

/* -------------------------------------------------------------------------
 * 19. Back to Top button markup
 * ---------------------------------------------------------------------- */
add_action( 'wp_footer', function() {
	echo '<button id="kbt-back-to-top" aria-label="Kembali ke atas" title="Kembali ke atas">';
	echo '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 15 12 9 6 15"/></svg>';
	echo '</button>';
} );

/* -------------------------------------------------------------------------
 * 20. Open Graph meta enhancements
 * ---------------------------------------------------------------------- */
add_action( 'wp_head', 'kbt_og_meta', 3 );
function kbt_og_meta() {
	echo '<meta property="og:locale" content="id_ID" />' . "\n";
	echo '<meta property="og:site_name" content="' . esc_attr( get_bloginfo( 'name' ) ) . '" />' . "\n";
	if ( is_singular( 'post' ) ) {
		echo '<meta property="og:type" content="article" />' . "\n";
		echo '<meta property="article:published_time" content="' . esc_attr( get_the_date( 'c' ) ) . '" />' . "\n";
		echo '<meta property="article:modified_time" content="' . esc_attr( get_the_modified_date( 'c' ) ) . '" />' . "\n";
	}
}

