<?php
if (!defined('ABSPATH')) {
	exit;
}

class ProbonoSEO_LLMS_Txt {
	private static $instance = null;

	public static function get_instance() {
		if (self::$instance === null) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		$this->init_hooks();
	}

	private function init_hooks() {
		if (get_option('probonoseo_aio_llms_txt', '1') === '1') {
			add_action('init', array($this, 'maybe_output_llms_txt'), 0);
		}
	}

	public function maybe_output_llms_txt() {
		if (is_admin()) {
			return;
		}

		$request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
		if ($request_uri === '') {
			return;
		}

		$path = wp_parse_url($request_uri, PHP_URL_PATH);
		if (empty($path)) {
			return;
		}

		$home_path = wp_parse_url(home_url('/'), PHP_URL_PATH);
		$relative = $path;
		if (!empty($home_path) && $home_path !== '/' && strpos($path, $home_path) === 0) {
			$relative = substr($path, strlen($home_path) - 1);
		}

		if (trim($relative, '/') !== 'llms.txt') {
			return;
		}

		nocache_headers();
		if (!headers_sent()) {
			header('Content-Type: text/plain; charset=utf-8');
		}

		echo $this->build_llms_txt(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	private function build_llms_txt() {
		$site_name = wp_strip_all_tags(get_bloginfo('name'));
		if ($site_name === '') {
			$site_name = wp_parse_url(home_url('/'), PHP_URL_HOST);
		}

		$lines = array();
		$lines[] = '# ' . $site_name;
		$lines[] = '';

		$description = wp_strip_all_tags(get_bloginfo('description'));
		if ($description !== '') {
			$lines[] = '> ' . $description;
			$lines[] = '';
		}

		$lines[] = 'URL: ' . home_url('/');
		$lines[] = '';

		$pages = get_pages(array(
			'sort_column' => 'menu_order,post_title',
			'sort_order'  => 'ASC',
			'parent'      => 0,
			'number'      => 50,
		));

		if (!empty($pages)) {
			$lines[] = '## 主要ページ';
			foreach ($pages as $page) {
				$title = wp_strip_all_tags(get_the_title($page));
				$title = trim(preg_replace('/\s+/', ' ', $title));
				if ($title === '') {
					continue;
				}
				$lines[] = '- [' . $title . '](' . get_permalink($page) . ')';
			}
			$lines[] = '';
		}

		$posts = get_posts(array(
			'numberposts' => 20,
			'post_status' => 'publish',
			'orderby'     => 'date',
			'order'       => 'DESC',
		));

		if (!empty($posts)) {
			$lines[] = '## 最近の投稿';
			foreach ($posts as $post) {
				$title = wp_strip_all_tags(get_the_title($post));
				$title = trim(preg_replace('/\s+/', ' ', $title));
				if ($title === '') {
					continue;
				}
				$lines[] = '- [' . $title . '](' . get_permalink($post) . ')';
			}
			$lines[] = '';
		}

		$categories = get_categories(array(
			'hide_empty' => true,
			'number'     => 30,
		));

		if (!empty($categories)) {
			$lines[] = '## カテゴリー';
			foreach ($categories as $category) {
				$title = wp_strip_all_tags($category->name);
				$title = trim(preg_replace('/\s+/', ' ', $title));
				if ($title === '') {
					continue;
				}
				$link = get_category_link($category);
				if (is_wp_error($link)) {
					continue;
				}
				$lines[] = '- [' . $title . '](' . $link . ')';
			}
			$lines[] = '';
		}

		$content = implode("\n", $lines);
		$content = rtrim($content) . "\n";

		/**
		 * Filter the generated llms.txt content.
		 *
		 * @param string $content The full llms.txt body.
		 */
		return apply_filters('probonoseo_llms_txt_content', $content);
	}
}

function probonoseo_init_llms_txt() {
	ProbonoSEO_LLMS_Txt::get_instance();
}
add_action('plugins_loaded', 'probonoseo_init_llms_txt');
