<?php
/**
 * Common functions only loaded on AJAX requests.
 *
 * @since 3.0.0
 * @version 8.0.0
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Load the template loop for the current object.
 *
 * @since 3.0.0
 *
 * @return string Template loop for the specified object
 */
function bp_nouveau_ajax_object_template_loader() {
	if ( ! bp_is_post_request() ) {
		wp_send_json_error();
	}

	if ( empty( $_POST['object'] ) ) {
		wp_send_json_error();
	}

	$object = sanitize_title( $_POST['object'] );
	$component = $object;

	$template = '';
	if (isset($_POST['template'])) {
		$template = $_POST['template'];
	}
	$is_group_activity = (0 === strpos($object, 'group_activity_'));
	if ($is_group_activity) {
		$component = 'activity';
	}
	$is_group_members = (0 === strpos($object, 'group_members_'));
	if ($is_group_members) {
		$component = 'members';
		$template = 'group_members';
	}

	// Nonce check!
	if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'bp_nouveau_' . $component ) ) {
		wp_send_json_error();
	}

	$scope = '';
	if (isset($_POST['scope'])) {
		$scope = $_POST['scope'];
	}

	$args = false;
	if ($is_group_activity) {
		$activity_args = bp_parse_args(bp_ajax_querystring( 'activity' ));
		$activity_args['excluded_types'] = array('joined_group');	// do not show "a member has joined the group" activities
		$activity_args['pinned'] = 'exclude-pinned';
		$activity_args['object'] = 'groups';

		$group_id = intval(substr($object, strlen('group_activity_')));
		$activity_args['primary_id'] = $group_id;

		if (!empty($_POST['last_id'])) {
			$activity_args['filter_query'] = array(
				'relation' => 'AND',
				'last_id' => array(
					'column' => 'id',
					'compare' => '<',
					'value' => intval($_POST['last_id'])
					),
				);
		}
		$args = array('r' => $activity_args);

		$group = groups_get_group($group_id);
		if (!empty($group)) {
			$args['group_id'] = $group_id;
		}
	} elseif ($is_group_members) {
		$group_id = intval(substr($object, strlen('group_members_')));
		$base_url = CommunityAlly_Groups_Setup::get_group_permalink($group_id);
		$args = array('group_id' => $group_id, 'base_url' => $base_url . 'members/');
	}
	$result = communityally_activity_template_loader($component, $scope, $template, $args);
	if (false === $result) {
		wp_send_json_error();
	}
	// Locate the object template.
	wp_send_json_success( $result );
}
