<?php

/**
 * Author Kit Meta Boxes class file.
 *
 * Provides the functionality to add custom meta boxes for co-authors and author bio box control.
 * Includes UI rendering, nonce verification, saving meta data for posts.
 *
 * @package Author_Kit
 * @since 1.0.0
 */

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

/**
 * Class Author_Kit_Meta_Boxes
 *
 * Handles adding, displaying, and saving custom meta boxes for Author Kit plugin.
 * Adds meta boxes for selecting co-authors and hiding the author bio box on supported post types.
 *
 * @package Author_Kit
 */
class Author_Kit_Meta_Boxes
{


	/**
	 * Post types where the meta boxes should be added.
	 *
	 * @var string[] Array of post type slugs.
	 */
	private $screens = array('post');

	/**
	 * Constructor
	 *
	 * Initialize meta box hooks for adding and saving Author Kit meta fields.
	 */
	public function __construct()
	{
		add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
		add_action('save_post', array($this, 'save_author_kit_coauthors_meta'));
		add_action('save_post', array($this, 'save_author_kit_hide_bio_box_meta'));
	}

	/**
	 * Register custom meta boxes for each screen.
	 *
	 * Adds "Co Authors" and "Author Bio Box" meta boxes
	 * to the specified post type screens.
	 */
	public function add_meta_boxes()
	{
		foreach ($this->screens as $s) {
			add_meta_box(
				'ADDcoauthors',
				__('Co Authors', 'author-kit'),
				array($this, 'author_kit_coauthors_meta_box_callback'),
				$s,
				'side',
				'high'
			);

			add_meta_box(
				'authorkit_bio_box_meta',
				__('Hide Bio Box', 'author-kit'),
				array($this, 'authorkit_bio_box_meta_callback'),
				$s,
				'side',
				'high'
			);
		}
	}

	/**
	 * Output the content of the "Co Authors" meta box.
	 *
	 * Adds a nonce field for security and calls the field generator.
	 *
	 * @param WP_Post $post The current post object.
	 */
	public function author_kit_coauthors_meta_box_callback($post)
	{
		$this->field_generator($post);
	}


	/**
	 * Generates the Co-Authors meta box UI.
	 *
	 * Displays the current co-authors for the post, allows searching
	 * and adding new co-authors from all WordPress users except the post author,
	 * and handles the UI for removing co-authors.
	 *
	 * @param WP_Post $post The current post object.
	 */
	private function field_generator($post)
	{
		// Get all WordPress users.
		$users = get_users();

		// create a global of coauthors class.
		global $author_kit_coauthors;

		// Retrieve existing co-authors against specific post ID.
		$coauthors = $author_kit_coauthors->get_coauthors_by_post($post->ID);
		$coauthors = is_array($coauthors) ? array_map('intval', $coauthors) : array();

		$post_author = intval(get_post_field('post_author', $post->ID));

		wp_nonce_field('save_authorkit_coauthors', 'authorkit_coauthors_nonce');

		// Meta box HTML.
?>
		<div id="coauthors-search">
			<input type="text" id="search-input" placeholder="Search Users..." />
			<ul id="coauthors-options">
				<?php foreach ($users as $user) { ?>
					<?php
					$user_id = intval($user->ID);
					if (! in_array($user_id, $coauthors, true) && $user_id !== $post_author) {
					?>
						<li
							data-user-id="<?php echo esc_attr($user->ID); ?>"
							data-avatar="<?php echo esc_url(get_avatar_url($user->ID)); ?>">
							<?php // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
							echo '<img src="' . esc_url(get_avatar_url($user->ID)) . '" alt="' . esc_attr($user->display_name) . '" width="24" height="24" />';
							?>
							<span><?php echo esc_html($user->display_name); ?></span>
						</li>
				<?php
					}
				}
				?>
			</ul>
		</div>
		<p class="author-kit-metabox-desc">
			<?php esc_html_e('Easily Add Multiple Co-Authors', 'author-kit'); ?>
		</p>

		<div id="coauthors-container">
			<div id="selected-coauthors">
				<?php foreach ($coauthors as $author_id) : ?>
					<?php $user = get_user_by('ID', $author_id); ?>
					<?php if ($user) : ?>
						<div class="coauthor-item" data-user-id="<?php echo esc_attr($user->ID); ?>" data-display-name="<?php echo esc_html($user->display_name); ?>">
							<?php echo get_avatar($user->ID, 32); ?>
							<?php echo esc_html($user->display_name); ?>
							<button type="button" class="remove-coauthor" data-user-id="<?php echo esc_attr($user->ID); ?>" data-display-name="<?php echo esc_html($user->display_name); ?>">X</button>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>
			</div>



			<input type="hidden" id="authorkit-coauthors-input" name="authorkit_coauthors[]" value="<?php echo esc_attr(implode(',', $coauthors)); ?>" />
		</div>
	<?php
	}

