<?php
/**
 * Notification ajax actions
 *
 * @since CommunityAlly 1.0.0
 */

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

add_action( 'admin_init', function() {
	$ajax_actions = array(
		array(
			'notification_mark_read' => array(
				'function' => 'communityally_ajax_mark_notification_read',
				'nopriv'   => false,
			),
		),
	);

	foreach ( $ajax_actions as $ajax_action ) {
		$action = key( $ajax_action );

		add_action( 'wp_ajax_' . $action, $ajax_action[ $action ]['function'] );

		if ( ! empty( $ajax_action[ $action ]['nopriv'] ) ) {
			add_action( 'wp_ajax_nopriv_' . $action, $ajax_action[ $action ]['function'] );
		}
	}
}, 12 );

// Marks a specific notification as read
function communityally_ajax_mark_notification_read() {
	if ( ! bp_is_post_request() ) {
		wp_send_json_error();
	}

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

	$notification_id = intval($_POST['notification_id']);

	bp_notifications_mark_notification($notification_id);
	wp_send_json_success();
}