<?php
namespace KBT_SEO;

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

class Baca_Juga {

	public static function init() {
		add_filter( 'the_content', array( __CLASS__, 'insert_baca_juga' ), 15 );
	}

	/**
	 * Auto-insert "Baca Juga" links into post content.
	 * Inserts after every Nth paragraph (default: after paragraph 2, then every 4 paragraphs).
	 */
	public static function insert_baca_juga( $content ) {
		if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
			return $content;
		}

		// Settings
		$enabled      = get_option( 'kbt_seo_baca_juga_enabled', '1' );
		$first_after  = (int) get_option( 'kbt_seo_baca_juga_first', 2 );   // After which paragraph
		$repeat_every = (int) get_option( 'kbt_seo_baca_juga_repeat', 4 );  // Repeat every N paragraphs
		$max_inserts  = (int) get_option( 'kbt_seo_baca_juga_max', 3 );     // Max inserts per article

		if ( '1' !== $enabled ) return $content;

		// Get related posts from same categories
		$cats = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );
		if ( empty( $cats ) ) return $content;

		$related = get_posts( array(
			'category__in'        => $cats,
			'post__not_in'        => array( get_the_ID() ),
			'posts_per_page'      => $max_inserts + 2,
			'orderby'             => 'rand',
			'ignore_sticky_posts' => true,
			'post_status'         => 'publish',
		) );

		// Fallback: if no same-category posts, get any recent posts
		if ( empty( $related ) ) {
			$related = get_posts( array(
				'post__not_in'        => array( get_the_ID() ),
				'posts_per_page'      => $max_inserts + 2,
				'orderby'             => 'date',
				'ignore_sticky_posts' => true,
				'post_status'         => 'publish',
			) );
		}

		if ( empty( $related ) ) return $content;

		// Split content by paragraphs
		$paragraphs = preg_split( '/(<\/p>)/i', $content, -1, PREG_SPLIT_DELIM_CAPTURE );

		// Rebuild paragraphs as pairs (content + closing tag)
		$blocks = array();
		for ( $i = 0; $i < count( $paragraphs ); $i += 2 ) {
			$block = $paragraphs[ $i ];
			if ( isset( $paragraphs[ $i + 1 ] ) ) {
				$block .= $paragraphs[ $i + 1 ];
			}
			// Only count actual paragraph blocks (not empty/whitespace-only)
			if ( trim( strip_tags( $block ) ) !== '' || preg_match( '/<\/p>/i', $block ) ) {
				$blocks[] = $block;
			}
		}

		$total_paragraphs = count( $blocks );
		if ( $total_paragraphs < $first_after + 1 ) return $content;

		// Determine insertion points
		$insert_points = array();
		$insert_points[] = $first_after; // First insert
		if ( $repeat_every > 0 ) {
			$next = $first_after + $repeat_every;
			while ( count( $insert_points ) < $max_inserts && $next < $total_paragraphs - 1 ) {
				$insert_points[] = $next;
				$next += $repeat_every;
			}
		}

		// Build output
		$related_idx = 0;
		$output = '';
		$para_count = 0;

		foreach ( $blocks as $block ) {
			$output .= $block;
			$para_count++;

			if ( in_array( $para_count, $insert_points, true ) && isset( $related[ $related_idx ] ) ) {
				$r = $related[ $related_idx ];
				$r_cats = get_the_category( $r->ID );
				$cat_name = ! empty( $r_cats ) ? $r_cats[0]->name : '';

				$output .= self::render_baca_juga( $r, $cat_name );
				$related_idx++;
			}
		}

		return $output;
	}

	/**
	 * Render a single "Baca Juga" box.
	 */
	private static function render_baca_juga( $post, $cat_name = '' ) {
		$url   = get_permalink( $post );
		$title = get_the_title( $post );
		$thumb = '';
		if ( has_post_thumbnail( $post->ID ) ) {
			$thumb = get_the_post_thumbnail( $post->ID, 'thumbnail', array(
				'class'   => 'kbt-bj-thumb',
				'loading' => 'lazy',
			) );
		}

		$html  = '<div class="kbt-baca-juga">';
		$html .= '<span class="kbt-bj-label">Baca Juga</span>';
		$html .= '<a href="' . esc_url( $url ) . '" class="kbt-bj-link">';
		if ( $thumb ) {
			$html .= '<div class="kbt-bj-image">' . $thumb . '</div>';
		}
		$html .= '<div class="kbt-bj-content">';
		$html .= '<span class="kbt-bj-title">' . esc_html( $title ) . '</span>';
		if ( $cat_name ) {
			$html .= '<span class="kbt-bj-cat">' . esc_html( $cat_name ) . '</span>';
		}
		$html .= '</div></a></div>';

		return $html;
	}
}
