<?php
/**
 * bbPress configuration for Forumax
 *
 * @package Forumax
 */

defined( 'ABSPATH' ) || exit;

/**
 * bbPress Replies
 */
add_filter( 'bbp_show_lead_topic', function () {
	$show_lead[] = 'true';
	return $show_lead;
} );

/**
 * bbPress User Role
 */
if ( ! function_exists( 'forumax_bbp_user_role_icon' ) ) {
	/**
	 * Get modern inline SVG icon markup for a bbPress role.
	 *
	 * @param string $author_role User role label.
	 * @return string
	 */
	function forumax_get_bbp_role_icon_svg( $author_role = '' ) {
		switch ( $author_role ) {
			case 'Keymaster':
				return '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3 8l4 4 5-7 5 7 4-4-2 11H5L3 8z"></path><path d="M8 18h8"></path></svg>';
			case 'Moderator':
				return '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 3l7 3v6c0 4.5-3 7.7-7 9-4-1.3-7-4.5-7-9V6l7-3z"></path><path d="M9 12l2 2 4-4"></path></svg>';
			case 'Participant':
				return '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="8.5" r="2.5"></circle><path d="M6.5 17.5c1.3-2.4 3.2-3.5 5.5-3.5s4.2 1.1 5.5 3.5"></path></svg>';
			case 'Member':
				return '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="8" r="2.75"></circle><path d="M6.5 18c1.2-2.6 3.1-3.8 5.5-3.8s4.3 1.2 5.5 3.8"></path><path d="M18.5 6.5l.9.6 1-.1-.6.9.1 1-.9-.6-.9.6.1-1-.6-.9 1 .1z"></path></svg>';
			case 'Spectator':
				return '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6z"></path><circle cx="12" cy="12" r="2.5"></circle></svg>';
			case 'Blocked':
				return '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"></circle><path d="M8.5 8.5l7 7"></path></svg>';
			default:
				return '';
		}
	}

	/**
	 * Display user role icon based on bbPress role.
	 */
	function forumax_bbp_user_role_icon() {
		$author_id = 0;

		if ( bbp_get_reply_id() ) {
			$author_id = bbp_get_reply_author_id( bbp_get_reply_id() );
		} elseif ( bbp_get_topic_id() ) {
			$author_id = bbp_get_topic_author_id( bbp_get_topic_id() );
		}

		$author_role = ! empty( $author_id ) ? bbp_get_user_display_role( $author_id ) : '';
		$icon_svg    = forumax_get_bbp_role_icon_svg( $author_role );

		if ( ! empty( $icon_svg ) ) {
			echo '<span class="forumax-role-icon forumax-role-icon--' . esc_attr( sanitize_title( $author_role ) ) . '" aria-hidden="true">' . $icon_svg . '</span>';
		}
	}
}

/**
 * Get author role
 */
if ( ! function_exists( 'forumax_get_bbp_user_role' ) ) {
	/**
	 * Get the author role for the current topic.
	 *
	 * @return string The author role.
	 */
	function forumax_get_bbp_user_role( $topic_id = 0 ) {
		$role = bbp_get_topic_author_role( [
			'topic_id' => $topic_id,
			'before'   => '',
			'after'    => '',
		]);
		return $role;
	}
}

/**
 * Get reply author role
 */
if ( ! function_exists( 'forumax_get_bbp_reply_user_role' ) ) {
	/**
	 * Get the author role for the current reply.
	 *
	 * @param int $reply_id Reply ID.
	 * @return string The author role.
	 */
	function forumax_get_bbp_reply_user_role( $reply_id = 0 ) {
		$role = bbp_get_reply_author_role( [
			'reply_id' => $reply_id,
			'before'   => '',
			'after'    => '',
		] );
		return $role;
	}
}

/**
 * Get topic reply count
 */
if ( ! function_exists( 'forumax_topic_reply_count' ) ) {
	/**
	 * Output the topic reply count.
	 */
	function forumax_topic_reply_count() {
		$get_reply    = get_post_meta( get_the_ID(), '_bbp_reply_count', true );
		$_reply_count = isset( $get_reply ) && ! empty( $get_reply ) ? $get_reply : 0;
		echo esc_html( $_reply_count );
	}
}

/**
 * Display bbp_reply_admin_links() as a dropdown list.
 */
