<?php
/**
 * User Notes functionality for Clicks User Manager.
 *
 * @package WP_User_Management
 */

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

/**
 * Register AJAX handlers for notes.
 */
add_action( 'wp_ajax_wpum_get_notes', 'wpum_handle_get_notes' );
add_action( 'wp_ajax_wpum_add_note', 'wpum_handle_add_note' );
add_action( 'wp_ajax_wpum_delete_note', 'wpum_handle_delete_note' );
add_action( 'wp_ajax_wpum_bulk_add_note', 'wpum_handle_bulk_add_note' );

/**
 * Retrieve notes for a specific user.
 *
 * @param int $user_id User ID.
 * @return array Array of notes.
 */
function wpum_get_user_notes( $user_id ) {
	$notes = get_user_meta( $user_id, '_wpum_notes', true );
	return is_array( $notes ) ? $notes : array();
}

/**
 * Handle AJAX request to fetch notes.
 */
function wpum_handle_get_notes() {
	check_ajax_referer( 'wpum_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied.', 'clicks-user-manager' ) ) );
	}

	$user_id = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;
	if ( ! $user_id ) {
		wp_send_json_error( array( 'message' => __( 'Invalid user ID.', 'clicks-user-manager' ) ) );
	}

	$notes = wpum_get_user_notes( $user_id );

	// Format timestamps for display
	foreach ( $notes as &$note ) {
		$note['display_date'] = mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $note['timestamp'] );
	}

	wp_send_json_success( array(
		'notes'    => $notes,
		'is_pro'   => wpum_is_pro(),
		'can_add'  => wpum_is_pro() || count( $notes ) < 3,
		'note_qty' => count( $notes ),
	) );
}

/**
 * Handle AJAX request to add a note.
 */
function wpum_handle_add_note() {
	check_ajax_referer( 'wpum_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied.', 'clicks-user-manager' ) ) );
	}

	$user_id   = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;
	$note_text = isset( $_POST['note'] ) ? sanitize_textarea_field( wp_unslash( $_POST['note'] ) ) : '';

	if ( ! $user_id ) {
		wp_send_json_error( array( 'message' => __( 'Invalid user ID.', 'clicks-user-manager' ) ) );
	}

	if ( empty( $note_text ) ) {
		wp_send_json_error( array( 'message' => __( 'Note content cannot be empty.', 'clicks-user-manager' ) ) );
	}

	$notes = wpum_get_user_notes( $user_id );

	// Enforce Free limit of 3 notes per user
	if ( ! wpum_is_pro() && count( $notes ) >= 3 ) {
		wp_send_json_error( array(
			'message' => __( 'Free version limit reached: Upgrade to Pro for unlimited notes.', 'clicks-user-manager' ),
			'is_limit_reached' => true
		) );
	}

	$current_user = wp_get_current_user();
	$new_note = array(
		'id'          => uniqid( 'note_', true ),
		'text'        => $note_text,
		'author'      => $current_user->display_name ? $current_user->display_name : $current_user->user_login,
		'timestamp'   => current_time( 'mysql' ),
	);

	$notes[] = $new_note;
	update_user_meta( $user_id, '_wpum_notes', $notes );

	$new_note['display_date'] = mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $new_note['timestamp'] );

	wp_send_json_success( array(
		'message'  => __( 'Note added successfully.', 'clicks-user-manager' ),
		'note'     => $new_note,
		'can_add'  => wpum_is_pro() || count( $notes ) < 3,
		'note_qty' => count( $notes ),
	) );
}

/**
 * Handle AJAX request to delete a note.
 */
function wpum_handle_delete_note() {
	check_ajax_referer( 'wpum_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied.', 'clicks-user-manager' ) ) );
	}

	$user_id = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;
	$note_id = isset( $_POST['note_id'] ) ? sanitize_key( $_POST['note_id'] ) : '';

	if ( ! $user_id || empty( $note_id ) ) {
		wp_send_json_error( array( 'message' => __( 'Invalid parameters.', 'clicks-user-manager' ) ) );
	}

	$notes = wpum_get_user_notes( $user_id );
	$updated_notes = array();
	$found = false;

	foreach ( $notes as $note ) {
		if ( $note['id'] === $note_id ) {
			$found = true;
			continue;
		}
		$updated_notes[] = $note;
	}

	if ( $found ) {
		update_user_meta( $user_id, '_wpum_notes', $updated_notes );
		wp_send_json_success( array(
			'message'  => __( 'Note deleted successfully.', 'clicks-user-manager' ),
			'can_add'  => wpum_is_pro() || count( $updated_notes ) < 3,
			'note_qty' => count( $updated_notes ),
		) );
	} else {
		wp_send_json_error( array( 'message' => __( 'Note not found.', 'clicks-user-manager' ) ) );
	}
}

/**
 * Handle AJAX request to bulk add a note to selected users (Pro feature).
 */
function wpum_handle_bulk_add_note() {
	check_ajax_referer( 'wpum_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied.', 'clicks-user-manager' ) ) );
	}

	// Enforce Pro only for bulk actions
	if ( ! wpum_is_pro() ) {
		wp_send_json_error( array( 'message' => __( 'Bulk notes are a Premium feature. Please upgrade to Pro.', 'clicks-user-manager' ) ) );
	}

	$user_ids  = isset( $_POST['user_ids'] ) ? array_map( 'absint', (array) $_POST['user_ids'] ) : array();
	$note_text = isset( $_POST['note'] ) ? sanitize_textarea_field( wp_unslash( $_POST['note'] ) ) : '';

	if ( empty( $user_ids ) ) {
		wp_send_json_error( array( 'message' => __( 'No users selected.', 'clicks-user-manager' ) ) );
	}

	if ( empty( $note_text ) ) {
		wp_send_json_error( array( 'message' => __( 'Note content cannot be empty.', 'clicks-user-manager' ) ) );
	}

	$current_user = wp_get_current_user();
	$success_count = 0;

	foreach ( $user_ids as $user_id ) {
		$notes = wpum_get_user_notes( $user_id );
		$new_note = array(
			'id'          => uniqid( 'note_', true ),
			'text'        => $note_text,
			'author'      => $current_user->display_name ? $current_user->display_name : $current_user->user_login,
			'timestamp'   => current_time( 'mysql' ),
		);
		$notes[] = $new_note;
		update_user_meta( $user_id, '_wpum_notes', $notes );
		$success_count++;
	}

	wp_send_json_success( array(
		/* translators: %d: number of users notes added to */
		'message' => sprintf( _n( 'Note added to %d user.', 'Note added to %d users.', $success_count, 'clicks-user-manager' ), $success_count ),
	) );
}
