<?php
/**
 * Disconnect class handler
 *
 * @package um_ext\um_social_login\core\Social_Login_Disconnect
 */

namespace um_ext\um_social_login\core;

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

/**
 * Class Social_Login_Disconnect
 *
 * @package um_ext\um_social_login\core
 */
class Social_Login_Disconnect {


	/**
	 * Social Network Providers
	 *
	 * @var $networks
	 */
	public $networks;


	/**
	 * Social_Login_Disconnect constructor.
	 */
	public function __construct() {

		add_action( 'template_redirect', array( $this, 'init' ) );

	}

	/**
	 * Handle disconnect
	 */
	public function init() {
		if ( ! isset( $_REQUEST['disconnect'] ) || ! is_user_logged_in() ) { //phpcs:ignore WordPress.Security.NonceVerification
			return;
		}

		$nonce = sanitize_key( 'um-sso-disconnect-' . $_REQUEST['disconnect'] ); //phpcs:ignore WordPress.Security.NonceVerification
		if ( ! isset( $_REQUEST['_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['_nonce'] ), $nonce ) ) {
			wp_die( esc_attr__( 'Security Check!', 'um-social-login' ) );
		}

		$uid = null;

		$uid = get_current_user_id();
 		//phpcs:disable WordPress.Security.NonceVerification
		if ( current_user_can( 'manage_options' ) ) {
			if ( isset( $_REQUEST['uid'] ) && get_current_user_id() !== $_REQUEST['uid'] ) {
				$uid = absint( $_REQUEST['uid'] );
			}
		} elseif ( isset( $_REQUEST['uid'] ) && get_current_user_id() !== $_REQUEST['uid'] ) {
			wp_die( esc_attr__( 'Ehh! hacking?', 'um-social-login' ) );
		}
		//phpcs:enable WordPress.Security.NonceVerification

		$provider = sanitize_key( $_REQUEST['disconnect'] ); //phpcs:ignore WordPress.Security.NonceVerification

		$networks = UM()->Social_Login_API()->available_networks();

		foreach ( $networks[ $provider ]['sync'] as $k => $v ) {
			delete_user_meta( $uid, $k );
		}

		foreach ( $networks[ $provider ]['sync_v2'] as $k => $v ) {
			delete_user_meta( $uid, $k );
		}

		delete_user_meta( $uid, "_uid_{$provider}" );

		do_action( 'um_social_login_after_disconnect', $provider, $uid );
		do_action( "um_social_login_after_{$provider}_disconnect", $uid );

		um_safe_redirect( UM()->account()->tab_link( 'social' ) );

	}

}
