<?php
/**
 * WordPress User Helper Functions
 *
 * Provides utility functions for creating WordPress user accounts
 * for club members and querying members that need WP users.
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes
 * @since      1.0.319
 */

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

/**
 * Generate a unique WordPress username from an email address.
 *
 * Extracts the local part (before @), sanitizes it, and appends
 * a numeric suffix if the username already exists.
 *
 * @since 1.0.319
 * @param string $email Email address to derive username from.
 * @return string Unique username string.
 */
function macm_generate_wp_username( $email ) {
	// Extract part before @.
	$parts    = explode( '@', $email );
	$username = sanitize_user( $parts[0], true );

	// Truncate to 50 chars.
	$username = substr( $username, 0, 50 );

	// Fallback if empty after sanitize.
	if ( empty( $username ) ) {
		$username = 'member';
	}

	// Check uniqueness — append suffix if taken.
	$base_username = $username;
	$suffix        = 2;
	while ( username_exists( $username ) ) {
		$username = $base_username . $suffix;
		++$suffix;
	}

	return $username;
}

/**
 * Create a WordPress user account for a club member.
 *
 * Creates the user with the 'customer' role, sets display name,
 * first/last name meta, and sends the new user notification email.
 *
 * @since 1.0.319
 * @param string $email     Valid email address for the new user.
 * @param string $full_name Full name of the member.
 * @return int|WP_Error New user ID on success, WP_Error on failure.
 */
function macm_create_wp_user_for_member( $email, $full_name ) {
	// Validate email.
	if ( ! is_email( $email ) ) {
		return new WP_Error( 'invalid_email', __( 'Invalid email address.', 'martial-arts-club-manager' ) );
	}

	// Check if email is already in use.
	if ( email_exists( $email ) ) {
		return new WP_Error( 'email_exists', __( 'This email address is already registered.', 'martial-arts-club-manager' ) );
	}

	// Generate unique username.
	$username = macm_generate_wp_username( $email );

	// Generate secure password.
	$password = wp_generate_password( 12, true, true );

	// Split full_name into first/last.
	$name_parts = explode( ' ', trim( $full_name ), 2 );
	$first_name = $name_parts[0];
	$last_name  = isset( $name_parts[1] ) ? $name_parts[1] : '';

	// Create user.
	$new_user_id = wp_insert_user(
		array(
			'user_login'   => $username,
			'user_email'   => $email,
			'user_pass'    => $password,
			'display_name' => $full_name,
			'first_name'   => $first_name,
			'last_name'    => $last_name,
			'role'         => 'customer',
		)
	);

	if ( is_wp_error( $new_user_id ) ) {
		return $new_user_id;
	}

	// Send new user notification email with password setup link.
	wp_new_user_notification( $new_user_id, null, 'both' );

	return $new_user_id;
}

/**
 * Get or create a WordPress user for a club member based on email.
 *
 * If the email already belongs to an existing WP user, returns that user ID
 * with action 'linked'. Otherwise creates a new user and returns action 'created'.
 *
 * @since 1.0.320
 * @param string $email     Valid email address.
 * @param string $full_name Full name of the member.
 * @return array|WP_Error Array with 'user_id' and 'action' keys, or WP_Error on failure.
 */
function macm_get_or_create_wp_user_for_member( $email, $full_name ) {
	if ( ! is_email( $email ) ) {
		return new WP_Error( 'invalid_email', __( 'Invalid email address.', 'martial-arts-club-manager' ) );
	}

	$existing_user_id = email_exists( $email );

	if ( $existing_user_id ) {
		return array(
			'user_id' => (int) $existing_user_id,
			'action'  => 'linked',
		);
	}

	$new_user_id = macm_create_wp_user_for_member( $email, $full_name );

	if ( is_wp_error( $new_user_id ) ) {
		return $new_user_id;
	}

	return array(
		'user_id' => (int) $new_user_id,
		'action'  => 'created',
	);
}

/**
 * Get active members that have been auto-assigned to admin and need their own WP user.
 *
 * Returns members where wp_user_auto_assigned = 1 and status = 'active'.
 *
 * @since 1.0.319
 * @return array Array of member row objects (stdClass).
 */
function macm_get_members_needing_wp_user() {
	global $wpdb;

	$results = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT m.* FROM %i m WHERE m.wp_user_auto_assigned = 1 AND m.status = 'active' ORDER BY m.full_name ASC",
			$wpdb->prefix . 'macm_members'
		)
	);

	return $results ? $results : array();
}
