<?php
function get_member_wp_creation(){
    $html = "";
    ob_start();
    ?>
    <form name="register_wp_member" id="register_wp_member">
		<h3><?php _e( 'Register Member' ); ?></h3>
		<div class="form-group">
            <label for="email"><?php _e('Enter email *', CIP_TXTDOMAIN); ?></label>
			<input type="email" class="form-control" name="email" id="email" required />
		</div>
        <div class="autofillsection hide">
            <div class="form-group">
                <label for="username"><?php _e('Enter username *', CIP_TXTDOMAIN); ?></label>
                <input type="text" class="form-control" placeholder="" name="username" id="username" required />
            </div>
            <div class="form-group">
                <label for="first_name"><?php _e('Enter first name *', CIP_TXTDOMAIN); ?></label>
                <input type="text" class="form-control" placeholder="" name="first_name" id="first_name" required />
            </div>
            <div class="form-group">
                <label for="last_name"><?php _e('Enter last name *', CIP_TXTDOMAIN); ?></label>
                <input type="text" class="form-control" placeholder="" name="last_name" id="last_name" required />
            </div>
            <button type="submit" class="btn btn-primary"><?php _e('Register', CIP_TXTDOMAIN); ?></button>
        </div>
		<input type="hidden" name="action" value="smcreate_wp_member_action" />
		<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPSMCreateWPMemberUserCIP_'); ?>" />

	</form>
    <?php
	$html .= ob_get_clean();
	return $html;
}
add_action( 'wp_ajax_smcreate_wp_member_action', 'cip_smcreate_wp_member_action_callback' );
function cip_smcreate_wp_member_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		if( wp_verify_nonce( $_POST['_micro'], '_CIPSMCreateWPMemberUserCIP_' ) ){
			
            if( !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ){
                $out = array( "error" => 1,'msg' => __('Please enter valid email address.',CIP_TXTDOMAIN) );
                echo wp_json_encode( $out );
	            exit;
            }

            if( !email_exists( $_POST['email'] )) {
                if( !empty( $_POST['email'] ) && $_POST['getDetails'] == 'yes' ){
    
                    $body = [
                        'email'	=>	$_POST['email'],
                    ];
                    $response = amplivo_api_send_requests( $body, 'get-user-data');
    
                    $username = "";
                    $first_name = "";
                    $last_name = "";
                    if( $response['success'] == true ){
                        $result = $response['result'];
                        $username = $result['Username'];
                        $first_name = $result['user_first_name'];
                        $last_name = $result['user_last_name'];
                    }
    
                    $out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'username' => $username, 'first_name' => $first_name, 'last_name' => $last_name );
                }else if( !empty( $_POST['email'] ) && !empty( $_POST['username'] ) && !empty( $_POST['first_name'] ) && !empty( $_POST['last_name'] ) && $_POST['getDetailsRegister'] == 'yes' ){
    
                    $username = $_POST['username'];
                    $username_counter = 0;
                    $newUsername = $username;
                    //check in wordpress user
                    do{
                        $exists_wp = check_username_in_wp($username);
                        if( $exists_wp ){
                            $username_counter++;
                            $username = $newUsername . $username_counter;
                        }
                    }while($exists_wp);

                    $user_password = wp_generate_password( 12, false );
					$user = wp_create_user( $username, $user_password, $_POST['email'] );
					if( !is_wp_error($user) ){
                        $user = get_user_by( 'email', $_POST['email'] );
                        if( $user instanceof WP_User ) {
                            $user->add_role( 'member' );
                            $user->remove_role( 'subscriber' );
                            $user_id = $user->ID;
                            wp_update_user([
                                'ID'            => $user_id,
                                'first_name'    => $_POST['first_name'],
                                'last_name'     => $_POST['last_name'],
                            ]);
                            update_user_meta( $user_id, 'csrnow_login_enable', 1 );
                        }
                        $logs = sprintf( __('WP Member created(%s) by %s at %s', CIP_TXTDOMAIN), $_POST['email'], $current_user->user_email, date_i18n('d/m/Y H:i A') );
                        create_cip_logs_entery( $user_id, 'member_create', '','sm', $logs, true );
                        $out = array( "error" => 0,'msg' => __('Member created successfully.',CIP_TXTDOMAIN) );

                    }else{
                        $out = array( "error" => 1,'msg' => $user->get_error_message() );
                    }
                }
            }else{
                $out = array( "error" => 1,'msg' => __('Email already registered.',CIP_TXTDOMAIN) );
            }
		}
	}
	echo wp_json_encode( $out );
	exit;
}