	/**
	 * Outputs the Author Kit Bio Box meta box content.
	 *
	 * Displays a checkbox to hide or show the Author Kit Bio Box on the post edit screen.
	 *
	 * @param WP_Post $post The current post object.
	 */
	public function authorkit_bio_box_meta_callback($post)
	{
		wp_nonce_field('hide_author_kit_bio_box_data', 'hide_author_kit_bio_box_nonce');

		// Retrieve the current value of the checkbox (true if checked, false otherwise).
		$hide_bio_box = metadata_exists('post', $post->ID, 'hide_author_kit_bio_box') ? boolval(get_post_meta($post->ID, 'hide_author_kit_bio_box', true)) : false;
		$checked      = $hide_bio_box ? 'checked' : '';

	?>

		<p>
			<label for="hide_author_kit_bio_box_checkbox">
				<input type="checkbox" id="hide_author_kit_bio_box_checkbox" name="hide_author_kit_bio_box_checkbox" value="<?php echo esc_html($hide_bio_box); ?>" <?php echo esc_html($checked); ?> />
				<?php esc_html_e('Hide Author Kit Bio Box', 'author-kit'); ?>
			</label>
		</p>

<?php
	}

	/**
	 * Save co-authors meta when the post is saved.
	 *
	 * Validates nonce, user permissions, and autosave state before
	 * sanitizing and updating the co-authors for the given post.
	 *
	 * @param int $post_id The ID of the post being saved.
	 */
	public function save_author_kit_coauthors_meta($post_id)
	{
		if (! isset($_POST['authorkit_coauthors_nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['authorkit_coauthors_nonce'])), 'save_authorkit_coauthors')) {
			return;
		}

		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
			return;
		}

		if (! current_user_can('edit_post', $post_id)) {
			return;
		}

		if (isset($_POST['authorkit_coauthors']) && is_array($_POST['authorkit_coauthors']) && isset($_POST['authorkit_coauthors'][0])) {

			require_once AUTHOR_KIT_PLUGIN_PATH . 'includes/class/class-author-kit-coauthors.php';
			global $author_kit_coauthors;

			// Sanitize the input to ensure it's an array of integers (user IDs).
			$selected_users = array_map('intval', explode(',', sanitize_text_field(wp_unslash($_POST['authorkit_coauthors'][0]))));

			$added_by = get_current_user_id();

			$result = $author_kit_coauthors->update_post_coauthors($post_id, $selected_users, $added_by);

			if (! $result) {
				return;
			}
		}
	}


	/**
	 * Save the state of the "Hide Author Kit Bio Box" checkbox meta.
	 *
	 * Verifies nonce, user permissions, and autosave status before
	 * updating the post meta with a boolean value based on checkbox input.
	 *
	 * @param int $post_id The ID of the post being saved.
	 * @return int The post ID, for hook compatibility.
	 */
	public function save_author_kit_hide_bio_box_meta($post_id)
	{
		// Check if the nonce is set.
		if (! isset($_POST['hide_author_kit_bio_box_nonce'])) {
			return $post_id;
		}

		// Verify the nonce.
		if (! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['hide_author_kit_bio_box_nonce'])), 'hide_author_kit_bio_box_data')) {
			return $post_id;
		}

		// Check if the user has permission to save the data.
		if (! current_user_can('edit_post', $post_id)) {
			return $post_id;
		}

		// Check if this is an auto-save routine; if it is, our form has not been submitted.
		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
			return $post_id;
		}

		// Sanitize and save the checkbox value.
		if (isset($_POST['hide_author_kit_bio_box_checkbox'])) {
			update_post_meta($post_id, 'hide_author_kit_bio_box', true);
		} else {
			update_post_meta($post_id, 'hide_author_kit_bio_box', false);
		}
	}
}


?>