<?php
namespace AcademyProSocialLogin;

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

use Academy\Classes\Sanitizer;
use AcademyPro\Google\Client as Google_Client;

class Hooks {

	public static function init() {
		$self = new self();
		add_action( 'academy/templates/student_reg_form_end', array( $self, 'add_student_social_register' ) );
		add_action( 'academy/templates/instructor_reg_form_end', array( $self, 'add_instructor_social_register' ) );
		add_action( 'wp_ajax_nopriv_academy_pro_social_login/facebook_login', array( $self, 'facebook_login' ) );
		add_action( 'wp_ajax_nopriv_academy_pro_social_login/google_login', array( $self, 'google_login' ) );
		// phpcs:ignore Squiz.PHP.CommentedOutCode.Found
		// add_action( 'login_form', array($self, 'add_social_login') );
	}

	public function add_student_social_register() {
		echo do_shortcode( '[academy_social_login is_register=true]' );
	}
	public function add_instructor_social_register() {
		echo do_shortcode( '[academy_social_login is_register=true role=subscriber]' );
	}

	public function facebook_login() {
		$payload = Sanitizer::sanitize_payload([
			'name' => 'string',
			'first_name' => 'string',
			'last_name' => 'string',
			'email' => 'string',
			'userID' => 'string',
			'access_token' => 'string',
			'is_register' => 'boolean',
			'role' => 'string',
		], $_POST); // phpcs:ignore WordPress.Security.NonceVerification.Missing

		$fb_user_id = $payload['userID'];
		$access_token = $payload['access_token'];
		$role = ( isset( $payload['role'] ) ? $payload['role'] : 'academy_student' );
		$name = $payload['name'];
		$facebook_app_id = \Academy\Helper::get_settings( 'facebook_app_id' );
		$facebook_app_secret = \Academy\Helper::get_settings( 'facebook_app_secret' );

		$user_data = Helper::get_user_profile_info_facebook( $access_token, $facebook_app_id, $facebook_app_secret );
		if ( $fb_user_id !== $user_data['data']['user_id'] || ! $user_data['data']['is_valid'] ) {
			wp_send_json_error( 'Invalid Authorization' );
		}

		$verified_email = Helper::get_user_email_facebook( $user_data['data']['user_id'], $access_token );

		if ( ! empty( $verified_email['email'] ) ) {
			$email = sanitize_email( $verified_email['email'] );

		} else {
			$email = $user_data['data']['user_id'] . '@facebook.com';
		}

		$email = sanitize_email( $email );

		if ( ! $email ) {
			wp_send_json_error( 'Email not provided by Facebook' );
		}

		$user_data = get_user_by( 'email', $email );

		// Login
		if ( ! empty( $user_data ) && false !== $user_data ) {
			$this->set_user_auth_cookie( $user_data );

			$message = __( 'Successfully logged in.', 'academy-pro' );
			if ( $payload['is_register'] ) {
				$message = __( 'You are already registered. Successfully logged in.', 'academy-pro' );
			}
			wp_send_json_success( $message );
		}

		// Register
		if ( ! get_option( 'users_can_register' ) ) {
			wp_send_json_error([
				esc_html__(
					'Sorry, Admin disabled new user registration',
					'academy-pro'
				),
			]);
		}

		$password   = wp_generate_password( 12, true, false );
		$user_login = str_replace( ' ', '_', $name );
		if ( username_exists( $user_login ) ) {
			$suffix     = '-' . zeroise( wp_rand( 0, 9999 ), 4 );
			$user_login .= $suffix;
		}
		$user_array = array(
			'user_login' => strtolower( preg_replace( '/\s+/', '', $user_login ) ),
			'user_pass'  => $password,
			'user_email' => $email,
			'first_name' => $payload['first_name'],
			'last_name'  => $payload['last_name'],
			'role' => $role
		);
		$user_role = 'subscriber' === $role ? 'instructor' : 'student';
		wp_insert_user( $user_array );

		$user_data = get_user_by( 'email', $email );
		// after registration notify admin
		do_action( "academy/admin/after_register_{$user_role}", $user_data->ID );

		if ( $user_data ) {
			if ( wp_check_password( $password, $user_data->user_pass, $user_data->ID ) ) {
				$this->set_user_auth_cookie( $user_data );
				do_action(
					"academy/shortcode/after_{$user_role}_registration",
					$user_data->ID
				);
				wp_send_json_success( __( 'You are registered. Successfully logged in.', 'academy-pro' ) );
			}
		}
		wp_send_json_error( __( 'Sorry, Something went wrong!', 'academy-pro' ) );
	}

