<?php
/**
 * Connect Hooks
 *
 * @package UM_Social_Login_API
 */

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

/**
 * Set Login callback url for Single-callback network/provider
 *
 * @param string $callback_url Callback URL.
 * @param string $provider     Provider slug.
 */
function um_social_login_callback_url( $callback_url, $provider ) {
	$networks = array_keys( UM()->Social_Login_API()->get_single_callback_networks() );
	if ( ! in_array( $provider, $networks, true ) ) {
		return $callback_url;
	}

	$callback_url = um_get_core_page( 'login' );
	$callback_url = add_query_arg( 'provider', $provider, $callback_url );

	return $callback_url;
}
add_filter( 'um_social_login_callback_url', 'um_social_login_callback_url', 10, 2 );

/**
 * Set Login Return Url for Single-callback network/provider
 *
 * @param string $return_url   Return URL.
 * @param string $provider     Provider slug.
 */
function um_social_login_return_url( $return_url, $provider ) {
	$networks = array_keys( UM()->Social_Login_API()->get_single_callback_networks() );
	if ( ! in_array( $provider, $networks, true ) ) {
		return $return_url;
	}

	$sso_session = UM()->Social_Login_API()->hybridauth()->session();
	$return_url  = $sso_session->get( 'um_sso_current_url' );

	$return_url = add_query_arg( 'return_provider', $provider, $return_url );
	$return_url = remove_query_arg( 'err', $return_url );

	return $return_url;
}
add_filter( 'um_social_login_window_process_error_return_url', 'um_social_login_return_url', 10, 2 );
add_filter( 'um_social_login_return_url', 'um_social_login_return_url', 10, 2 );


/**
 * Set Connect Url for Single-callback network/provider
 *
 * @param string $connect_url  Connect URL.
 * @param string $provider     Provider slug.
 */
function um_social_login_connect_url( $connect_url, $provider ) {
	$networks = array_keys( UM()->Social_Login_API()->get_single_callback_networks() );
	if ( ! in_array( $provider, $networks, true ) ) {
		return $connect_url;
	}

	$return_url = UM()->Social_Login_API()->hybridauth()->get_current_url();

	$sso_session = UM()->Social_Login_API()->hybridauth()->session();
	$sso_session->set( 'sso_last_auth_page', $return_url );

	return $connect_url;
}
add_filter( 'um_social_login_connect_url', 'um_social_login_connect_url', 10, 2 );


/**
 * Make register fields hidden for One-step process
 *
 * @param array   $fields Fields data.
 * @param integer $base_form_id Form ID.
 */
function um_sso_make_fields_hidden( $fields, $base_form_id ) {
	if ( empty( $fields ) ) {
		return $fields;
	}

	if ( isset( $_REQUEST['return_provider'] ) ) { //phpcs:ignore  WordPress.Security.NonceVerification
		$mode = isset( UM()->fields()->set_mode ) ? UM()->fields()->set_mode : null;

		if ( 'login' === $mode ) {
			return $fields;
		}

		$form_id = UM()->Social_Login_API()->user_connect()->form_id();
		if ( $base_form_id !== $form_id ) {
			return $fields;
		}

		$step_process = UM()->Social_Login_API()->user_connect()->get_enabled_step_process( $form_id );
		if ( '' === $step_process || 1 === absint( $step_process ) ) {
			return $fields;
		}

		// Remove submit button.
		remove_action( 'um_after_register_fields', 'um_add_submit_button_to_register', 1000 );
		add_filter( 'um_register_form_button_two_url', '__return_empty_string' );

		$profile = UM()->Social_Login_API()->user_connect()->user_profile;

		foreach ( $fields as $field_key => $field_value ) {

			if ( strpos( $field_key, '_um_row' ) !== false || strpos( $field_key, 'um_block' ) !== false ) {

				$fields[ $field_key ] = $field_value;

			} else {
				$field_value['type'] = 'hidden';

				$fields[ $field_key ] = $field_value;
			}

			if ( isset( $field_value['sso_sync_value'] ) ) {
				// Email Address.
				if ( 'user_email' === $field_key && isset( $profile->{$field_value['sso_sync_value']} ) ) {
					if ( email_exists( $profile->{$field_value['sso_sync_value']} ) ) {
						unset( $fields['user_email'] );
					}
				}

				// Username.
				if ( 'user_login' === $field_key && isset( $profile->{$field_value['sso_sync_value']} ) ) {
					if ( username_exists( $profile->{$field_value['sso_sync_value']} ) ) {
						$profile->{$field_value['sso_sync_value']}   = UM()->Social_Login_API()->generate_unique_username( $profile->{$field_value['sso_sync_value']} );
						$_SESSION['um_social_profile'][ $field_key ] = $profile->{$field_value['sso_sync_value']};
					}
				}
			}

			// User login/email.
			if ( ! in_array( $field_key, array( 'user_login', 'user_email' ), true ) ) {
				unset( $fields[ $field_key ]['required'] );
				unset( $fields[ $field_key ]['validate'] );
			}
		}
	}

	return $fields;
}
add_filter( 'um_get_form_fields', 'um_sso_make_fields_hidden', 100, 2 );

