<?php

/**
 * Author Kit Byline Manager
 *
 * Manages the display of custom author bylines in posts, including
 * theme compatibility detection, selector resolution, and conditional
 * asset injection for byline rendering.
 *
 * Handles user options, caches theme-specific selectors, and updates
 * compatibility status based on the active theme.
 *
 * @package AuthorKit
 * @since 1.0.0
 */

if (! defined('ABSPATH')) {
	exit; // Exit if accessed directly.
}

/**
 * Class Author_Kit_Byline_Manager
 *
 * Replaces theme's byline with Author Kit's custom byline.
 */
class Author_Kit_Byline_Manager
{

	/**
	 * Array of current options/settings used by the Byline Manager.
	 *
	 * @var array
	 */
	protected $options;

	/**
	 * CSS selector string where the byline should be injected.
	 *
	 * @var string
	 */
	protected $selector;

	/**
	 * Array of available theme compatibility options for byline placement.
	 *
	 * @var array
	 */
	protected $available_options;

	/**
	 * Constructor.
	 *
	 * Loads compatible themes options, updates compatibility status if needed,
	 * resolves CSS selector for byline elements, and hooks asset loading to 'wp' action.
	 */
	public function __construct()
	{
		$this->available_options = include __DIR__ . '/compatible-themes.php';

		$this->selector = $this->resolve_selector();

		add_action('wp', array($this, 'author_kit_conditionally_add_assets'));
	}

	/**
	 * Resolve the CSS selector used to locate the byline element.
	 *
	 * The method prioritizes selectors in this order:
	 * - If theme is compatible:
	 *   1. Use selector from compatibility map
	 * - If theme is incompatible:
	 *   1. User-defined selector per theme
	 *   2. Manual override
	 *   3. Cached fallback
	 *   4. Default
	 *
	 * @return string The resolved CSS selector for the byline element.
	 */
	protected function resolve_selector()
	{
		$normalized_theme = $this->get_normalized_theme_name();
		$available_options = $this->available_options;

		// Always check and refresh compatibility on each call
		author_kit_update_compatibility_status();
		$compatibility_status = get_option('author_kit_byline_compatibility_status', 'Incompatible');

		if ('Compatible' === $compatibility_status && isset($available_options[$normalized_theme])) {
			// Use compatible theme selector directly
			return $available_options[$normalized_theme];
		}

		// Theme is Incompatible: use fallback options
		$custom_selectors_map = get_option('author_kit_byline_custom_selectors', array());
		if (! empty($custom_selectors_map[$normalized_theme])) {
			return sanitize_text_field($custom_selectors_map[$normalized_theme]);
		}

		$manual_selector = get_option('author_kit_manual_byline_selector');
		if (! empty($manual_selector)) {
			return sanitize_text_field($manual_selector);
		}

		$transient_key   = 'author_kit_theme_byline_selector';
		$cached_selector = get_transient($transient_key);
		if (false !== $cached_selector) {
			return $cached_selector;
		}

		// Fallback to default selector
		return $available_options['Default'];
	}


	/**
	 * Get the normalized current theme name.
	 *
	 * Converts the theme name to lowercase and then capitalizes the first letter of each word,
	 * ensuring consistent formatting for theme name comparisons.
	 *
	 * @return string Normalized theme name.
	 */
	protected function get_normalized_theme_name()
	{
		return ucwords(strtolower(wp_get_theme()->get('Name')));
	}



	/**
	 * Injects byline HTML into the theme on single posts using JavaScript.
	 *
	 * NOTE TO REVIEWERS:
	 * This inline JavaScript is required to dynamically inject and override byline content
	 * based on theme-specific selectors stored in PHP. Since the selector and rendered HTML
	 * are generated at runtime, this script must be generated inline in PHP to prevent
	 * breakage and preserve flexibility. Moving this logic to a static JS file will
	 * break the feature.
	 *
	 * @return void
	 */
	public function author_kit_conditionally_add_assets()
	{
		if (is_singular('post') && ! empty($this->selector)) {

			// Register dummy handle for inline script
			add_action('wp_enqueue_scripts', function () {
				wp_register_script('author-kit-byline', '', [], '1.0.0', true);
				wp_enqueue_script('author-kit-byline');
			});

			add_action('wp_footer', function () {
				$selector = esc_js($this->selector);
				$content  = wp_json_encode($this->get_rendered_byline_content());

				$script  = 'document.addEventListener("DOMContentLoaded", function() {';
				$script .= 'const element = document.querySelector("' . $selector . '");';
				$script .= 'if (element) {';
				$script .= 'element.innerHTML = ' . $content . ';';
				$script .= 'element.removeAttribute("id");';
				$script .= 'element.removeAttribute("class");';
				$script .= 'element.classList.add("author-kit-byline", "author-kit-byline-container");';
				$script .= '}';
				$script .= '});';

				wp_add_inline_script('author-kit-byline', $script);
			});
		}
	}


	/**
	 * Generates the byline HTML content for the current post.
	 *
	 * Collects author, coauthor, avatar, dates, and comments data,
	 * includes the active byline template, and returns sanitized output.
	 *
	 * @return string Rendered byline HTML content.
	 */
	protected function get_rendered_byline_content()
	{
		global $post;
		if (! is_singular('post') || ! isset($post)) {
			return '';
		}

		$post_id              = $post->ID;
		$author_id            = get_the_author_meta('ID');
		$coauthors            = author_kit_get_coauthors_by_post($post_id);
		$author_kit_name      = author_kit_display_name($author_id);
		$avatar               = get_avatar_url($author_id);
		$avatar_alt_text      = ! empty($author_kit_name) ? $author_kit_name . ' Avatar' : 'Author Avatar';
		$date_format          = get_option('date_format');
		$first_published_date = get_the_date($date_format, $post_id);
		$last_updated_date    = get_the_modified_date($date_format, $post_id);
		$comments_count       = absint(get_comments_number());
		$comments_link        = get_comments_link();

		ob_start();
		include $this->author_kit_get_active_template_path();
		$byline_content = ob_get_clean();

		return  $byline_content;
	}

	/**
	 * Get the path to the active byline template.
	 *
	 * Returns the custom template path if it exists,
	 * otherwise falls back to the default template.
	 *
	 * @return string Path to the byline template file.
	 */
	protected function author_kit_get_active_template_path()
	{
		$template_path = AUTHOR_KIT_PLUGIN_PATH . 'public/templates/custom-bylines/byline-template.php';

		return file_exists($template_path)
			? $template_path
			: AUTHOR_KIT_PLUGIN_PATH . 'public/templates/custom-bylines/template-default.php';
	}
}

/**
 * Initialize the Author_Kit_Byline_Manage if enabled.
 */

add_action(
	'init',
	function () {
		if (get_option('author_kit_byline_display', true)) {
			new Author_Kit_Byline_Manager();
		}
	}
);
