<?php
namespace AcademyProEmail\Classes;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class EmailVerify {
	public function show_verify_email_message() {
		// Show Message
		$status = get_transient( 'academy_verify_email_status' );
		if ( $status ) {
			$message = __( 'Oops! Your email verification failed. Please try again or contact support for assistance.', 'academy-pro' );
			// message
			if ( 'success' === $status ) {
				$message = __( 'Congratulations! Your email has been successfully verified.', 'academy-pro' );
			}
			?>
			<div class="academy-verify-registration academy-verify-registration--<?php echo 'success' === $status ? 'success' : 'error'; ?>">
				<?php
					echo esc_html( $message );
				?>
			</div>
			<?php
			delete_transient( 'academy_verify_email_status' );
		}
		return false;
	}
	public function verify_email_address() {
		// verify email
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		if ( isset( $_GET['nonce'], $_GET['email'] ) && wp_verify_nonce( $_GET['nonce'], 'academy_email_verification_' . $_GET['email'] ) && ! is_user_logged_in() ) {
			global $wpdb;
			$verify_status = 'failed';

			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$email = isset( $_GET['email'] ) ? sanitize_email( wp_unslash( $_GET['email'] ) ) : '';
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : '';
			$redirect_url = isset( $_GET['redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) : \Academy\Helper::get_page_permalink( 'frontend_dashboard_page' );
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->users} WHERE user_email = %s AND user_activation_key = %s", $email, $token ) );
			if ( $user ) {
				update_user_meta( $user->ID, 'academy_email_verified', true );
				$update_user_args = array(
					'ID' => $user->ID,
					'user_activation_key' => ''
				);
				if ( get_user_meta( $user->ID, 'is_academy_student' ) ) {
					$update_user_args['role'] = 'academy_student';
				}
				wp_update_user( $update_user_args );
				$verify_status = 'success';
				// Log in the user
				if ( $user ) {
					wp_set_current_user( $user->ID, $user->user_login );
					wp_set_auth_cookie( $user->ID );
				}
				// dispatch email event
				if ( get_user_meta( $user->ID, 'is_academy_student' ) ) {
					if ( apply_filters( 'academy/is_allow_new_student_notification', true ) ) {
						wp_new_user_notification( $user->ID, null, 'both' );
					} else {
						do_action( 'academy_pro_email/after_verify_student_registration', $user->ID );
					}
				} elseif ( get_user_meta( $user->ID, 'is_academy_instructor' ) ) {
					if ( apply_filters( 'academy/is_allow_new_instructor_notification', true ) ) {
						wp_new_user_notification( $user->ID, null, 'both' );
					} else {
						do_action( 'academy_pro_email/after_verify_instructor_registration', $user->ID );
					}
				}
			}//end if
			set_transient( 'academy_verify_email_status', $verify_status, MINUTE_IN_SECONDS );
			wp_safe_redirect( $redirect_url );
			exit;
		}//end if
		return false;
	}
	public function email_verification_registration( $user_data, $role ) {
		// Generate a verification token
		$verification_token = md5( uniqid() );
		$user_data['user_activation_key'] = $verification_token;
		$user_id = wp_insert_user( $user_data );
		if ( $user_id ) {
			// Store Verification token to verify user
			update_user_meta( $user_id, 'academy_email_verified', false );
			// if has role then it will be student
			if ( 'student' === $role ) {
				update_user_meta( $user_id, 'is_academy_student', \Academy\Helper::get_time() );
			} elseif ( 'instructor' === $role ) {
				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' ) );
			}
			// Prepare email Template
			$user_name = $user_data['user_login'];
			$user_email = $user_data['user_email'];
			$site_url = site_url();
			$query_args = array(
				'email' => $user_email,
				'token' => $verification_token,
				'nonce'  => wp_create_nonce( 'academy_email_verification_' . $user_email ),
			);
			// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
			if ( isset( $_POST['redirect_to'] ) && ! empty( $_POST['redirect_to'] ) ) {
				// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
				$query_args['redirect_to'] = sanitize_text_field( $_POST['redirect_to'] );
			}
			$verify_link = add_query_arg( $query_args, \Academy\Helper::get_page_permalink( 'frontend_dashboard_page' ) );

			$settings = \AcademyProEmail\Admin\Settings::get_settings_saved_data();
			$email_verify_settings = $settings['email_verify'];
			$student     = get_userdata( $user_id );
			$site_url    = get_bloginfo( 'url' );
			$site_name   = get_bloginfo( 'name' );
			$user_display_name = $student->display_name;
			$user_email = $student->user_email;

			$subject = str_replace(
				[ '{user_display_name}', '{site_title}', '{site_url}' ],
				[ $user_display_name, $site_name, $site_url ],
				$email_verify_settings['email_subject']
			);
			$footer = $settings['footer_text'];
			$email_type = $settings['email_content_type'];
			if ( 'plainText' === $email_type ) {
				$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
				$body = strip_tags( $email_verify_settings['email_heading'], '<br>' ) . "\n" . strip_tags( $email_verify_settings['email_content'], '<br>' ) . "\n" . strip_tags( $footer, '<br>' );
			} else {
				$headers = array( 'Content-Type: text/html; charset=UTF-8' );
				ob_start();
				\AcademyPro\Helper::get_template('email/student-registration-admin.php', array(
					'heading' => $email_verify_settings['email_heading'],
					'content' => $email_verify_settings['email_content'],
					'footer' => $footer,
				));
				$body = ob_get_clean();
			}

			$body = str_replace(
				[ '{verify_email_link}', '{user_display_name}', '{site_title}', '{site_url}' ],
				[ $verify_link, $user_display_name, $site_name, $site_url ],
				$body
			);

			$mail = new \AcademyProEmail\Email\Mail();
			$mail->send_mail( $user_email, $subject, $body, $headers );

			wp_send_json_success([
				'message'           => __( 'Thank you for submitting registration form. Please check your email inbox for a verification email from us. In order to complete your registration, please click the verification link provided in the email. If you do not receive the email within a few minutes, please check your spam or junk folder. If you still do not see the email, please contact us for assistance.', 'academy-pro' ),
				'redirect_url'      => false,
			]);
		}//end if
		wp_send_json_error( [ __( 'Failed to registered.', 'academy-pro' ) ] );
	}

	public function restrict_unverified_users_login( $user_login ) {
		$user = get_user_by( is_email( $user_login ) ? 'email' : 'login', $user_login );
		if ( ! $user || ! metadata_exists( 'user', $user->ID, 'academy_email_verified' ) ) {
			return $user_login;
		}
		// Check if the user's email is verified
		$email_verified = get_user_meta( $user->ID, 'academy_email_verified', true );
		if ( ! $email_verified ) {
			// If the email is not verified, prevent login and show an error message
			new \WP_Error( 'email_not_verified', __( 'Please verify your email before logging in.', 'academy-pro' ) );
			wp_send_json_error( __( 'Please verify your email before logging in.', 'academy-pro' ) );
		}
		return $user_login;
	}
}