if ( ! function_exists( 'forumax_get_reply_admin_links' ) ) {
	/**
	 * Get reply admin links as a dropdown.
	 *
	 * @param array $args Arguments for the admin links.
	 * @return string|void Admin links HTML.
	 */
	function forumax_get_reply_admin_links( $args = [] ) {

		// Parse arguments against default values
		$r = bbp_parse_args( $args, [
			'id'     => 0,
			'before' => '<div class="bbp-admin-links-dropdown">',
			'after'  => '</div>',
			'sep'    => '',
			'links'  => [],
		], 'get_reply_admin_links' );

		$r['id'] = bbp_get_reply_id( $r['id'] );

		// If post is a topic, return the topic admin links instead
		if ( bbp_is_topic( $r['id'] ) ) {
			return forumax_get_topic_admin_links( $args );
		}

		// If post is not a reply, return
		if ( ! bbp_is_reply( $r['id'] ) ) {
			return;
		}

		// If topic is trashed, do not show admin links
		if ( bbp_is_topic_trash( bbp_get_reply_topic_id( $r['id'] ) ) ) {
			return;
		}

		// If no links were passed, default to the standard
		if ( empty( $r['links'] ) ) {
			$r['links'] = apply_filters( 'bbp_reply_admin_links', [
				'edit'    => bbp_get_reply_edit_link( $r ),
				'move'    => bbp_get_reply_move_link( $r ),
				'split'   => bbp_get_topic_split_link( $r ),
				'trash'   => bbp_get_reply_trash_link( $r ),
				'spam'    => bbp_get_reply_spam_link( $r ),
				'approve' => bbp_get_reply_approve_link( $r ),
				'reply'   => bbp_get_reply_to_link( $r ),
			], $r['id'] );
		}

		// See if links need to be unset
		$reply_status = bbp_get_reply_status( $r['id'] );
		if ( in_array( $reply_status, [ bbp_get_spam_status_id(), bbp_get_trash_status_id(), bbp_get_pending_status_id() ], true ) ) {

			// Spam link shouldn't be visible on trashed topics
			if ( bbp_get_trash_status_id() === $reply_status ) {
				unset( $r['links']['spam'] );

			// Trash link shouldn't be visible on spam topics
			} elseif ( bbp_get_spam_status_id() === $reply_status ) {
				unset( $r['links']['trash'] );
			}
		}

		// Build our dropdown menu structure
		$menu  = '<select name="reply-admin-links" class="frmx-nice-select bbp-admin-dropdown-menu" onchange="if(this.value && this.options[this.selectedIndex].getAttribute(\'data-action\') !== \'edit\') window.location.href=this.value;">';

		// Process each link as a menu item
		$menu .= '<option value="" disabled selected>' . esc_html__( 'Select an option', 'forumax' ) . '</option>';
		foreach ( array_filter( $r['links'] ) as $key => $link ) {
			// Extract href attribute from the link
			preg_match( '/href=(["\'])([^"\']+)\\1/', $link, $matches );
			$href = ! empty( $matches[2] ) ? $matches[2] : '';

			// Add data-action attribute so JS can identify actions (e.g. "edit") regardless of language.
			$menu .= '<option value="' . esc_url( $href ) . '" class="bbp-admin-dropdown-item" data-action="' . esc_attr( $key ) . '">' . wp_strip_all_tags( $link ) . '</option>';
		}

		$menu .= '</select>';

		$retval = $r['before'] . $menu . $r['after'];

		// Filter & return
		if ( is_user_logged_in() ) {
			return apply_filters( 'forumax_bbp_get_reply_admin_links', $retval, $r, $args );
		}
	}
}

/**
 * Similar function for topics - to handle the case where a topic is passed to the reply function
 */
if ( ! function_exists( 'forumax_get_topic_admin_links' ) ) {
	/**
	 * Get topic admin links as a dropdown.
	 *
	 * @param array $args Arguments for the admin links.
	 * @return string|void Admin links HTML.
	 */
	function forumax_get_topic_admin_links( $args = [] ) {
		// Parse arguments against default values
		$r = bbp_parse_args( $args, [
			'id'     => 0,
			'before' => '<div class="bbp-admin-links-dropdown">',
			'after'  => '</div>',
			'sep'    => '',
			'links'  => [],
		], 'get_topic_admin_links' );

		$r['id'] = bbp_get_topic_id( $r['id'] );

		// If not a topic, then return
		if ( ! bbp_is_topic( $r['id'] ) ) {
			return;
		}

		// If no links were passed, get the default ones
		if ( empty( $r['links'] ) ) {
			$r['links'] = apply_filters( 'bbp_topic_admin_links', [
				'edit'    => bbp_get_topic_edit_link( $r ),
				'close'   => bbp_get_topic_close_link( $r ),
				'stick'   => bbp_get_topic_stick_link( $r ),
				'merge'   => bbp_get_topic_merge_link( $r ),
				'trash'   => bbp_get_topic_trash_link( $r ),
				'spam'    => bbp_get_topic_spam_link( $r ),
				'approve' => bbp_get_topic_approve_link( $r ),
				'reply'   => bbp_get_topic_reply_link( $r ),
			], $r['id'] );
		}

		// See if links need to be unset
		$topic_status = bbp_get_topic_status( $r['id'] );
		if ( in_array( $topic_status, [ bbp_get_spam_status_id(), bbp_get_trash_status_id(), bbp_get_pending_status_id() ], true ) ) {

			// Spam link shouldn't be visible on trashed topics
			if ( bbp_get_trash_status_id() === $topic_status ) {
				unset( $r['links']['spam'] );

			// Trash link shouldn't be visible on spam topics
			} elseif ( bbp_get_spam_status_id() === $topic_status ) {
				unset( $r['links']['trash'] );
			}
		}

		// Build our dropdown menu structure
		$menu  = '<select name="topic-admin-links" class="frmx-nice-select bbp-admin-dropdown-menu" onchange="if(this.value && this.options[this.selectedIndex].getAttribute(\'data-action\') !== \'edit\') window.location.href=this.value;">';
		$menu .= '<option value="" disabled selected>' . esc_html__( 'Select an option', 'forumax' ) . '</option>';

		// Process each link as a menu item
		foreach ( array_filter( $r['links'] ) as $key => $link ) {
			// Extract href attribute from the link
			preg_match( '/href=(["\'])([^"\']+)\\1/', $link, $matches );
			$href = ! empty( $matches[2] ) ? $matches[2] : '';

			// Add data-action attribute so JS can identify actions (e.g. "edit") regardless of language.
			$menu .= '<option value="' . esc_url( $href ) . '" class="bbp-admin-dropdown-item" data-action="' . esc_attr( $key ) . '">' . wp_strip_all_tags( $link ) . '</option>';
		}

		$menu .= '</select>';

		$retval = $r['before'] . $menu . $r['after'];

		// Filter & return
		return apply_filters( 'forumax_bbp_get_topic_admin_links', $retval, $r, $args );
	}
}

