<?php
/**
 * Setup Permalinks
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Resets;

defined( 'ABSPATH' ) || die( 'Shame on you' );

/**
 * Reset and optimize permalinks. Make all the permalinks app-friendly
 */
class Permalinks {
	/**
	 * Constructor. Sets up filters and actions.
	 */
	public function __construct() {
		add_filter( 'bp_get_group_permalink', [ $this, 'set_groups_permalink' ], 10, 2 );
		add_filter( 'bp_core_get_user_domain', [ $this, 'set_members_permalink' ], 10, 2 );

		add_filter( 'post_type_link', [ $this, 'replace_post_id' ], 1, 3 );
		add_action( 'init', [ $this, 'prefix_page' ] );
	}

	/**
	 * Filter permalink.
	 *
	 * @param string  $post_link The post's permalink.
	 * @param WP_Post $post      The post in question.
	 * @param bool    $leavename Whether to keep the post name.
	 *
	 * @return string Filtered permalink
	 */
	public function replace_post_id( $post_link, $post = 0, $leavename = false ) {
		if ( strpos( '%post_id%', $post_link ) === 'false' ) {
			return $post_link;
		}

		if ( is_object( $post ) ) {
			$post_id = $post->ID;
		} else {
			$post_id = $post;
			$post    = get_post( $post_id );
		}

		if ( ! is_object( $post ) ) {
			return $post_link;
		}

		// put post ID in place of %post_id%.
		return str_replace( '%post_id%', $post_id, $post_link );
	}

	/**
	 * Prefix page slug with page
	 */
	public function prefix_page() {
		global $wp_rewrite;

		$wp_rewrite->page_structure = $wp_rewrite->root . 'page/%pagename%';
	}


	/**
	 * Set groups permalink.
	 *
	 * @param string $link  Group link.
	 * @param object $group Group.
	 *
	 * @return string Group Permalink structure
	 */
	public function set_groups_permalink( $link, $group ) {
		return trailingslashit( bp_get_groups_directory_permalink() . $group->id . '/' );
	}

	/**
	 * Set members permalink.
	 *
	 * @param string $domain  Members domain.
	 * @param object $user_id Current member id.
	 *
	 * @return string Members Permalink structure
	 */
	public function set_members_permalink( $domain, $user_id ) {
		$after_domain = bp_core_enable_root_profiles() ? $user_id : bp_get_members_root_slug() . '/' . $user_id;
		$domain       = trailingslashit( bp_get_root_domain() . '/' . $after_domain );

		return $domain;
	}
}

new Permalinks();
