<?php
/**
 * Author Kit User Functionality
 *
 * Provides AJAX handlers to add and edit WordPress users
 * with custom validation and user meta management.
 *
 * @package Author_Kit
 * @since 1.0.0
 */

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

/**
 * Handles user-related AJAX functionality for Author Kit.
 *
 * Supports adding and editing users via AJAX requests.
 */
class Author_Kit_User_Functionality {

	/**
	 * Constructor.
	 *
	 * Registers AJAX handler for adding or editing a user.
	 */
	public function __construct() {
		add_action( 'wp_ajax_author_kit_add_or_edit_user', array( $this, 'author_kit_add_or_edit_user' ) );
	}

	/**
	 * Handles AJAX to add or edit a user.
	 *
	 * Checks nonce, permissions, sanitizes input, then creates or updates user.
	 * Supports email change with confirmation, avatar update, and notifications.
	 *
	 * @return void Sends JSON success or error response.
	 */
	public function author_kit_add_or_edit_user() {
		check_ajax_referer( 'author-kit-add-edit-user-nonce', 'nonce' );

		$username            = isset( $_POST['username'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['username'] ) ) : '';
		$email               = isset( $_POST['email'] ) ? (string) sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
		$first_name          = isset( $_POST['first_name'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) : '';
		$last_name           = isset( $_POST['last_name'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) : '';
		$display_name        = isset( $_POST['display_name'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['display_name'] ) ) : $username;
		$password            = isset( $_POST['password'] ) ? sanitize_text_field( wp_unslash( $_POST['password'] ) ) : '';
		$role                = isset( $_POST['role'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['role'] ) ) : '';
		$user_action         = isset( $_POST['user_action'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['user_action'] ) ) : 'add-new';
		$avatar              = isset( $_POST['avatar'] ) ? sanitize_url( wp_unslash( $_POST['avatar'] ) ) : '';
		$email_notifications = isset( $_POST['emailNotifications'] ) ? filter_var( sanitize_text_field( wp_unslash( $_POST['emailNotifications'] ) ), FILTER_VALIDATE_BOOLEAN ) : true;
		$user_id             = isset( $_POST['user_id'] ) ? intval( sanitize_text_field( wp_unslash( $_POST['user_id'] ) ) ) : 0; // User ID for updates.

		$success_message = __( 'User Updated Successfully.', 'author-kit' ); // Default success message.

		if ( 'edit' === $user_action && $user_id > 0 ) {

			if ( ! current_user_can( 'edit_users' ) ) {
				wp_send_json_error( array( 'message' => __( 'Permission Denied', 'author-kit' ) ) );
			}

			// Get current user data.
			$current_user = get_userdata( $user_id );
			if ( ! $current_user ) {
				wp_send_json_error( array( 'message' => __( 'Invalid user ID.', 'author-kit' ) ) );
			}

			$current_email   = $current_user->user_email;
			$current_user_id = get_current_user_id();

			// Check if role is valid.
			$all_roles = get_editable_roles();
			if ( ! array_key_exists( $role, $all_roles ) ) {
				wp_send_json_error( array( 'message' => __( 'Invalid Role Specified.', 'author-kit' ) ) );
			}

			// Prepare user data for update (excluding email initially).
			$userdata = array(
				'ID'           => $user_id,
				'role'         => $role,
				'display_name' => $display_name,
				'nickname'     => $first_name,
				'first_name'   => $first_name,
				'last_name'    => $last_name,
			);

			// Admins updating other users should update email directly.
			if ( $email !== $current_email && ! empty( $email ) ) {
				if ( email_exists( $email ) ) {
					wp_send_json_error( array( 'message' => __( 'Email Already Exists.', 'author-kit' ) ) );
				}

				// If editing self, require confirmation; if editing another user, update immediately.
				if ( $current_user_id === $user_id ) {
					update_user_meta(
						$user_id,
						'_new_email',
						array(
							'newemail' => $email,
							'hash'     => wp_generate_password( 20, false ),
						)
					);
					$success_message = __( 'User Updated. Confirm Email via Link Sent to New Address', 'author-kit' );

					unset( $userdata['role'] );
				} else {
					$userdata['user_email'] = $email; // Update immediately if admin edits another user.
				}
			}

			if ( $current_user_id === $user_id ) {
				unset( $userdata['role'] );
			}

			// Update user.
			$result = wp_update_user( $userdata );

			if ( is_wp_error( $result ) ) {
				wp_send_json_error( array( 'message' => $result->get_error_message() ) );
			}

			// Update avatar only if provided.
			if ( ! empty( $avatar ) ) {
				update_user_meta( $user_id, 'author_kit_custom_avatar_url', $avatar );
			} elseif ( metadata_exists( 'user', $user_id, 'author_kit_custom_avatar_url' ) ) {
				delete_user_meta( $user_id, 'author_kit_custom_avatar_url' );
			}

			wp_send_json_success( array( 'message' => $success_message ) );
		} else {
			if ( ! current_user_can( 'create_users' ) ) {
				wp_send_json_error( array( 'message' => __( 'Permission Denied', 'author-kit' ) ) );
			}
			// Insert new user.
			if ( 'guest' === $role ) {
				$placeholder_email = $username . '@example.com';

				if ( username_exists( $username ) ) {
					wp_send_json_error( array( 'message' => __( 'Username Already Exists.', 'author-kit' ) ) );
				}

				if ( email_exists( $placeholder_email ) ) {
					wp_send_json_error( array( 'message' => __( 'Email Already Exists', 'author-kit' ) ) );
				}

				$password = wp_generate_password( 12, true );

				$userdata = array(
					'user_pass'    => $password,
					'user_login'   => $username,
					'user_email'   => $placeholder_email,
					'role'         => $role,
					'display_name' => $username,
					'nickname'     => $first_name,
					'first_name'   => $first_name,
					'last_name'    => $last_name,
				);
			} else {
				if ( empty( $username ) || empty( $email ) || empty( $password ) ) {
					wp_send_json_error( array( 'message' => __( 'Required Fields are Missing.', 'author-kit' ) ) );
				}

				if ( username_exists( $username ) ) {
					wp_send_json_error( array( 'message' => __( 'Username Already Exists', 'author-kit' ) ) );
				}

				if ( email_exists( $email ) ) {
					wp_send_json_error( array( 'message' => __( 'Email Already Exists', 'author-kit' ) ) );
				}

				// Check if role is valid.
				$all_roles = get_editable_roles();
				if ( ! array_key_exists( $role, $all_roles ) ) {
					wp_send_json_error( array( 'message' => __( 'Invalid Role Specified.', 'author-kit' ) ) );
				}

				$userdata = array(
					'user_pass'    => $password,
					'user_login'   => $username,
					'user_email'   => $email,
					'role'         => $role,
					'display_name' => $username,
					'nickname'     => $first_name,
					'first_name'   => $first_name,
					'last_name'    => $last_name,
				);
			}

			$insert_user_id = wp_insert_user( $userdata );

			if ( is_wp_error( $insert_user_id ) ) {
				wp_send_json_error( array( 'message' => $insert_user_id->get_error_message() ) );
			}

			if ( ! empty( $avatar ) ) {
				update_user_meta( $insert_user_id, 'author_kit_custom_avatar_url', $avatar );
			}

			if ( $email_notifications && 'guest' !== $role ) {
				wp_new_user_notification( $insert_user_id, null, 'both' );
			}

			wp_send_json_success( array( 'message' => __( 'User Added Successfully.', 'author-kit' ) ) );
		}
	}
}

// Initialize the class.
new Author_Kit_User_Functionality();