/**
 * Enqueue the script for sorting bbPress replies
 */
if ( ! function_exists( 'forumax_enqueue_bbp_replies_sorting_script' ) ) {
	/**
	 * Enqueue replies sorting script.
	 */
	function forumax_enqueue_bbp_replies_sorting_script() {
		wp_localize_script( 'bbp-replies-sorting', 'bbp_reply_ajax_obj', [
			'ajax_url'     => admin_url( 'admin-ajax.php' ),
			'bbp_topic_id' => get_the_ID(),
		] );
	}
	add_action( 'wp_enqueue_scripts', 'forumax_enqueue_bbp_replies_sorting_script' );
}

if ( ! function_exists( 'forumax_ajax_sort_bbp_replies' ) ) {
	/**
	 * AJAX handler for sorting replies.
	 */
	function forumax_ajax_sort_bbp_replies() {
		check_ajax_referer( 'forumax-nonce', 'nonce' );

		if ( empty( $_POST['topic_id'] ) ) {
			wp_send_json_error( [ 'message' => 'No topic ID provided.' ] );
		}
		$topic_id = intval( $_POST['topic_id'] );
		$sort     = isset( $_POST['sort'] ) ? sanitize_text_field( wp_unslash( $_POST['sort'] ) ) : 'desc';

		// Set $_GET['sort'] for the filter to pick up
		$_GET['sort'] = $sort;

		// Start output buffering to capture the replies loop HTML
		ob_start();
		// Set up bbPress replies loop manually for AJAX context
		$replies_args = [
			'post_parent'    => $topic_id,
			'post_type'      => bbp_get_reply_post_type(),
			'orderby'        => ( 'vote' === $sort ? 'meta_value_num' : 'date' ),
			'order'          => ( 'asc' === $sort ? 'ASC' : 'DESC' ),
			'meta_key'       => ( 'vote' === $sort ? 'bbp_voting_score' : '' ),
			'posts_per_page' => -1,
		];
		if ( bbp_has_replies( $replies_args ) ) {
			while ( bbp_replies() ) :
				bbp_the_reply();
				$template_file = plugin_dir_path( __FILE__ ) . '../templates/loop-single-reply.php';
				if ( file_exists( $template_file ) ) {
					include $template_file;
				}
			endwhile;
		} else {
			echo '<div>No replies found.</div>';
		}
		$html = ob_get_clean();

		wp_send_json_success( [ 'html' => $html ] );
	}
	add_action( 'wp_ajax_sort_bbp_replies', 'forumax_ajax_sort_bbp_replies' );
	add_action( 'wp_ajax_nopriv_sort_bbp_replies', 'forumax_ajax_sort_bbp_replies' );
}

/**
 * Remove unnecessary pipe separator from bbPress subscription links.
 */
add_filter( 'bbp_get_user_subscribe_link', 'forumax_remove_subscribe_separator', 10, 1 );

/**
 * Remove subscribe separator.
 *
 * @param string $html The HTML.
 * @return string Modified HTML.
 */
function forumax_remove_subscribe_separator( $html ) {
	$html = str_replace( '&nbsp;|&nbsp;', '', $html );
	return $html;
}

/**
 * Restrict visibility of the "modified" notice to the author only.
 *
 * @param string $log The log output.
 * @param int    $post_id The post ID.
 * @return string The log if allowed, empty string otherwise.
 */
function forumax_restrict_revision_log_visibility( $log, $post_id ) {
	if ( ! is_user_logged_in() ) {
		return '';
	}

	$current_user_id = bbp_get_current_user_id();
	$post            = get_post( $post_id );

	if ( ! empty( $post ) && ( int ) $post->post_author === ( int ) $current_user_id ) {
		return $log;
	}

	return '';
}
add_filter( 'bbp_get_reply_revision_log', 'forumax_restrict_revision_log_visibility', 10, 2 );
add_filter( 'bbp_get_topic_revision_log', 'forumax_restrict_revision_log_visibility', 10, 2 );
