<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
add_action( 'wp_ajax_nopriv_sifency_register_user', 'sifency_ajax_register' );
add_action( 'wp_ajax_sifency_register_user', 'sifency_ajax_register' );

function sifency_ajax_register() {
	if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'sifency_reg_nonce' ) ) {
		wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
	}

	$username = sanitize_user( $_POST['username'] );
	$email    = sanitize_email( $_POST['email'] );
	$password = $_POST['password'];
	$fname    = sanitize_text_field( $_POST['fname'] );
	$lname    = sanitize_text_field( $_POST['lname'] );

	if ( username_exists( $username ) || email_exists( $email ) ) {
		wp_send_json_error( array( 'message' => 'Username or Email already exists.' ) );
	}

	$user_id = wp_create_user( $username, $password, $email );

	if ( is_wp_error( $user_id ) ) {
		wp_send_json_error( array( 'message' => $user_id->get_error_message() ) );
	}
	if ( ! empty( $fname ) ) {
		update_user_meta( $user_id, 'first_name', $fname );
	}
	if ( ! empty( $lname ) ) {
		update_user_meta( $user_id, 'last_name', $lname );
	}

	if ( 'yes' === $_POST['auto_login'] ) {
		wp_set_current_user( $user_id );
		wp_set_auth_cookie( $user_id );
	}

	wp_send_json_success(
		array(
			'message'  => 'Registration successful! Redirecting...',
			'redirect' => $_POST['redirect_to'],
		)
	);
}