	public function google_login() {
		$payload = Sanitizer::sanitize_payload([
			'id_token' => 'string',
			'is_register' => 'boolean',
			'role' => 'string'
		], $_POST); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		$client = new Google_Client( [ 'client_id' => \Academy\Helper::get_settings( 'google_client_id' ) ] );
		$verify_token = $client->verifyIdToken( $payload['id_token'] );
		if ( ! $verify_token || ! $verify_token['email_verified'] ) {
			wp_send_json_error( __( 'Invalid Authorization', 'academy-pro' ) );
		}
		$email = $verify_token['email'];
		$name = $verify_token['name'];
		$role = $payload['role'];

		$user_data = get_user_by( 'email', $email );
		// Login
		if ( ! empty( $user_data ) && false !== $user_data ) {
			$this->set_user_auth_cookie( $user_data );

			$message = __( 'Successfully logged in.', 'academy-pro' );
			if ( $payload['is_register'] ) {
				$message = __( 'You are already registered. Successfully logged in.', 'academy-pro' );
			}
			wp_send_json_success( $message );
		}

		// Register
		if ( ! get_option( 'users_can_register' ) ) {
			wp_send_json_error([
				esc_html__(
					'Sorry, Admin disabled new user registration',
					'academy-pro'
				),
			]);
		}

		if ( 'academy_student' !== $role && 'subscriber' !== $role ) {
			wp_send_json_error([
				esc_html__(
					'Registration Failed. Please try again later',
					'academy-pro'
				),
			]);
		}

		$password   = wp_generate_password( 12, true, false );
		$user_login = $name;
		if ( username_exists( $name ) ) {
			// Generate something unique to append to the username in case of a conflict with another user.
			$suffix     = '-' . zeroise( wp_rand( 0, 9999 ), 4 );
			$name      .= $suffix;
			$user_login = $name;
		}
		$name_array = explode( ' ', $name );
		$user_array = array(
			'user_login' => strtolower( preg_replace( '/\s+/', '', $user_login ) ),
			'user_pass'  => $password,
			'user_email' => $email,
			'first_name' => $name_array[0],
			'last_name'  => $name_array[1],
			'role' => $role
		);
		$user_role = 'subscriber' === $role ? 'instructor' : 'student';

		$user_id = wp_insert_user( $user_array );
		$user_data = get_user_by( 'ID', $user_id );
		// after registration notify admin
		do_action( "academy/admin/after_register_{$user_role}", $user_id );

		if ( $user_data ) {
			if ( wp_check_password( $password, $user_data->user_pass, $user_data->ID ) ) {
				if ( 'subscriber' === $role ) {
					$user_data->add_role( 'academy_student' );
				}
				$this->set_user_auth_cookie( $user_data );
				do_action(
					"academy/shortcode/after_{$user_role}_registration",
					$user_id
				);
				wp_send_json_success( __( 'You are registered. Successfully logged in.', 'academy-pro' ) );
			}
		}
		wp_send_json_error( __( 'Sorry, Something went wrong!', 'academy-pro' ) );
	}

	private function set_user_auth_cookie( $user_data ) {
		$user_ID = $user_data->ID;
		wp_set_auth_cookie( $user_ID );
		wp_set_current_user( $user_ID, $user_data->user_login );

		if ( 'academy_student' === $user_data->roles[0] ) {
			update_user_meta( $user_ID, 'is_academy_student', \Academy\Helper::get_time() );
		}

		if ( 'subscriber' === $user_data->roles[0] ) {
			update_user_meta( $user_ID, 'is_academy_instructor', \Academy\Helper::get_time() );
			update_user_meta( $user_ID, 'academy_instructor_status', apply_filters( 'academy/admin/registration_instructor_status', 'pending' ) );
		}
		wp_new_user_notification( $user_ID, null, 'both' );
		do_action( 'wp_login', $user_data->user_login, $user_data );
	}

}
