<?php
/**
 * Markdown export endpoint.
 *
 * @package MicropediaAISearchOptimizer
 */

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

/** Markdown exporter. */
class Micropedia_AI_Markdown {
	/** Init hooks. */
	public static function init() {
		add_action( 'template_redirect', array( __CLASS__, 'maybe_render_markdown' ) );
	}

	/** Render /micropedia-ai-md/post-slug.md endpoint. */
	public static function maybe_render_markdown() {
		if ( ! micropedia_ai_get_option( 'enable_markdown', 0 ) ) {
			return;
		}

		$uri  = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		$path = (string) wp_parse_url( $uri, PHP_URL_PATH );

		if ( ! preg_match( '#^/micropedia-ai-md/([^/]+)\.md$#', $path, $matches ) ) {
			return;
		}

		$slug = sanitize_title( $matches[1] );
		$post = get_page_by_path( $slug, OBJECT, array( 'post', 'page' ) );
		if ( ! $post || 'publish' !== $post->post_status ) {
			status_header( 404 );
			exit;
		}

		$cache_key = 'micropedia_ai_md_' . md5( $post->ID . '_' . get_post_modified_time( 'U', false, $post ) );
		$body      = get_transient( $cache_key );
		if ( ! is_string( $body ) ) {
			$content = get_post_field( 'post_content', $post );
			$content = strip_shortcodes( $content );
			$content = wp_strip_all_tags( apply_filters( 'the_content', $content ) );
			$body    = '# ' . wp_strip_all_tags( get_the_title( $post ) ) . "\n\n";
			$body   .= 'URL: ' . esc_url_raw( get_permalink( $post ) ) . "\n";
			$body   .= 'Date: ' . wp_strip_all_tags( get_the_date( 'c', $post ) ) . "\n\n";
			$body   .= trim( $content ) . "\n";
			set_transient( $cache_key, $body, absint( micropedia_ai_get_option( 'cache_ttl', HOUR_IN_SECONDS ) ) );
		}

		status_header( 200 );
		nocache_headers();
		header( 'Content-Type: text/markdown; charset=utf-8' );
		echo esc_html( $body );
		exit;
	}
}