/**
 * Add fallback for first and last name
 *
 * @param string $key Field key.
 * @param string $sso_sync_value Field key.
 * @param array  $field Field data.
 * @param object $profile Profile Data.
 * @param string $provider Provider slug.
 */
function um_sso_returned_raw_data( $key, $sso_sync_value, $field, $profile, $provider ) {
	if ( 'first_name' === $key ) {
		if ( empty( $sso_sync_value ) ) {
			$display_name                   = $profile->displayName; //phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
			list( $first_name, $last_name ) = explode( ' ', $display_name );
			$sso_sync_value                 = $first_name;
		}

		if ( empty( $sso_sync_value ) ) {
			$sso_sync_value = $profile->identifier;
		}
	}

	if ( 'last_name' === $key ) {
		if ( empty( $sso_sync_value ) ) {
			$display_name     = $profile->displayName; //phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
			$arr_display_name = explode( ' ', $display_name );
			if ( count( $arr_display_name ) >= 2 ) {
				list( $first_name, $last_name ) = $arr_display_name;
			}
			$sso_sync_value = $last_name;
		}

		if ( empty( $sso_sync_value ) ) {
			$sso_sync_value = $provider;
		}
	}

	if ( 'user_email' === $key ) {
		if ( empty( $sso_sync_value ) && apply_filters( 'um_sso_generate_email', true ) ) {
			$unique_user_id = UM()->query()->count_users( true ) + 1;
			$site_url       = @$_SERVER['SERVER_NAME']; //phpcs:ignore

			$email_prefix = apply_filters( 'um_sso_generate_email_address', "nobody{$unique_user_id}", $unique_user_id, $site_url );
			$email_domain = apply_filters( 'um_sso_generate_email_domain', $site_url );

			$sso_sync_value = $email_prefix . '@' . $email_domain;
		}
	}

	return $sso_sync_value;
}
add_filter( 'um_sso_returned_raw_data', 'um_sso_returned_raw_data', 10, 5 );

/**
 * Disable SSO fields when users cannot edit the field
 *
 * @param string $disabled Disabled value.
 * @param array  $data field data.
 *
 * @return string
 */
function um_sso_disable_fields( $disabled, $data ) {
	// It's for a legacy case `array_key_exists( 'editable', $data )`.
	if ( array_key_exists( 'editable', $data ) && empty( $data['editable'] ) && isset( $_REQUEST['return_provider'] ) && ! isset( $_REQUEST['err'] ) ) { //phpcs:ignore  WordPress.Security.NonceVerification
		$disabled = " disabled='disabled' ";
	}
	return $disabled;
}
add_filter( 'um_is_field_disabled', 'um_sso_disable_fields', 10, 2 );
